diff options
Diffstat (limited to 'asdc-controller/src/test/java/org/onap')
35 files changed, 3453 insertions, 0 deletions
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/ASDCPojoTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/ASDCPojoTest.java new file mode 100644 index 0000000000..354b6dac3c --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/ASDCPojoTest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + +import org.junit.Test; +import org.onap.so.asdc.client.FinalDistributionStatusMessage; +import org.onap.so.asdc.client.test.emulators.ArtifactInfoImpl; +import org.onap.so.asdc.client.test.emulators.DistributionClientEmulator; +import org.onap.so.asdc.client.test.emulators.JsonStatusData; +import org.onap.so.asdc.client.test.emulators.JsonVfModuleMetaData; +import org.onap.so.asdc.client.test.emulators.NotificationDataImpl; +import org.onap.so.asdc.client.test.emulators.ResourceInfoImpl; +import org.onap.so.asdc.installer.VfResourceStructure; + +import com.openpojo.reflection.PojoClass; +import com.openpojo.reflection.impl.PojoClassFactory; +import com.openpojo.validation.Validator; +import com.openpojo.validation.ValidatorBuilder; +import com.openpojo.validation.test.impl.GetterTester; +import com.openpojo.validation.test.impl.SetterTester; + +public class ASDCPojoTest { + @Test + public void pojoStructure() { + test(PojoClassFactory.getPojoClass(FinalDistributionStatusMessage.class)); + test(PojoClassFactory.getPojoClass(ArtifactInfoImpl.class)); + test(PojoClassFactory.getPojoClass(NotificationDataImpl.class)); + test(PojoClassFactory.getPojoClass(JsonVfModuleMetaData.class)); + test(PojoClassFactory.getPojoClass(ResourceInfoImpl.class)); + test(PojoClassFactory.getPojoClass(DistributionClientEmulator.class)); + test(PojoClassFactory.getPojoClass(JsonStatusData.class)); + test(PojoClassFactory.getPojoClass(VfResourceStructure.class)); + } + + private void test(PojoClass pojoClass) { + Validator validator = ValidatorBuilder.create() + .with(new SetterTester()) + .with(new GetterTester()) + .build(); + validator.validate(pojoClass); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/BaseTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/BaseTest.java new file mode 100644 index 0000000000..9a7240c830 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/BaseTest.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + +import static org.mockito.Mockito.reset; + +import org.junit.After; +import org.junit.runner.RunWith; +import org.onap.so.asdc.installer.ToscaResourceStructure; +import org.onap.so.asdc.installer.VfResourceStructure; +import org.onap.so.asdc.installer.heat.ToscaResourceInstaller; +import org.onap.so.asdc.tenantIsolation.SpringContextHelper; +import org.onap.so.asdc.tenantIsolation.WatchdogDistribution; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +@ContextConfiguration(classes = SpringContextHelper.class, initializers = ConfigFileApplicationContextInitializer.class) +@AutoConfigureWireMock(port = 0) +public abstract class BaseTest { + @MockBean + protected VfResourceStructure vfResourceStructure; + @MockBean + protected ToscaResourceStructure toscaResourceStruct; + @SpyBean + protected WatchdogDistribution watchdogDistributionSpy; + @SpyBean + protected ToscaResourceInstaller toscaInstaller; + + @Value("${wiremock.server.port}") + protected String wireMockPort; + + @After + public void after() { + reset(vfResourceStructure); + reset(toscaResourceStruct); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedCatalogDbConfig.java b/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedCatalogDbConfig.java new file mode 100644 index 0000000000..f7e678731e --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedCatalogDbConfig.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; +import ch.vorburger.exec.ManagedProcessException; +import ch.vorburger.mariadb4j.DBConfigurationBuilder; +import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; +import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.Profile; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +@Configuration +@Profile({"test"}) +@EnableTransactionManagement +@EnableJpaRepositories( + entityManagerFactoryRef = "entityManagerFactory", + basePackages = {"org.onap.so.db.catalog.data.repository"} + ) +public class EmbeddedCatalogDbConfig { + + @Bean + MariaDB4jSpringService mariaDB4jSpringService() { + return new MariaDB4jSpringService(); + } + + @Primary + @Bean(name = "dataSource") + DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService, + @Value("${mariaDB4j.databaseName}") String databaseName, + @Value("${spring.datasource.username}") String datasourceUsername, + @Value("${spring.datasource.password}") String datasourcePassword, + @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { + //Create our database with default root user and no password + mariaDB4jSpringService.getDB().createDB(databaseName); + + DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration(); + + return DataSourceBuilder + .create() + .username(datasourceUsername) + .password(datasourcePassword) + .url(config.getURL(databaseName)) + .driverClassName(datasourceDriver) + .build(); + } + + + @Primary + @Bean(name = "entityManagerFactory") + public LocalContainerEntityManagerFactoryBean + entityManagerFactory( + EntityManagerFactoryBuilder builder, + @Qualifier("dataSource") DataSource dataSource + ) { + return builder + .dataSource(dataSource) + .packages("org.onap.so.db.catalog.beans") + .persistenceUnit("catalogDB") + .build(); + } + + @Primary + @Bean(name = "transactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("entityManagerFactory") EntityManagerFactory + entityManagerFactory + ) { + return new JpaTransactionManager(entityManagerFactory); + } + +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedRequestDbConfig.java b/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedRequestDbConfig.java new file mode 100644 index 0000000000..6d1bfcdb8f --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedRequestDbConfig.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; +import ch.vorburger.exec.ManagedProcessException; +import ch.vorburger.mariadb4j.DBConfigurationBuilder; +import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.Profile; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +@Configuration +@Profile({"test"}) +@EnableTransactionManagement +@EnableJpaRepositories( + entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager", + basePackages = { "org.onap.so.db.request.data.repository" } + ) +public class EmbeddedRequestDbConfig { + + @Bean + MariaDB4jSpringService mariaDB4jSpringService() { + return new MariaDB4jSpringService(); + } + + + @Bean(name = "requestDataSource") + @ConfigurationProperties(prefix = "request.datasource") + DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService, + @Value("${mariaDB4j.databaseName2}") String databaseName, + @Value("${spring.datasource.username}") String datasourceUsername, + @Value("${spring.datasource.password}") String datasourcePassword, + @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { + //Create our database with default root user and no password + mariaDB4jSpringService.getDB().createDB(databaseName); + + DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration(); + + return DataSourceBuilder + .create() + .username(datasourceUsername) + .password(datasourcePassword) + .url(config.getURL(databaseName)) + .driverClassName(datasourceDriver) + .build(); + } + + + @Bean(name = "requestEntityManagerFactory") + public LocalContainerEntityManagerFactoryBean + entityManagerFactory( + EntityManagerFactoryBuilder builder, + @Qualifier("requestDataSource") DataSource dataSource + ) { + return builder + .dataSource(dataSource) + .packages("org.onap.so.db.request.beans") + .persistenceUnit("requestDB") + .build(); + } + + + @Bean(name = "requestTransactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("requestEntityManagerFactory") EntityManagerFactory + entityManagerFactory + ) { + return new JpaTransactionManager(entityManagerFactory); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java b/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java new file mode 100644 index 0000000000..4298f9c5b5 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + +import org.onap.so.db.request.data.repository.InfraActiveRequestsRepositoryImpl; +import org.onap.so.requestsdb.RequestsDBHelper; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.ComponentScan.Filter; +import org.springframework.context.annotation.FilterType; +import org.springframework.context.annotation.Profile; + +@SpringBootApplication +@Profile("test") +@ComponentScan(basePackages = {"org.onap.so.asdc"}, excludeFilters = { + @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class), + @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = RequestsDBHelper.class), + @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = InfraActiveRequestsRepositoryImpl.class) }) +public class TestApplication { + public static void main(String... args) { + SpringApplication.run(TestApplication.class, args); + System.getProperties().setProperty("mso.db", "MARIADB"); + System.getProperties().setProperty("server.name", "Springboot"); + System.getProperties().setProperty("mso.config.path", "src/test/resources/"); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCConfigurationTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCConfigurationTest.java new file mode 100644 index 0000000000..ce8b664bda --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCConfigurationTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + + + +import static org.junit.Assert.assertTrue; + +import javax.transaction.Transactional; + +import org.junit.Test; +import org.onap.so.asdc.BaseTest; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * THis class tests the ASDC Controller by using the ASDC Mock CLient + * + * + */ +public class ASDCConfigurationTest extends BaseTest { + + @Autowired + private ASDCConfiguration config; + + @Test + @Transactional + public void testInitASDCConfiguration() throws Exception { + assertTrue("msopreist".equals(config.getUser())); + assertTrue("msoasdc-id-local".equals(config.getConsumerGroup())); + assertTrue("msoasdc-id-local".equals(config.getConsumerID())); + assertTrue("Pre-IST".equals(config.getEnvironmentName())); + assertTrue("localhost:8443".equals(config.getAsdcAddress())); + assertTrue("msopreist".equals(config.getPassword())); + assertTrue(config.getPollingInterval() == 30); + assertTrue(config.getPollingTimeout() == 30); + assertTrue(config.getRelevantArtifactTypes().size() == config.SUPPORTED_ARTIFACT_TYPES_LIST.size()); + assertTrue(config.getWatchDogTimeout() == 1); + } + +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerTest.java new file mode 100644 index 0000000000..580220aabb --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerTest.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.so.asdc.BaseTest; +import org.onap.so.asdc.client.exceptions.ASDCControllerException; +import org.springframework.beans.factory.annotation.Autowired; + +public class ASDCControllerTest extends BaseTest { + @Autowired + private ASDCController asdcController; + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void initASDCExceptionTest() throws Exception { + expectedException.expect(ASDCControllerException.class); + + asdcController.changeControllerStatus(ASDCControllerStatus.IDLE); + + try { + asdcController.initASDC(); + } finally { + asdcController.closeASDC(); + } + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCElementInfoTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCElementInfoTest.java new file mode 100644 index 0000000000..fec3ae6362 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCElementInfoTest.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.onap.so.asdc.client; + + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Collections; +import java.util.UUID; + +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.api.notification.IVfModuleMetadata; +import org.onap.so.asdc.client.ASDCConfiguration; +import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; +import org.onap.so.asdc.installer.ASDCElementInfo; +import org.onap.so.asdc.installer.VfModuleStructure; +import org.onap.so.asdc.installer.VfResourceStructure; +import org.onap.so.asdc.installer.IVfModuleData; + +public class ASDCElementInfoTest { + + @Test + public void createASDCElementInfoWithNullParameterTest() { + ASDCElementInfo elementInfoFromNullVfArtifact = ASDCElementInfo.createElementFromVfArtifactInfo(null); + ASDCElementInfo elementInfoFromNullVfModuleStructure = ASDCElementInfo.createElementFromVfModuleStructure(null); + ASDCElementInfo elementInfoFromNullVfResourceStructure = ASDCElementInfo.createElementFromVfResourceStructure(null); + + elementInfoFromNullVfArtifact.addElementInfo(null, null); + elementInfoFromNullVfModuleStructure.addElementInfo(null, "someValue"); + elementInfoFromNullVfResourceStructure.addElementInfo("someKey", null); + + assertEquals(elementInfoFromNullVfArtifact.toString(), ""); + assertEquals(elementInfoFromNullVfModuleStructure.toString(), ""); + assertEquals(elementInfoFromNullVfResourceStructure.toString(), ""); + + assertNotNull(elementInfoFromNullVfArtifact); + assertNotNull(elementInfoFromNullVfModuleStructure); + assertNotNull(elementInfoFromNullVfResourceStructure); + + assertNotNull(ASDCElementInfo.EMPTY_INSTANCE); + + assertEquals(elementInfoFromNullVfArtifact, ASDCElementInfo.EMPTY_INSTANCE); + assertEquals(elementInfoFromNullVfModuleStructure, ASDCElementInfo.EMPTY_INSTANCE); + assertEquals(elementInfoFromNullVfResourceStructure, ASDCElementInfo.EMPTY_INSTANCE); + + assertEquals(ASDCElementInfo.EMPTY_INSTANCE.getType(), ""); + assertEquals(ASDCElementInfo.EMPTY_INSTANCE.toString(), ""); + + assertEquals(elementInfoFromNullVfArtifact.getType(), ASDCElementInfo.EMPTY_INSTANCE.getType()); + assertEquals(elementInfoFromNullVfModuleStructure.getType(), ASDCElementInfo.EMPTY_INSTANCE.getType()); + assertEquals(elementInfoFromNullVfResourceStructure.getType(), ASDCElementInfo.EMPTY_INSTANCE.getType()); + } + + @Test + public void createASDCElementInfoFromVfResourceTest() { + + String resourceInstanceName = "Resource 1"; + + UUID generatedUUID = UUID.randomUUID(); + + INotificationData notificationData = Mockito.mock(INotificationData.class); + IResourceInstance resourceInstance = Mockito.mock(IResourceInstance.class); + + Mockito.when(resourceInstance.getResourceInstanceName()).thenReturn(resourceInstanceName); + Mockito.when(resourceInstance.getResourceInvariantUUID()).thenReturn(generatedUUID.toString()); + + VfResourceStructure vfResourceStructure = new VfResourceStructure(notificationData, resourceInstance); + + ASDCElementInfo elementInfoFromVfResource = ASDCElementInfo.createElementFromVfResourceStructure(vfResourceStructure); + + assertTrue(elementInfoFromVfResource.toString().contains(resourceInstanceName)); + assertTrue(elementInfoFromVfResource.toString().contains(generatedUUID.toString())); + + assertFalse(ASDCConfiguration.VF_MODULES_METADATA.equals(elementInfoFromVfResource.getType())); + assertEquals(ASDCElementInfo.ASDCElementTypeEnum.VNF_RESOURCE.name(), elementInfoFromVfResource.getType()); + + assertFalse(elementInfoFromVfResource.toString().contains("MyInfo1: someValue")); + elementInfoFromVfResource.addElementInfo("MyInfo1", "someValue"); + assertTrue(elementInfoFromVfResource.toString().contains("MyInfo1: someValue")); + } + + @Test + public void createASDCElementInfoFromVfModuleTest() throws ArtifactInstallerException { + + String resourceInstanceName = "Resource 1"; + + UUID generatedUUID = UUID.randomUUID(); + + INotificationData notificationData = Mockito.mock(INotificationData.class); + IResourceInstance resourceInstance = Mockito.mock(IResourceInstance.class); + + Mockito.when(resourceInstance.getResourceInstanceName()).thenReturn(resourceInstanceName); + Mockito.when(resourceInstance.getResourceInvariantUUID()).thenReturn(generatedUUID.toString()); + + VfResourceStructure vfResourceStructure = new VfResourceStructure(notificationData, resourceInstance); + + // Create module structure now + + String vfModuleModelName = "Module Model XYZ"; + + UUID generatedUUIDForModule = UUID.randomUUID(); + + IVfModuleData moduleMetadata = Mockito.mock(IVfModuleData.class); + Mockito.when(moduleMetadata.getVfModuleModelName()).thenReturn(vfModuleModelName); + Mockito.when(moduleMetadata.getVfModuleModelInvariantUUID()).thenReturn(generatedUUIDForModule.toString()); + Mockito.when(moduleMetadata.getArtifacts()).thenReturn(Collections.<String> emptyList()); + + VfModuleStructure vfModuleStructure = new VfModuleStructure(vfResourceStructure, moduleMetadata); + + ASDCElementInfo elementInfoFromVfModule = ASDCElementInfo.createElementFromVfModuleStructure(vfModuleStructure); + + assertTrue(elementInfoFromVfModule.toString().contains(vfModuleModelName)); + assertTrue(elementInfoFromVfModule.toString().contains(generatedUUIDForModule.toString())); + + assertFalse(ASDCElementInfo.ASDCElementTypeEnum.VNF_RESOURCE.name().equals(elementInfoFromVfModule.getType())); + assertEquals(ASDCConfiguration.VF_MODULES_METADATA, elementInfoFromVfModule.getType()); + + assertFalse(elementInfoFromVfModule.toString().contains("MyInfo2: someValue")); + elementInfoFromVfModule.addElementInfo("MyInfo2", "someValue"); + assertTrue(elementInfoFromVfModule.toString().contains("MyInfo2: someValue")); + } + + @Test + public void createASDCElementInfoFromArtifact() { + for (String eVal : ASDCConfiguration.SUPPORTED_ARTIFACT_TYPES_LIST) { + String generatedArtifactName = eVal + " 1"; + UUID generatedUUIDForArtifact = UUID.randomUUID(); + + IArtifactInfo artifactInfo = Mockito.mock(IArtifactInfo.class); + Mockito.when(artifactInfo.getArtifactType()).thenReturn(eVal); + Mockito.when(artifactInfo.getArtifactName()).thenReturn(generatedArtifactName); + Mockito.when(artifactInfo.getArtifactUUID()).thenReturn(generatedUUIDForArtifact.toString()); + + ASDCElementInfo elementInfoFromArtifact = ASDCElementInfo.createElementFromVfArtifactInfo(artifactInfo); + + assertTrue(elementInfoFromArtifact.toString().contains(generatedArtifactName)); + assertTrue(elementInfoFromArtifact.toString().contains(generatedUUIDForArtifact.toString())); + + assertFalse(ASDCElementInfo.ASDCElementTypeEnum.VNF_RESOURCE.name().equals(elementInfoFromArtifact.getType())); + assertEquals(eVal, elementInfoFromArtifact.getType()); + + assertFalse(elementInfoFromArtifact.toString().contains("MyInfo3: someValue")); + elementInfoFromArtifact.addElementInfo("MyInfo3", "someValue"); + assertTrue(elementInfoFromArtifact.toString().contains("MyInfo3: someValue")); + } + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCStatusCallBackTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCStatusCallBackTest.java new file mode 100644 index 0000000000..97fa773fd5 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCStatusCallBackTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.api.notification.IStatusData; +import org.onap.sdc.utils.DistributionStatusEnum; +import org.onap.so.asdc.BaseTest; +import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; +import org.onap.so.asdc.client.test.emulators.JsonStatusData; +import org.springframework.beans.factory.annotation.Autowired; + +public class ASDCStatusCallBackTest extends BaseTest { + @Autowired + private ASDCStatusCallBack statusCallback; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void before() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void activateCallbackTest() throws Exception { + JsonStatusData statusData = new JsonStatusData(); + + doNothing().when(toscaInstaller).installTheComponentStatus(isA(JsonStatusData.class)); + + statusCallback.activateCallback(statusData); + + verify(toscaInstaller, times(1)).installTheComponentStatus(statusData); + } + + @Test + public void activateCallbackDoneErrorStatusTest() throws Exception { + IStatusData statusData = mock(IStatusData.class); + + doReturn("distributionId").when(statusData).getDistributionID(); + doReturn("componentName").when(statusData).getComponentName(); + doReturn(DistributionStatusEnum.COMPONENT_DONE_ERROR).when(statusData).getStatus(); + doNothing().when(toscaInstaller).installTheComponentStatus(isA(IStatusData.class)); + + statusCallback.activateCallback(statusData); + + verify(toscaInstaller, times(1)).installTheComponentStatus(statusData); + } + + @Test + public void activateCallbackExceptionTest() throws Exception { + IStatusData statusData = mock(IStatusData.class); + + doReturn("distributionId").when(statusData).getDistributionID(); + doReturn("componentName").when(statusData).getComponentName(); + doReturn(DistributionStatusEnum.COMPONENT_DONE_OK).when(statusData).getStatus(); + doThrow(ArtifactInstallerException.class).when(toscaInstaller).installTheComponentStatus(isA(IStatusData.class)); + + statusCallback.activateCallback(statusData); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/BigDecimalVersionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/BigDecimalVersionTest.java new file mode 100644 index 0000000000..4eb9ed5619 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/BigDecimalVersionTest.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + + +import static org.junit.Assert.assertTrue; +import java.math.BigDecimal; +import org.junit.Test; + +import org.onap.so.asdc.installer.BigDecimalVersion; + + +public class BigDecimalVersionTest { + + @Test + public final void versionCastTest () { + + BigDecimal versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("12.0"); + assertTrue(versionDecimal.equals(new BigDecimal("12.0"))); + assertTrue("12.0".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("12.0"))); + + versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("12.0.2"); + assertTrue(versionDecimal.equals(new BigDecimal("12.02"))); + assertTrue("12.02".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("12.0.2"))); + + versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("10"); + assertTrue(versionDecimal.equals(new BigDecimal("10"))); + assertTrue("10".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("10"))); + + versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("10.1.2.6"); + assertTrue(versionDecimal.equals(new BigDecimal("10.126"))); + assertTrue("10.126".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("10.1.2.6"))); + + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/DistributionStatusMessageTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/DistributionStatusMessageTest.java new file mode 100644 index 0000000000..0c6476ddef --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/DistributionStatusMessageTest.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.sdc.utils.DistributionStatusEnum; + +public class DistributionStatusMessageTest { + + @Test + public void distributionStatusMessageTest() { + String artifactUrl = "artifactUrl"; + String consumerId = "consumerId"; + String distributionId = "distributionId"; + Long timestamp = 123L; + DistributionStatusMessage distributionStatusMessage = new DistributionStatusMessage( + artifactUrl, consumerId, distributionId, DistributionStatusEnum.DEPLOY_OK, timestamp); + + assertEquals(artifactUrl, distributionStatusMessage.getArtifactURL()); + assertEquals(consumerId, distributionStatusMessage.getConsumerID()); + assertEquals(distributionId, distributionStatusMessage.getDistributionID()); + assertEquals(DistributionStatusEnum.DEPLOY_OK, distributionStatusMessage.getStatus()); + assertEquals(123L, distributionStatusMessage.getTimestamp()); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/YamlTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/YamlTest.java new file mode 100644 index 0000000000..ed761c7f4d --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/YamlTest.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.onap.so.asdc.util.YamlEditor; +import org.onap.so.db.catalog.beans.HeatTemplateParam; + + +public class YamlTest { + @Test + public void getYamlResourceTypeTestList() throws Exception { + + InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTest.yaml")); + YamlEditor decoder = new YamlEditor (IOUtils.toByteArray(input)); + List<String> typeList = decoder.getYamlNestedFileResourceTypeList(); + + assertTrue(typeList.size() == 1 && typeList.get(0).equals("file:///my_test.yaml")); + } + + @Test + public void getParameterListTest() throws Exception { + + InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTest.yaml")); + YamlEditor decoder = new YamlEditor (IOUtils.toByteArray(input)); + Set <HeatTemplateParam> paramSet = decoder.getParameterList("123456"); + + assertTrue(paramSet.size() == 5); + + for (HeatTemplateParam param : paramSet) { + if ("ip_port_snmp_manager".equals(param.getParamName()) || "cor_direct_net_name".equals(param.getParamName()) || "cor_direct_net_RT".equals(param.getParamName())) { + + assertTrue(param.isRequired()==false); + } else { + + assertTrue(param.isRequired()==true); + } + + assertTrue("string".equals(param.getParamType())); + } + } + + @Test + public void addParameterListWhenEmptyTest() throws Exception { + + InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTestWithoutParam.yaml")); + YamlEditor decoder = new YamlEditor (IOUtils.toByteArray(input)); + + Set <HeatTemplateParam> newParamSet = new HashSet<>(); + + HeatTemplateParam heatParam1 = new HeatTemplateParam(); + heatParam1.setHeatTemplateArtifactUuid("1"); + heatParam1.setParamName("testos1"); + heatParam1.setParamType("string"); + + HeatTemplateParam heatParam2 = new HeatTemplateParam(); + heatParam2.setHeatTemplateArtifactUuid("2"); + heatParam2.setParamName("testos2"); + heatParam2.setParamType("number"); + + newParamSet.add(heatParam1); + newParamSet.add(heatParam2); + + decoder.addParameterList(newParamSet); + + Set <HeatTemplateParam> paramSet = decoder.getParameterList("123456"); + assertTrue(paramSet.size() == 2); + + assertTrue(decoder.encode().contains("testos1")); + assertTrue(decoder.encode().contains("string")); + assertTrue(decoder.encode().contains("testos2")); + assertTrue(decoder.encode().contains("number")); + } + + @Test + public void addParameterListTest() throws Exception { + + InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTest.yaml")); + YamlEditor decoder = new YamlEditor (IOUtils.toByteArray(input)); + + Set <HeatTemplateParam> newParamSet = new HashSet<>(); + + HeatTemplateParam heatParam1 = new HeatTemplateParam(); + heatParam1.setHeatTemplateArtifactUuid("1"); + heatParam1.setParamName("testos1"); + heatParam1.setParamType("string"); + + HeatTemplateParam heatParam2 = new HeatTemplateParam(); + heatParam2.setHeatTemplateArtifactUuid("2"); + heatParam2.setParamName("testos2"); + heatParam2.setParamType("number"); + + newParamSet.add(heatParam1); + newParamSet.add(heatParam2); + + decoder.addParameterList(newParamSet); + + Set <HeatTemplateParam> paramSet = decoder.getParameterList("123456"); + + assertTrue(paramSet.size() == 7); + + Boolean check1 = Boolean.FALSE; + Boolean check2 = Boolean.FALSE; + + for (HeatTemplateParam param : paramSet) { + if ("ip_port_snmp_manager".equals(param.getParamName()) || "cor_direct_net_name".equals(param.getParamName()) || "cor_direct_net_RT".equals(param.getParamName())) { + assertFalse(param.isRequired()); + } else { + assertTrue(param.isRequired()); + } + + if ("testos1".equals(param.getParamName()) && "string".equals(param.getParamType())) { + check1=Boolean.TRUE; + } + + if ("testos2".equals(param.getParamName()) && "number".equals(param.getParamType())) { + check2=Boolean.TRUE; + } + + } + + assertTrue(check1); + assertTrue(check2); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCControllerExceptionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCControllerExceptionTest.java new file mode 100644 index 0000000000..e2aee6080e --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCControllerExceptionTest.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.exceptions; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; + +import org.junit.Test; + +public class ASDCControllerExceptionTest { + private String exceptionMessage = "test message for exception"; + private String throwableMessage = "separate throwable that caused asdcDownloadException"; + + @Test + public void asdcParametersExceptionTest() { + ASDCControllerException asdcDownloadException = new ASDCControllerException(exceptionMessage); + + Exception expectedException = new Exception(exceptionMessage); + + assertThat(asdcDownloadException, sameBeanAs(expectedException)); + } + + @Test + public void asdcParametersExceptionThrowableTest() { + Throwable throwableCause = new Throwable(throwableMessage); + ASDCControllerException asdcDownloadException = new ASDCControllerException(exceptionMessage, throwableCause); + + Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage)); + + assertThat(asdcDownloadException, sameBeanAs(expectedException)); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCDownloadExceptionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCDownloadExceptionTest.java new file mode 100644 index 0000000000..98deb52a08 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCDownloadExceptionTest.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.exceptions; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; + +import org.junit.Test; + +public class ASDCDownloadExceptionTest { + private String exceptionMessage = "test message for exception"; + private String throwableMessage = "separate throwable that caused asdcDownloadException"; + + @Test + public void asdcDownloadExceptionTest() { + ASDCDownloadException asdcDownloadException = new ASDCDownloadException(exceptionMessage); + + Exception expectedException = new Exception(exceptionMessage); + + assertThat(asdcDownloadException, sameBeanAs(expectedException)); + } + + @Test + public void asdcDownloadExceptionThrowableTest() { + Throwable throwableCause = new Throwable(throwableMessage); + ASDCDownloadException asdcDownloadException = new ASDCDownloadException(exceptionMessage, throwableCause); + + Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage)); + + assertThat(asdcDownloadException, sameBeanAs(expectedException)); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCParametersExceptionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCParametersExceptionTest.java new file mode 100644 index 0000000000..bac05bd47c --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCParametersExceptionTest.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.exceptions; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; + +import org.junit.Test; + +public class ASDCParametersExceptionTest { + private String exceptionMessage = "test message for exception"; + private String throwableMessage = "separate throwable that caused asdcDownloadException"; + + @Test + public void asdcParametersExceptionTest() { + ASDCParametersException asdcDownloadException = new ASDCParametersException(exceptionMessage); + + Exception expectedException = new Exception(exceptionMessage); + + assertThat(asdcDownloadException, sameBeanAs(expectedException)); + } + + @Test + public void asdcParametersExceptionThrowableTest() { + Throwable throwableCause = new Throwable(throwableMessage); + ASDCParametersException asdcDownloadException = new ASDCParametersException(exceptionMessage, throwableCause); + + Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage)); + + assertThat(asdcDownloadException, sameBeanAs(expectedException)); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java new file mode 100644 index 0000000000..f2227908f5 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.exceptions; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; + +import org.junit.Test; + +public class ArtifactInstallerExceptionTest { + private String exceptionMessage = "test message for exception"; + private String throwableMessage = "separate throwable that caused asdcDownloadException"; + + @Test + public void asdcParametersExceptionTest() { + ArtifactInstallerException asdcDownloadException = new ArtifactInstallerException(exceptionMessage); + + Exception expectedException = new Exception(exceptionMessage); + + assertThat(asdcDownloadException, sameBeanAs(expectedException)); + } + + @Test + public void asdcParametersExceptionThrowableTest() { + Throwable throwableCause = new Throwable(throwableMessage); + ArtifactInstallerException asdcDownloadException = new ArtifactInstallerException(exceptionMessage, throwableCause); + + Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage)); + + assertThat(asdcDownloadException, sameBeanAs(expectedException)); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImplTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImplTest.java new file mode 100644 index 0000000000..3dc323559d --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImplTest.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.mockito.Mock; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.so.asdc.BaseTest; + +public class ArtifactInfoImplTest extends BaseTest { + @Mock + private IArtifactInfo iArtifactInfo; + + @Test + public void convertToArtifactInfoImplTest() { + List<IArtifactInfo> list = new ArrayList<IArtifactInfo>(); + list.add(iArtifactInfo); + assertEquals(1, ArtifactInfoImpl.convertToArtifactInfoImpl(list).size()); + } + + @Test + public void convertToArtifactInfoImplNullListTest() { + assertTrue(ArtifactInfoImpl.convertToArtifactInfoImpl(null).isEmpty()); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulatorTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulatorTest.java new file mode 100644 index 0000000000..38c2564241 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulatorTest.java @@ -0,0 +1,178 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.onap.sdc.api.consumer.IDistributionStatusMessage; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.impl.DistributionClientDownloadResultImpl; +import org.onap.sdc.impl.DistributionClientResultImpl; +import org.onap.sdc.utils.DistributionActionResultEnum; +import org.onap.sdc.utils.DistributionStatusEnum; +import org.onap.so.asdc.client.ASDCConfiguration; +import org.onap.so.asdc.client.ASDCNotificationCallBack; +import org.onap.so.asdc.client.ASDCStatusCallBack; +import org.onap.so.asdc.client.DistributionStatusMessage; + +public class DistributionClientEmulatorTest { + + private DistributionClientEmulator distClientEmulator; + + @Before + public void before() { + distClientEmulator = new DistributionClientEmulator(); + } + + @Test + public void getDistributionMessageReceived() { + List<IDistributionStatusMessage> receivedMessages = distClientEmulator.getDistributionMessageReceived(); + assertEquals(new LinkedList<>(), receivedMessages); + + IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456); + distClientEmulator.sendDeploymentStatus(message); + assertEquals(message, receivedMessages.get(0)); + + IDistributionStatusMessage message2 = new DistributionStatusMessage("testArtifactUrl2", "testConsumerId2", "testDistributionId2", DistributionStatusEnum.DOWNLOAD_OK, 1234567); + distClientEmulator.sendDeploymentStatus(message2); + assertEquals(message2, receivedMessages.get(1)); + } + + @Test + public void sendDeploymentStatusPrimary() { + IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456); + IDistributionClientResult result = distClientEmulator.sendDeploymentStatus(message); + IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0)); + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } + + @Test + public void sendDeploymentStatusSecondary() { + IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456); + IDistributionClientResult result = distClientEmulator.sendDeploymentStatus(message, "test"); + IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0)); + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } + + @Test + public void sendDownloadStatusPrimary() { + IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456); + IDistributionClientResult result = distClientEmulator.sendDownloadStatus(message); + IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0)); + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } + + @Test + public void sendDownloadStatusSecondary() { + IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456); + IDistributionClientResult result = distClientEmulator.sendDownloadStatus(message, "test"); + IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0)); + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } + + @Test + public void initPrimary() { + IDistributionClientResult result = distClientEmulator.init(new ASDCConfiguration(), new ASDCNotificationCallBack()); + IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } + + @Test + public void initSecondary() { + IDistributionClientResult result = distClientEmulator.init(new ASDCConfiguration(), new ASDCNotificationCallBack(), new ASDCStatusCallBack()); + IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } + + @Test + public void start() { + IDistributionClientResult result = distClientEmulator.start(); + IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } + + @Test + public void stop() { + IDistributionClientResult result = distClientEmulator.stop(); + IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } + + @Test + public void updateConfiguration() { + IDistributionClientResult result = distClientEmulator.updateConfiguration(new ASDCConfiguration()); + IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } + + @Test + public void getResourcePath() { + String testResourcePath = "testResourcePath"; + distClientEmulator = new DistributionClientEmulator(testResourcePath); + assertEquals(testResourcePath, distClientEmulator.getResourcePath()); + } + + @Test + public void setResourcePath() { + String testResourcePath = "testResourcePath"; + distClientEmulator.setResourcePath(testResourcePath); + assertEquals(testResourcePath, distClientEmulator.getResourcePath()); + } + + @Test + public void downloadSuccess() throws IOException { + ArtifactInfoImpl info = new ArtifactInfoImpl(); + info.setArtifactURL("mso.json"); + info.setArtifactName("testArtifactName"); + + distClientEmulator.setResourcePath("src/test/resources/"); + + IDistributionClientDownloadResult result = distClientEmulator.download(info); + + byte[] expectedInputStream = Files.readAllBytes(Paths.get(distClientEmulator.getResourcePath() + info.getArtifactURL())); + IDistributionClientDownloadResult expectedResult = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name(), info.getArtifactName(), expectedInputStream); + + assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult()); + assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult()); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonStatusDataTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonStatusDataTest.java new file mode 100644 index 0000000000..5e2f1ad828 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonStatusDataTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class JsonStatusDataTest { + + @Test + public void instantiateNotifFromJsonFileTest() { + JsonStatusData jsonStatusData = new JsonStatusData(); + JsonStatusData returnedVal = null; + try { + returnedVal = jsonStatusData.instantiateNotifFromJsonFile(jsonStatusData.getArtifactURL()); + } catch (Exception ex) { + + } + assertEquals(returnedVal, null); + } + + @Test + public void setGetAttributes() + { + JsonStatusData jsonStatusData = new JsonStatusData(); + jsonStatusData.setAttribute("test","test"); + jsonStatusData.getStatus(); + jsonStatusData.getTimestamp(); + jsonStatusData.getComponentName(); + jsonStatusData.getConsumerID(); + jsonStatusData.getDistributionID(); + String errReason = jsonStatusData.getErrorReason(); + assertEquals(errReason,"MSO FAILURE"); + + } + + + +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaDataTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaDataTest.java new file mode 100644 index 0000000000..6da3a2c18c --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaDataTest.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; + +import org.junit.Test; + +public class JsonVfModuleMetaDataTest { + + @Test + public void attributesMapTest() { + JsonVfModuleMetaData vfModuleMetadata = new JsonVfModuleMetaData(); + vfModuleMetadata.setAttribute("vfModuleModelDescription", "vfModuleModelDescription"); + vfModuleMetadata.setAttribute("vfModuleModelInvariantUUID", "vfModuleModelInvariantUUID"); + vfModuleMetadata.setAttribute("vfModuleModelCustomizationUUID", "vfModuleModelCustomizationUUID"); + vfModuleMetadata.setAttribute("vfModuleModelName", "vfModuleModelName"); + vfModuleMetadata.setAttribute("vfModuleModelUUID", "vfModuleModelUUID"); + vfModuleMetadata.setAttribute("vfModuleModelVersion", "vfModuleModelVersion"); + vfModuleMetadata.setAttribute("isBase", true); + + assertEquals("vfModuleModelDescription", vfModuleMetadata.getVfModuleModelDescription()); + assertEquals("vfModuleModelInvariantUUID", vfModuleMetadata.getVfModuleModelInvariantUUID()); + assertEquals("vfModuleModelCustomizationUUID", vfModuleMetadata.getVfModuleModelCustomizationUUID()); + assertEquals("vfModuleModelName", vfModuleMetadata.getVfModuleModelName()); + assertEquals("vfModuleModelUUID", vfModuleMetadata.getVfModuleModelUUID()); + assertEquals("vfModuleModelVersion", vfModuleMetadata.getVfModuleModelVersion()); + assertEquals(true, vfModuleMetadata.isBase()); + assertEquals(null, vfModuleMetadata.getArtifacts()); + assertEquals(new HashMap<String, String>(), vfModuleMetadata.getProperties()); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/NotificationDataImplTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/NotificationDataImplTest.java new file mode 100644 index 0000000000..b1524e015f --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/NotificationDataImplTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.mockito.Mock; +import org.onap.so.asdc.BaseTest; +import org.springframework.beans.factory.annotation.Autowired; + +public class NotificationDataImplTest extends BaseTest { + @Autowired + private NotificationDataImpl notificationDataImpl; + + @Mock + private ArtifactInfoImpl artifactInfoImpl; + + private static final String NOTIFICATION_DATA_IMPL_STRING = "NotificationDataImpl [distributionID=distributionID, serviceName=serviceName, " + + "serviceVersion=serviceVersion, serviceUUID=serviceUUID, serviceDescription=serviceDescription, " + + "serviceInvariantUUID=serviceInvariantUUID, resources=null, serviceArtifacts=[artifactInfoImpl], workloadContext=workloadContext]"; + + @Test + public void toStringTest() { + List<ArtifactInfoImpl> relevantServiceArtifacts = new ArrayList<ArtifactInfoImpl>(); + relevantServiceArtifacts.add(artifactInfoImpl); + notificationDataImpl.setDistributionID("distributionID"); + notificationDataImpl.setServiceName("serviceName"); + notificationDataImpl.setServiceVersion("serviceVersion"); + notificationDataImpl.setServiceDescription("serviceDescription"); + notificationDataImpl.setServiceUUID("serviceUUID"); + notificationDataImpl.setServiceInvariantUUID("serviceInvariantUUID"); + notificationDataImpl.setWorkloadContext("workloadContext"); + notificationDataImpl.setServiceArtifacts(relevantServiceArtifacts); + + assertEquals(NOTIFICATION_DATA_IMPL_STRING, notificationDataImpl.toString()); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImplTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImplTest.java new file mode 100644 index 0000000000..423661770b --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImplTest.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.mockito.Mock; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.so.asdc.BaseTest; + +public class ResourceInfoImplTest extends BaseTest { + @Mock + private IResourceInstance iResourceInstance; + + @Test + public void convertToJsonContainerTest() { + List<IResourceInstance> resources = new ArrayList<IResourceInstance>(); + resources.add(iResourceInstance); + ResourceInfoImpl.convertToJsonContainer(resources); + + assertEquals(1, ResourceInfoImpl.convertToJsonContainer(resources).size()); + } + + @Test + public void convertToJsonContainerNullListTest() { + assertTrue(ResourceInfoImpl.convertToJsonContainer(null).isEmpty()); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java new file mode 100644 index 0000000000..1944c3af73 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.rest; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.transaction.Transactional; +import javax.ws.rs.core.Response; + +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Spy; +import org.onap.so.asdc.BaseTest; +import org.onap.so.asdc.client.test.emulators.DistributionClientEmulator; +import org.onap.so.asdc.client.test.emulators.NotificationDataImpl; +import org.onap.so.db.catalog.beans.AllottedResource; +import org.onap.so.db.catalog.beans.AllottedResourceCustomization; +import org.onap.so.db.catalog.beans.CollectionResource; +import org.onap.so.db.catalog.beans.CollectionResourceCustomization; +import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization; +import org.onap.so.db.catalog.beans.ConfigurationResource; +import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization; +import org.onap.so.db.catalog.beans.InstanceGroup; +import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization; +import org.onap.so.db.catalog.beans.NetworkResource; +import org.onap.so.db.catalog.beans.NetworkResourceCustomization; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.ServiceProxyResource; +import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization; +import org.onap.so.db.catalog.beans.ServiceRecipe; +import org.onap.so.db.catalog.beans.ToscaCsar; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization; +import org.onap.so.db.catalog.data.repository.AllottedResourceCustomizationRepository; +import org.onap.so.db.catalog.data.repository.AllottedResourceRepository; +import org.onap.so.db.catalog.data.repository.CollectionResourceInstanceGroupCustomizationRepository; +import org.onap.so.db.catalog.data.repository.CollectionResourceRepository; +import org.onap.so.db.catalog.data.repository.ConfigurationResourceRepository; +import org.onap.so.db.catalog.data.repository.InstanceGroupRepository; +import org.onap.so.db.catalog.data.repository.NetworkResourceRepository; +import org.onap.so.db.catalog.data.repository.ServiceProxyResourceRepository; +import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.db.catalog.data.repository.VnfcInstanceGroupCustomizationRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ASDCRestInterfaceTest extends BaseTest { + //ASDC Controller writes to this path + static { + System.setProperty("mso.config.path", "src/test/resources/"); + } + + + @Autowired + private AllottedResourceRepository allottedRepo; + + @Autowired + private ServiceRepository serviceRepo; + + @Autowired + private NetworkResourceRepository networkRepo; + + @Autowired + private ASDCRestInterface asdcRestInterface; + + private TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + private HttpHeaders headers = new HttpHeaders(); + + @Spy + DistributionClientEmulator spyClient = new DistributionClientEmulator(); + + @LocalServerPort + private int port; + + + @Test + @Transactional + public void testAllottedResourceService() throws Exception { + + stubFor(post(urlPathMatching("/aai/.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json"))); + + ObjectMapper mapper = new ObjectMapper(); + NotificationDataImpl request = mapper.readValue(new File("src/test/resources/resource-examples/allottedresource/notif-portm.json"), NotificationDataImpl.class); + headers.add("resource-location", "src/test/resources/resource-examples/allottedresource/"); + HttpEntity<NotificationDataImpl> entity = new HttpEntity<NotificationDataImpl>(request, headers); + + ResponseEntity<String> response = restTemplate.exchange(createURLWithPort("test/treatNotification/v1"), HttpMethod.POST, + entity, String.class); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + + AllottedResource expectedService = new AllottedResource(); + expectedService.setDescription("rege1802pnf"); + expectedService.setModelInvariantUUID("b8f83c3f-077c-4e2c-b489-c66382060436"); + expectedService.setModelName("rege1802pnf"); + expectedService.setModelUUID("5b18c75e-2d08-4bf2-ad58-4ea704ec648d"); + expectedService.setModelVersion("1.0"); + expectedService.setSubcategory("Contrail Route"); + expectedService.setToscaNodeType("org.openecomp.resource.pnf.Rege1802pnf"); + Set<AllottedResourceCustomization> arCustomizationSet = new HashSet<AllottedResourceCustomization>(); + AllottedResourceCustomization arCustomization = new AllottedResourceCustomization(); + arCustomization.setModelCustomizationUUID("f62bb612-c5d4-4406-865c-0abec30631ba"); + arCustomization.setModelInstanceName("rege1802pnf 0"); + arCustomizationSet.add(arCustomization); + + arCustomization.setAllottedResource(expectedService); + + + expectedService.setAllotedResourceCustomization(arCustomizationSet); + + AllottedResource actualResponse = allottedRepo.findResourceByModelUUID("5b18c75e-2d08-4bf2-ad58-4ea704ec648d"); + + + if(actualResponse == null) + throw new Exception("No Allotted Resource Written to database"); + + + assertThat(actualResponse, sameBeanAs(expectedService).ignoring("0x1.created").ignoring("0x1.allotedResourceCustomization.created")); + } + + @Test + public void invokeASDCStatusDataNullTest() { + String request = ""; + Response response = asdcRestInterface.invokeASDCStatusData(request); + assertNull(response); + + } + + + + + + protected String createURLWithPort(String uri) { + return "http://localhost:" + port + uri; + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/HealthCheckTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/HealthCheckTest.java new file mode 100644 index 0000000000..f5f7445771 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/HealthCheckTest.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.rest; + +import static org.junit.Assert.assertEquals; +import javax.ws.rs.core.Response; +import org.json.JSONException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.so.asdc.Application; +import org.onap.so.asdc.BaseTest; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +public class HealthCheckTest extends BaseTest { + + @LocalServerPort + private int port; + + TestRestTemplate restTemplate = new TestRestTemplate(); + + HttpHeaders headers = new HttpHeaders(); + + @Test + public void testHealthcheck() throws JSONException { + + HttpEntity<String> entity = new HttpEntity<String>(null, headers); + + ResponseEntity<String> response = restTemplate.exchange( + createURLWithPort("/manage/health"), + HttpMethod.GET, entity, String.class); + + assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value()); + } + + private String createURLWithPort(String uri) { + return "http://localhost:" + port + uri; + } + +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/tests/ASDCConfigurationTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/tests/ASDCConfigurationTest.java new file mode 100644 index 0000000000..6f07f44e2b --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/tests/ASDCConfigurationTest.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import javax.transaction.Transactional; + +import org.junit.Test; +import org.onap.so.asdc.BaseTest; +import org.onap.so.asdc.client.ASDCConfiguration; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * This class tests the ASDC Controller by using the ASDC Mock CLient + * + * + */ +@Transactional +public class ASDCConfigurationTest extends BaseTest { + + @Autowired + private ASDCConfiguration config; + + private List<String> msgBusAddressList = new ArrayList<String>(); + + private static final String MSO_PRE_IST = "msopreist"; + private static final String MSO_ASDC_ID_LOCAL = "msoasdc-id-local"; + private static final String PRE_IST = "Pre-IST"; + private static final String ASDC_ADDRESS = "localhost:8443"; + + @Test + public void isUseHttpsWithDmaapTest() { + assertFalse(config.isUseHttpsWithDmaap()); + } + + @Test + public void isConsumeProduceStatusTopicTest() { + assertTrue(config.isConsumeProduceStatusTopic()); + } + + @Test + public void getUserTest() { + assertTrue(MSO_PRE_IST.equals(config.getUser())); + } + + @Test + public void getConsumerGroupTest() { + assertTrue(MSO_ASDC_ID_LOCAL.equals(config.getConsumerGroup())); + } + + @Test + public void getConsumerIDTest() { + assertTrue(MSO_ASDC_ID_LOCAL.equals(config.getConsumerID())); + } + + @Test + public void getEnvironmentNameTest() { + assertTrue(PRE_IST.equals(config.getEnvironmentName())); + } + + @Test + public void getAsdcAddress() { + assertTrue(ASDC_ADDRESS.equals(config.getAsdcAddress())); + } + + @Test + public void getPasswordTest() { + assertTrue(MSO_PRE_IST.equals(config.getPassword())); + } + + @Test + public void getPollingIntervalTest() { + assertTrue(config.getPollingInterval() == 30); + } + + @Test + public void getPollingTimeoutTest() { + assertTrue(config.getPollingTimeout() == 30); + } + + @Test + public void getRelevantArtifactTypesTest() { + assertTrue(config.getRelevantArtifactTypes().size() == ASDCConfiguration.SUPPORTED_ARTIFACT_TYPES_LIST.size()); + } + + @Test + public void getWatchDogTimeoutTest() { + assertTrue(config.getWatchDogTimeout() == 1); + } + + @Test + public void activateServerTLSAuthTest() { + assertFalse(config.activateServerTLSAuth()); + } + + @Test + public void getKeyStorePasswordTest() { + assertNull(config.getKeyStorePassword()); + } + + @Test + public void getKeyStorePathTest() { + assertNull(config.getKeyStorePath()); + } + + @Test + public void isFilterInEmptyResourcesTest() { + assertTrue(config.isFilterInEmptyResources()); + } + + @Test + public void setGetAsdcControllerNameTest() { + String asdcControllerName = "testAsdcControllerName"; + config.setAsdcControllerName(asdcControllerName); + String actualAsdcControllerName = config.getAsdcControllerName(); + assertEquals(asdcControllerName, actualAsdcControllerName); + } + + @Test + public void getMsgBusAddressTest() { + msgBusAddressList.add("localhost"); + msgBusAddressList.add("localhost"); + + List<String> actualMsgBusAddress = config.getMsgBusAddress(); + assertEquals(msgBusAddressList, actualMsgBusAddress); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/installer/ToscaResourceStructureTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/installer/ToscaResourceStructureTest.java new file mode 100644 index 0000000000..de0d2e08a1 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/installer/ToscaResourceStructureTest.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer; + +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +import java.util.ArrayList; +import java.util.HashMap; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.sdc.tosca.parser.impl.SdcCsarHelperImpl; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.so.asdc.client.exceptions.ASDCDownloadException; +import org.onap.so.asdc.client.test.emulators.ArtifactInfoImpl; +import org.onap.so.db.catalog.beans.AllottedResource; +import org.onap.so.db.catalog.beans.AllottedResourceCustomization; +import org.onap.so.db.catalog.beans.NetworkResource; +import org.onap.so.db.catalog.beans.NetworkResourceCustomization; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.TempNetworkHeatTemplateLookup; +import org.onap.so.db.catalog.beans.ToscaCsar; +import org.onap.so.db.catalog.beans.VfModule; +import org.onap.so.db.catalog.beans.VfModuleCustomization; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; + +public class ToscaResourceStructureTest { + private ArtifactInfoImpl artifactInfo; + private SdcCsarHelperImpl sdcCsarHelper; + + private ToscaResourceStructure toscaResourceStructure; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void toscaResourceStructureBeanTest() { + artifactInfo = mock(ArtifactInfoImpl.class); + sdcCsarHelper = mock(SdcCsarHelperImpl.class); + + toscaResourceStructure = new ToscaResourceStructure(); + toscaResourceStructure.setHeatTemplateUUID("heatTemplateUUID"); + toscaResourceStructure.setAllottedList(new ArrayList<NodeTemplate>()); + toscaResourceStructure.setSdcCsarHelper(sdcCsarHelper); + toscaResourceStructure.setServiceMetadata(new Metadata(new HashMap<>())); + toscaResourceStructure.setCatalogService(new Service()); + toscaResourceStructure.setNetworkTypes(new ArrayList<>()); + toscaResourceStructure.setVfTypes(new ArrayList<>()); + toscaResourceStructure.setCatalogResourceCustomization(new AllottedResourceCustomization()); + toscaResourceStructure.setCatalogNetworkResourceCustomization(new NetworkResourceCustomization()); + toscaResourceStructure.setCatalogNetworkResource(new NetworkResource()); + toscaResourceStructure.setCatalogVfModule(new VfModule()); + toscaResourceStructure.setVnfResourceCustomization(new VnfResourceCustomization()); + toscaResourceStructure.setVfModuleCustomization(new VfModuleCustomization()); + toscaResourceStructure.setAllottedResource(new AllottedResource()); + toscaResourceStructure.setAllottedResourceCustomization(new AllottedResourceCustomization()); + toscaResourceStructure.setCatalogTempNetworkHeatTemplateLookup(new TempNetworkHeatTemplateLookup()); + toscaResourceStructure.setHeatFilesUUID("heatFilesUUID"); + toscaResourceStructure.setToscaArtifact(artifactInfo); + toscaResourceStructure.setToscaCsar(new ToscaCsar()); + toscaResourceStructure.setVnfAlreadyInstalled(true); + toscaResourceStructure.setVolHeatTemplateUUID("volHeatTemplateUUID"); + toscaResourceStructure.setEnvHeatTemplateUUID("envHeatTemplateUUID"); + toscaResourceStructure.setServiceVersion("serviceVersion"); + toscaResourceStructure.setWorkloadPerformance("workloadPerformance"); + toscaResourceStructure.setVfModule(new VfModule()); + toscaResourceStructure.setTempNetworkHeatTemplateLookup(new TempNetworkHeatTemplateLookup()); + toscaResourceStructure.setSuccessfulDeployment(); + + assertEquals("heatTemplateUUID", toscaResourceStructure.getHeatTemplateUUID()); + assertThat(toscaResourceStructure.getAllottedList(), sameBeanAs(new ArrayList<NodeTemplate>())); + assertEquals(sdcCsarHelper, toscaResourceStructure.getSdcCsarHelper()); + assertThat(toscaResourceStructure.getServiceMetadata(), sameBeanAs(new Metadata(new HashMap<>()))); + assertThat(toscaResourceStructure.getCatalogService(), sameBeanAs(new Service())); + assertThat(toscaResourceStructure.getNetworkTypes(), sameBeanAs(new ArrayList<>())); + assertThat(toscaResourceStructure.getVfTypes(), sameBeanAs(new ArrayList<>())); + assertThat(toscaResourceStructure.getCatalogResourceCustomization(), sameBeanAs(new AllottedResourceCustomization())); + assertThat(toscaResourceStructure.getCatalogNetworkResourceCustomization(), sameBeanAs(new NetworkResourceCustomization())); + assertThat(toscaResourceStructure.getCatalogNetworkResource(), sameBeanAs(new NetworkResource())); + assertThat(toscaResourceStructure.getCatalogVfModule(), sameBeanAs(new VfModule())); + assertThat(toscaResourceStructure.getVnfResourceCustomization(), sameBeanAs(new VnfResourceCustomization())); + assertThat(toscaResourceStructure.getVfModuleCustomization(), sameBeanAs(new VfModuleCustomization())); + assertThat(toscaResourceStructure.getAllottedResource(), sameBeanAs(new AllottedResource())); + assertThat(toscaResourceStructure.getAllottedResourceCustomization(), sameBeanAs(new AllottedResourceCustomization())); + assertThat(toscaResourceStructure.getCatalogTempNetworkHeatTemplateLookup(), sameBeanAs(new TempNetworkHeatTemplateLookup())); + assertEquals("heatFilesUUID", toscaResourceStructure.getHeatFilesUUID()); + assertEquals(artifactInfo, toscaResourceStructure.getToscaArtifact()); + assertThat(toscaResourceStructure.getToscaCsar(), sameBeanAs(new ToscaCsar())); + assertEquals(true, toscaResourceStructure.isVnfAlreadyInstalled()); + assertEquals("volHeatTemplateUUID", toscaResourceStructure.getVolHeatTemplateUUID()); + assertEquals("envHeatTemplateUUID", toscaResourceStructure.getEnvHeatTemplateUUID()); + assertEquals("serviceVersion", toscaResourceStructure.getServiceVersion()); + assertEquals("workloadPerformance", toscaResourceStructure.getWorkloadPerformance()); + assertThat(toscaResourceStructure.getVfModule(), sameBeanAs(new VfModule())); + assertThat(toscaResourceStructure.getTempNetworkHeatTemplateLookup(), sameBeanAs(new TempNetworkHeatTemplateLookup())); + assertEquals(true, toscaResourceStructure.isDeployedSuccessfully()); + } + + @Test + public void updateResourceStructureExceptionTest() throws Exception { + expectedException.expect(ASDCDownloadException.class); + + artifactInfo = mock(ArtifactInfoImpl.class); + toscaResourceStructure = new ToscaResourceStructure(); + + doReturn("artifactName").when(artifactInfo).getArtifactName(); + + toscaResourceStructure.updateResourceStructure(artifactInfo); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java new file mode 100644 index 0000000000..d96e480945 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java @@ -0,0 +1,479 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer.heat; + +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; + +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import javax.transaction.Transactional; + +import org.apache.commons.io.IOUtils; +import org.hibernate.exception.LockAcquisitionException; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.tosca.parser.impl.SdcCsarHelperImpl; +import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; +import org.onap.sdc.toscaparser.api.CapabilityAssignment; +import org.onap.sdc.toscaparser.api.CapabilityAssignments; +import org.onap.sdc.toscaparser.api.Group; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.sdc.utils.DistributionStatusEnum; +import org.onap.so.asdc.BaseTest; +import org.onap.so.asdc.client.ASDCConfiguration; +import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; +import org.onap.so.asdc.client.test.emulators.ArtifactInfoImpl; +import org.onap.so.asdc.client.test.emulators.JsonStatusData; +import org.onap.so.asdc.client.test.emulators.NotificationDataImpl; +import org.onap.so.asdc.installer.VfModuleArtifact; +import org.onap.so.asdc.installer.VfResourceStructure; +import org.onap.so.db.catalog.beans.AllottedResource; +import org.onap.so.db.catalog.beans.AllottedResourceCustomization; +import org.onap.so.db.catalog.beans.ExternalServiceToInternalService; +import org.onap.so.db.catalog.beans.HeatTemplate; +import org.onap.so.db.catalog.beans.NetworkResource; +import org.onap.so.db.catalog.beans.NetworkResourceCustomization; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.VnfResource; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.data.repository.AllottedResourceCustomizationRepository; +import org.onap.so.db.catalog.data.repository.AllottedResourceRepository; +import org.onap.so.db.catalog.data.repository.ExternalServiceToInternalServiceRepository; +import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; +import org.onap.so.db.request.beans.WatchdogDistributionStatus; +import org.onap.so.db.request.beans.WatchdogServiceModVerIdLookup; +import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository; +import org.springframework.beans.factory.annotation.Autowired; + +public class ToscaResourceInstallerTest extends BaseTest { + @Autowired + private ToscaResourceInstaller toscaInstaller; + @Autowired + private WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository; + @Autowired + private AllottedResourceRepository allottedRepo; + @Autowired + private AllottedResourceCustomizationRepository allottedCustomizationRepo; + @Autowired + private ServiceRepository serviceRepo; + @Autowired + private ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository; + @Mock + private SdcCsarHelperImpl sdcCsarHelper; + @Mock + private Metadata metadata; + @Mock + private ArtifactInfoImpl artifactInfo; + @Mock + private List<Group> vfGroups; + @Mock + private IResourceInstance resourceInstance; + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + private NotificationDataImpl notificationData; + private JsonStatusData statusData; + private static final String MSO = "SO"; + + private AllottedResource allottedResource; + private AllottedResourceCustomization allottedResourceCustomization; + private Service catalogService; + + @Before + public void before() { + MockitoAnnotations.initMocks(this); + + notificationData = new NotificationDataImpl(); + statusData = new JsonStatusData(); + } + + @Test + public void isResourceAlreadyDeployedTest() throws Exception { + notificationData.setServiceName("serviceName"); + notificationData.setServiceVersion("123456"); + notificationData.setServiceUUID("serviceUUID"); + notificationData.setDistributionID("testStatusSuccessTosca"); + + WatchdogComponentDistributionStatus expectedComponentDistributionStatus = + new WatchdogComponentDistributionStatus(notificationData.getDistributionID(), MSO); + expectedComponentDistributionStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); + + doReturn(true).when(vfResourceStructure).isDeployedSuccessfully(); + doReturn(notificationData).when(vfResourceStructure).getNotification(); + doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance(); + doReturn("resourceInstanceName").when(resourceInstance).getResourceInstanceName(); + doReturn("resourceCustomizationUUID").when(resourceInstance).getResourceCustomizationUUID(); + doReturn("resourceName").when(resourceInstance).getResourceName(); + + toscaInstaller.isResourceAlreadyDeployed(vfResourceStructure); + + WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus = getWatchdogCDStatusWithName(watchdogCDStatusRepository.findByDistributionId(notificationData.getDistributionID()), MSO); + + verify(vfResourceStructure, times(3)).getResourceInstance(); + verify(vfResourceStructure, times(5)).getNotification(); + assertThat(actualWatchdogComponentDistributionStatus, sameBeanAs(expectedComponentDistributionStatus) + .ignoring("createTime") + .ignoring("modifyTime")); + } + + @Test + public void isResourceAlreadyDeployedFalseTest() throws Exception { + notificationData.setServiceName("serviceName"); + notificationData.setServiceVersion("123456"); + notificationData.setServiceUUID("serviceUUID"); + notificationData.setDistributionID("testStatusSuccess"); + + doThrow(RuntimeException.class).when(vfResourceStructure).isDeployedSuccessfully(); + doReturn(notificationData).when(vfResourceStructure).getNotification(); + doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance(); + doReturn("resourceInstanceName").when(resourceInstance).getResourceInstanceName(); + doReturn("resourceCustomizationUUID").when(resourceInstance).getResourceCustomizationUUID(); + doReturn("resourceName").when(resourceInstance).getResourceName(); + + toscaInstaller.isResourceAlreadyDeployed(vfResourceStructure); + + verify(vfResourceStructure, times(3)).getResourceInstance(); + verify(vfResourceStructure, times(4)).getNotification(); + } + + @Test + public void isResourceAlreadyDeployedExceptionTest() throws ArtifactInstallerException { + expectedException.expect(ArtifactInstallerException.class); + + toscaInstaller.isResourceAlreadyDeployed(vfResourceStructure); + } + + @Test + public void installTheComponentStatusTest() throws Exception { + String distributionId = "testStatusSuccessTosca"; + String componentName = "testComponentName"; + + statusData = spy(JsonStatusData.class); + doReturn(distributionId).when(statusData).getDistributionID(); + doReturn(componentName).when(statusData).getComponentName(); + + WatchdogComponentDistributionStatus expectedWatchdogComponentDistributionStatus = + new WatchdogComponentDistributionStatus(distributionId, componentName); + expectedWatchdogComponentDistributionStatus.setComponentDistributionStatus(statusData.getStatus().toString()); + + WatchdogComponentDistributionStatus cdStatus = new WatchdogComponentDistributionStatus(statusData.getDistributionID(), + statusData.getComponentName()); + + toscaInstaller.installTheComponentStatus(statusData); + + WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus = getWatchdogCDStatusWithName(watchdogCDStatusRepository.findByDistributionId("testStatusSuccessTosca"), statusData.getComponentName()); + + assertEquals(statusData.getDistributionID(), cdStatus.getDistributionId()); + assertEquals(statusData.getComponentName(), cdStatus.getComponentName()); + assertThat(actualWatchdogComponentDistributionStatus, sameBeanAs(expectedWatchdogComponentDistributionStatus) + .ignoring("createTime") + .ignoring("modifyTime")); + } + + @Test + public void installTheComponentStatusExceptionTest() throws ArtifactInstallerException { + expectedException.expect(ArtifactInstallerException.class); + + statusData = spy(JsonStatusData.class); + doReturn(null).when(statusData).getStatus(); + + toscaInstaller.installTheComponentStatus(statusData); + } + + @Test + @Ignore + @Transactional + public void installTheResourceTest() throws Exception { + notificationData.setDistributionID("testStatusSuccessTosca"); + notificationData.setServiceVersion("123456"); + notificationData.setServiceUUID("5df8b6de-2083-11e7-93ae-92361f002671"); + notificationData.setWorkloadContext("workloadContext"); + + HashMap<String, VfModuleArtifact> vfModuleArtifacts = mock(HashMap.class); + CapabilityAssignments capabilityAssignments = mock(CapabilityAssignments.class); + CapabilityAssignment capabilityAssignment = mock(CapabilityAssignment.class); + + vfResourceStructure = spy(new VfResourceStructure(notificationData, resourceInstance)); + + VnfResource vnfResource = new VnfResource(); + vnfResource.setModelName("modelName"); + vnfResource.setModelVersion("1.1"); + vnfResource.setModelUUID("modelUUID"); + vnfResource.setOrchestrationMode("orchestrationMode"); + + VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization(); + vnfResourceCustomization.setVnfResources(vnfResource); + vnfResourceCustomization.setModelCustomizationUUID("vnfResCustModelCustomizationUUID"); + vnfResourceCustomization.setModelInstanceName("modelInstanceName"); + + AllottedResource allottedResource = new AllottedResource(); + allottedResource.setModelUUID("serviceMetadataValue"); + allottedResource.setModelInvariantUUID("modelInvariantUUID"); + allottedResource.setModelName("modelName"); + allottedResource.setModelVersion("1.1"); + + AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization(); + allottedResourceCustomization.setAllottedResource(allottedResource); + allottedResourceCustomization.setModelCustomizationUUID("modelCustomizationUUID"); + allottedResourceCustomization.setModelInstanceName("modelInstanceName"); + + Service catalogService = new Service(); + catalogService.setServiceType("serviceType"); + catalogService.setModelUUID("5df8b6de-2083-11e7-93ae-92361f002672"); + catalogService.setModelInvariantUUID("modelInvariantUUID"); + catalogService.setModelName("modelName"); + catalogService.setModelVersion("modelVersion"); + catalogService.getVnfCustomizations().add(vnfResourceCustomization); + + Iterator artifactIterator = mock(Iterator.class); + Iterator nodeTemplateIterator = mock(Iterator.class); + IDistributionClientDownloadResult clientResult = mock(IDistributionClientDownloadResult.class); + doReturn(IOUtils.toByteArray( + new FileInputStream( + new File( + getClass().getClassLoader().getResource("resource-examples/simpleTest.yaml").getFile()) + ))).when(clientResult).getArtifactPayload(); + VfModuleArtifact vfModuleArtifact = new VfModuleArtifact(artifactInfo, clientResult); + Collection<VfModuleArtifact> vfModuleArtifactsValues = mock(Collection.class); + + NodeTemplate nodeTemplate = mock(NodeTemplate.class); + List<NodeTemplate> nodeTemplateList = new ArrayList<>(); + nodeTemplateList.add(nodeTemplate); + + HeatTemplate heatTemplate = new HeatTemplate(); + heatTemplate.setArtifactUuid("ff874603-4222-11e7-9252-005056850d2e"); + heatTemplate.setArtifactChecksum("MANUAL RECORD"); + heatTemplate.setTemplateBody("templateBody"); + heatTemplate.setTemplateName("module_mns_zrdm3frwl01exn_01_rgvm_1.yml"); + heatTemplate.setVersion("1"); + + NetworkResource networkResource = new NetworkResource(); + networkResource.setAicVersionMin("aicVersionMin"); + networkResource.setModelUUID("modelUUID"); + networkResource.setOrchestrationMode("orchestrationMode"); + networkResource.setModelVersion("modelVersion"); + networkResource.setNeutronNetworkType("neutronNetworkType"); + networkResource.setAicVersionMax("aicVersionMax"); + networkResource.setModelName("CONTRAIL30_GNDIRECT"); + networkResource.setModelInvariantUUID("modelInvariantUUID"); + networkResource.setHeatTemplate(heatTemplate); + + NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization(); + networkResourceCustomization.setModelCustomizationUUID("modelCustomizationUUID"); + networkResourceCustomization.setModelInstanceName("modelInstanceName"); + networkResourceCustomization.setNetworkResource(networkResource); + + WatchdogServiceModVerIdLookup expectedModVerIdLookup = new WatchdogServiceModVerIdLookup(notificationData.getDistributionID(), notificationData.getServiceUUID()); + WatchdogDistributionStatus expectedDistributionStatus = new WatchdogDistributionStatus(notificationData.getDistributionID()); + WatchdogComponentDistributionStatus expectedComponentDistributionStatus = new WatchdogComponentDistributionStatus(notificationData.getDistributionID(), MSO); + expectedComponentDistributionStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); + + doReturn(sdcCsarHelper).when(toscaResourceStruct).getSdcCsarHelper(); + doReturn("metadataPropertyValue").when(sdcCsarHelper).getMetadataPropertyValue(any(Metadata.class), any(String.class)); + doReturn("ntPropertyLeafValue").when(sdcCsarHelper).getNodeTemplatePropertyLeafValue(any(NodeTemplate.class), any(String.class)); + doReturn("true").when(sdcCsarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK); + doReturn("1").when(sdcCsarHelper).getCapabilityPropertyLeafValue(any(CapabilityAssignment.class), any(String.class)); + doReturn(vfGroups).when(sdcCsarHelper).getVfModulesByVf(any(String.class)); + doReturn(capabilityAssignments).when(sdcCsarHelper).getCapabilitiesOf(any(NodeTemplate.class)); + doReturn(capabilityAssignment).when(capabilityAssignments).getCapabilityByName(any(String.class)); + + doReturn(catalogService).when(toscaResourceStruct).getCatalogService(); + + doReturn(artifactInfo).when(toscaResourceStruct).getToscaArtifact(); + doReturn("artifactChecksum").when(artifactInfo).getArtifactChecksum(); + doReturn("artifactUUID").when(artifactInfo).getArtifactUUID(); + doReturn("artifactName").when(artifactInfo).getArtifactName(); + doReturn("1.0").when(artifactInfo).getArtifactVersion(); + doReturn("artifactDescription").when(artifactInfo).getArtifactDescription(); + doReturn("artifactURL").when(artifactInfo).getArtifactURL(); + + doReturn(metadata).when(toscaResourceStruct).getServiceMetadata(); + doReturn("serviceMetadataValue").when(metadata).getValue(any(String.class)); + doReturn("CONTRAIL30_GNDIRECT").when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_NAME); + + doReturn("serviceVersion").when(toscaResourceStruct).getServiceVersion(); + doReturn(nodeTemplateList).when(sdcCsarHelper).getServiceVfList(); + doReturn(nodeTemplateList).when(sdcCsarHelper).getServiceVlList(); + doReturn(nodeTemplateList).when(sdcCsarHelper).getAllottedResources(); + doReturn(metadata).when(nodeTemplate).getMetaData(); + doReturn("model_instance_name").when(nodeTemplate).getName(); + doReturn(false).when(toscaResourceStruct).isVnfAlreadyInstalled(); + doReturn(vnfResourceCustomization).when(toscaResourceStruct).getCatalogVnfResourceCustomization(); + doReturn(allottedResource).when(toscaResourceStruct).getAllottedResource(); + doReturn(allottedResourceCustomization).when(toscaResourceStruct).getCatalogAllottedResourceCustomization(); + + doReturn(vfModuleArtifacts).when(vfResourceStructure).getArtifactsMapByUUID(); + when(vfModuleArtifacts.values()).thenReturn(vfModuleArtifactsValues); + when(vfModuleArtifactsValues.iterator()).thenReturn(artifactIterator); + when(artifactIterator.hasNext()).thenReturn(true, false); + when(artifactIterator.next()).thenReturn(vfModuleArtifact); + when(artifactInfo.getArtifactType()).thenReturn(ASDCConfiguration.OTHER); + when(nodeTemplateIterator.hasNext()).thenReturn(true, false); + + doReturn(networkResource).when(toscaResourceStruct).getCatalogNetworkResource(); + doReturn(networkResourceCustomization).when(toscaResourceStruct).getCatalogNetworkResourceCustomization(); + + doNothing().when(toscaResourceStruct).setSuccessfulDeployment(); + + toscaInstaller.installTheResource(toscaResourceStruct, vfResourceStructure); + + AllottedResource actualAllottedResource = allottedRepo.findResourceByModelUUID(allottedResource.getModelUUID()); + AllottedResourceCustomization actualAllottedResourceCustomization = allottedCustomizationRepo.findOne(allottedResourceCustomization.getModelCustomizationUUID()); + Service actualService = serviceRepo.findByServiceType(catalogService.getServiceType()); + WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus = getWatchdogCDStatusWithName(watchdogCDStatusRepository.findByDistributionId(notificationData.getDistributionID()), MSO); + + verify(toscaResourceStruct, times(1)).setSuccessfulDeployment(); + assertThat(actualAllottedResource, + sameBeanAs(allottedResource)); + assertThat(actualAllottedResourceCustomization, sameBeanAs(allottedResourceCustomization) + .ignoring("created")); + assertThat(actualService, sameBeanAs(catalogService) + .ignoring("created") + .ignoring("networkCustomizations.0x1.created") + .ignoring("networkCustomizations.0x1.networkResource.created")); + assertThat(actualWatchdogComponentDistributionStatus, sameBeanAs(expectedComponentDistributionStatus) + .ignoring("createTime") + .ignoring("modifyTime")); + } + + + @Test + public void installTheResourceExceptionTest() throws Exception { + expectedException.expect(ArtifactInstallerException.class); + + notificationData.setDistributionID("testStatusFailureTosca"); + notificationData.setServiceVersion("123456"); + notificationData.setServiceUUID("serviceUUID"); + notificationData.setWorkloadContext("workloadContext"); + + doReturn(notificationData).when(vfResourceStructure).getNotification(); + doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance(); + + toscaInstaller.installTheResource(toscaResourceStruct, vfResourceStructure); + } + + @Test + public void installTheResourceDBExceptionTest() throws Exception { + notificationData.setDistributionID("testStatusSuccessTosca"); + notificationData.setServiceVersion("123456"); + notificationData.setServiceUUID("serviceUUID"); + notificationData.setWorkloadContext("workloadContext"); + + doReturn(notificationData).when(vfResourceStructure).getNotification(); + doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance(); + doThrow(LockAcquisitionException.class).when(toscaResourceStruct).getToscaArtifact(); + + toscaInstaller.installTheResource(toscaResourceStruct, vfResourceStructure); + } + + @Test + public void verifyTheFilePrefixInStringTest() { + String body = "abcabcabcfile:///testfile.txtabcbabacbcabc"; + String filenameToVerify = "testfile.txt"; + String expectedFileBody = "abcabcabctestfile.txtabcbabacbcabc"; + + String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify); + + assertEquals(expectedFileBody, newFileBody); + } + + @Test + public void verifyTheFilePrefixInStringNullBodyTest() { + String body = null; + String filenameToVerify = "testfile.txt"; + + String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify); + + assertEquals(body, newFileBody); + } + + @Test + public void verifyTheFilePrefixInStringEmptyBodyTest() { + String body = ""; + String filenameToVerify = "testfile.txt"; + + String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify); + + assertEquals(body, newFileBody); + } + + @Test + public void verifyTheFilePrefixInStringNullFilenameTest() { + String body = "abcabcabcfile:///testfile.txtabcbabacbcabc"; + String filenameToVerify = null; + + String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify); + + assertEquals(body, newFileBody); + } + + @Test + public void verifyTheFilePrefixInStringEmptyFilenameTest() { + String body = "abcabcabcfile:///testfile.txtabcbabacbcabc"; + String filenameToVerify = ""; + + String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify); + + assertEquals(body, newFileBody); + } + + private WatchdogComponentDistributionStatus getWatchdogCDStatusWithName(List<WatchdogComponentDistributionStatus> watchdogComponentDistributionStatuses, String componentName) { + WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus = new WatchdogComponentDistributionStatus(); + for(WatchdogComponentDistributionStatus watchdogComponentDistributionStatus : watchdogComponentDistributionStatuses) { + if(componentName.equals(watchdogComponentDistributionStatus.getComponentName())) { + actualWatchdogComponentDistributionStatus = watchdogComponentDistributionStatus; + break; + } + } + return actualWatchdogComponentDistributionStatus; + } + + + +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImplTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImplTest.java new file mode 100644 index 0000000000..a20f6de579 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImplTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.tenantIsolation; + +import static org.junit.Assert.assertEquals; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.so.asdc.BaseTest; +import org.onap.so.client.aai.AAIVersion; + +public class AaiClientPropertiesImplTest extends BaseTest { + + private static final String SYSTEM_NAME = "MSO"; + private static final String LOCAL_HOST = "http://localhost:"; + + @BeforeClass + public static void setup() throws Exception { + System.setProperty("mso.config.path", "src/test/resources"); + } + + @Test + public void getEndpointTest() throws Exception { + AaiClientPropertiesImpl aaiClientPropertiesImpl = new AaiClientPropertiesImpl(); + String aaiEndpoint = aaiClientPropertiesImpl.getEndpoint().toString(); + assertEquals(LOCAL_HOST + wireMockPort, aaiEndpoint); + } + + @Test + public void getSystemNameTest() { + AaiClientPropertiesImpl aaiClientPropertiesImpl = new AaiClientPropertiesImpl(); + assertEquals(SYSTEM_NAME, aaiClientPropertiesImpl.getSystemName()); + } + + @Test + public void getDefaultVersionTest() { + AaiClientPropertiesImpl aaiClientPropertiesImpl = new AaiClientPropertiesImpl(); + assertEquals(AAIVersion.LATEST, aaiClientPropertiesImpl.getDefaultVersion()); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/WatchdogDistributionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/WatchdogDistributionTest.java new file mode 100644 index 0000000000..b72e079e9e --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/WatchdogDistributionTest.java @@ -0,0 +1,141 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.tenantIsolation; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.HashMap; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.so.asdc.BaseTest; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.db.catalog.beans.Service; +import org.springframework.beans.factory.annotation.Autowired; + +public class WatchdogDistributionTest extends BaseTest { + @Autowired + private WatchdogDistribution watchdogDistribution; + + @Mock + private AAIResourcesClient aaiResourceClient; + + private static final String SUCCESS_TEST = "watchdogTestStatusSuccess"; + private static final String FAILURE_TEST = "watchdogTestStatusFailure"; + private static final String TIMEOUT_TEST = "watchdogTestStatusTimeout"; + private static final String INCOMPLETE_TEST = "watchdogTestStatusIncomplete"; + private static final String EXCEPTION_TEST = "watchdogTestStatusException"; + private static final String NULL_TEST = "watchdogTestStatusNull"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void before() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void getOverallDistributionStatusTimeoutTest() throws Exception { + String status = watchdogDistribution.getOverallDistributionStatus(TIMEOUT_TEST); + assertEquals(DistributionStatus.TIMEOUT.toString(), status); + } + + @Test + public void getOverallDistributionStatusSuccessTest() throws Exception { + String status = watchdogDistribution.getOverallDistributionStatus(SUCCESS_TEST); + assertEquals(DistributionStatus.SUCCESS.toString(), status); + } + + @Test + public void getOverallDistributionStatusFailureTest() throws Exception { + String status = watchdogDistribution.getOverallDistributionStatus(FAILURE_TEST); + assertEquals(DistributionStatus.FAILURE.toString(), status); + } + + @Test + public void getOverallDistributionStatusIncompleteTest() throws Exception { + String status = watchdogDistribution.getOverallDistributionStatus(INCOMPLETE_TEST); + assertEquals(DistributionStatus.INCOMPLETE.toString(), status); + } + + @Test + public void getOverallDistributionStatusInvalidComponentExceptionTest() throws Exception { + expectedException.expect(Exception.class); + watchdogDistribution.getOverallDistributionStatus(EXCEPTION_TEST); + } + + @Test + public void getOverallDistributionStatusNewStatusTest() throws Exception { + String status = watchdogDistribution.getOverallDistributionStatus("newDistrubutionStatus"); + assertEquals(DistributionStatus.INCOMPLETE.toString(), status); + } + + @Test + public void getOverallDistributionStatusExceptionTest() throws Exception { + expectedException.expect(Exception.class); + watchdogDistribution.getOverallDistributionStatus(null); + } + + @Test + public void executePatchAAITest() throws Exception { + Service service = new Service(); + service.setModelInvariantUUID("9647dfc4-2083-11e7-93ae-92361f002671"); + + doReturn(aaiResourceClient).when(watchdogDistributionSpy).getAaiClient(); + doNothing().when(aaiResourceClient).update(isA(AAIResourceUri.class), isA(HashMap.class)); + + watchdogDistribution.executePatchAAI(SUCCESS_TEST, service.getModelInvariantUUID(), DistributionStatus.SUCCESS.toString()); + + verify(aaiResourceClient, times(1)).update(any(AAIResourceUri.class), any(HashMap.class)); + } + + @Test + public void executePatchAAINullDistrubutionIdTest() throws Exception { + expectedException.expect(Exception.class); + watchdogDistribution.executePatchAAI(null, "", DistributionStatus.SUCCESS.toString()); + } + + @Test + public void executePatchAAINullServiceTest() throws Exception { + expectedException.expect(Exception.class); + watchdogDistribution.executePatchAAI(NULL_TEST, null, DistributionStatus.SUCCESS.toString()); + } + + @Test + public void getSetAaiClientTest() { + aaiResourceClient = watchdogDistribution.getAaiClient(); + watchdogDistribution.setAaiClient(aaiResourceClient); + AAIResourcesClient aaiResourceClient2 = watchdogDistribution.getAaiClient(); + assertEquals(aaiResourceClient, aaiResourceClient2); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/util/ASDCNotificationLoggingTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/util/ASDCNotificationLoggingTest.java new file mode 100644 index 0000000000..3abc2e7a62 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/util/ASDCNotificationLoggingTest.java @@ -0,0 +1,186 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.util; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.so.asdc.installer.IVfModuleData; +import org.onap.so.asdc.installer.VfModuleMetaData; +import org.onap.so.asdc.util.ASDCNotificationLogging; + +public class ASDCNotificationLoggingTest { + @Test + public void dumpASDCNotificationTestForNull() throws Exception { + INotificationData asdcNotification = iNotificationDataObject(); + + String result = ASDCNotificationLogging.dumpASDCNotification(asdcNotification); + + assertTrue(!result.equalsIgnoreCase("NULL")); + } + + private INotificationData iNotificationDataObject() { + INotificationData iNotification = new INotificationData() { + + @Override + public String getServiceVersion() { + return "DistributionID"; + } + + @Override + public String getServiceUUID() { + return "12343254"; + } + + @Override + public String getServiceName() { + return "servername"; + } + + @Override + public String getServiceInvariantUUID() { + return "ServiceInvariantUUID"; + } + + @Override + public String getServiceDescription() { + return "Description"; + } + + @Override + public List<IArtifactInfo> getServiceArtifacts() { + return new ArrayList(); + } + + @Override + public List<IResourceInstance> getResources() { + return new ArrayList(); + } + + @Override + public String getDistributionID() { + return "23434"; + } + + @Override + public IArtifactInfo getArtifactMetadataByUUID(String arg0) { + return null; + } + + @Override + public String getWorkloadContext() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setWorkloadContext(String arg0) { + // TODO Auto-generated method stub + + } + }; + return iNotification; + } + + @Test + public void dumpASDCNotificationTest() throws Exception { + INotificationData asdcNotification = iNotificationDataObject(); + String result = ASDCNotificationLogging.dumpASDCNotification(asdcNotification); + + assertTrue(!result.equalsIgnoreCase("NULL")); + } + + @Test + public void dumpVfModuleMetaDataListTest() { + INotificationData asdcNotification = iNotificationDataObject(); + List<IVfModuleData> list = new ArrayList<>(); + list.add(new VfModuleMetaData()); + String result = null; + try { + result = ASDCNotificationLogging.dumpVfModuleMetaDataList(list); + } catch (Exception e) { + } + + assertTrue(result == null); + + } + + public IArtifactInfo getIArtifactInfo() { + return new IArtifactInfo() { + + @Override + public List<IArtifactInfo> getRelatedArtifacts() { + return null; + } + + @Override + public IArtifactInfo getGeneratedArtifact() { + return null; + } + + @Override + public String getArtifactVersion() { + return "version"; + } + + @Override + public String getArtifactUUID() { + return "123"; + } + + @Override + public String getArtifactURL() { + return "url"; + } + + @Override + public String getArtifactType() { + return "type"; + } + + @Override + public Integer getArtifactTimeout() { + return 12; + } + + @Override + public String getArtifactName() { + return "name"; + } + + @Override + public String getArtifactDescription() { + return "desc"; + } + + @Override + public String getArtifactChecksum() { + return "true"; + } + }; + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/util/NotificationLoggingTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/util/NotificationLoggingTest.java new file mode 100644 index 0000000000..8bd11d9f52 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/util/NotificationLoggingTest.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.onap.so.asdc.client.test.emulators.NotificationDataImpl; + +public class NotificationLoggingTest { + private NotificationDataImpl notificationData; + + @Before + public void before() { + notificationData = new NotificationDataImpl(); + } + + @Test + public void logNotificationTest() { + notificationData.setDistributionID("distributionID"); + notificationData.setServiceVersion("123456"); + notificationData.setServiceUUID("serviceUUID"); + notificationData.setWorkloadContext("workloadContext"); + + String response = NotificationLogging.logNotification(notificationData); + + assertTrue(response.contains("ASDC Notification")); + assertTrue(response.contains("ResourcesType not recognized")); + assertTrue(response.contains("ServiceNameNULL")); + assertTrue(response.contains("ServiceUUIDserviceUUID")); + assertTrue(response.contains("ResourcesImplNULL")); + assertTrue(response.contains("ServiceArtifactsType not recognized")); + assertTrue(response.contains("ServiceDescriptionNULL")); + assertTrue(response.contains("DistributionIDdistributionID")); + assertTrue(response.contains("ServiceInvariantUUIDNULL")); + assertTrue(response.contains("WorkloadContextworkloadContext")); + } + + @Test + public void logNotificationNullTest() { + notificationData = null; + + String response = NotificationLogging.logNotification(notificationData); + + assertEquals("NULL", response); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingRunner.java b/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingRunner.java new file mode 100644 index 0000000000..2a77664714 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingRunner.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.utils; + +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.tree.ParseTree; + +import com.fasterxml.jackson.databind.JsonNode; + + +public class ASDCLoggingRunner +{ + public static void main( String[] args) throws Exception + { + String content = new String(Files.readAllBytes(Paths.get("src/test/resources/Heat_Nested_Notification.txt"))); + + ASDCLoggingLexer lexer = new ASDCLoggingLexer(CharStreams.fromString(content)); + + CommonTokenStream tokens = new CommonTokenStream(lexer); + + ASDCLoggingParser parser = new ASDCLoggingParser(tokens); + + ParseTree tree = parser.doc(); + + System.out.println(TreeUtils.printTree(tree, parser)); // print LISP-style tree + + ASDCLoggingVisitorImpl v = new ASDCLoggingVisitorImpl(); + + JsonNode node = v.visit(tree); + + System.out.println(node.toString()); + + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingVisitorImpl.java b/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingVisitorImpl.java new file mode 100644 index 0000000000..51036e2a18 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingVisitorImpl.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.utils; + +import java.util.ArrayDeque; +import java.util.Deque; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ContainerNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.base.CaseFormat; + + +public class ASDCLoggingVisitorImpl extends ASDCLoggingBaseVisitor<ContainerNode> { + + private final ObjectMapper mapper = new ObjectMapper(); + private ObjectNode doc; + private Deque<ContainerNode> nodeStore = new ArrayDeque<>(); + + @Override + public ContainerNode visitDoc(ASDCLoggingParser.DocContext ctx) { + doc = mapper.createObjectNode(); + nodeStore.addFirst(doc); + this.visitChildren(ctx); + return doc; + } + + @Override + public ContainerNode visitValue(ASDCLoggingParser.ValueContext ctx) { + + return this.visitChildren(ctx); + + } + @Override + public ContainerNode visitSimplePair(ASDCLoggingParser.SimplePairContext ctx) { + ObjectNode node = mapper.createObjectNode(); + ((ObjectNode)nodeStore.peekFirst()).put(this.toLowerCamel(ctx.key().getText()), ctx.keyValue().getText()); + + return node; + } + + @Override + public ContainerNode visitComplexPair(ASDCLoggingParser.ComplexPairContext ctx) { + ContainerNode container = nodeStore.peekFirst(); + if (container.isArray()) { + ArrayNode array = (ArrayNode) container; + ObjectNode node = mapper.createObjectNode(); + array.add(node); + nodeStore.addFirst(node); + } else { + nodeStore.addFirst(((ObjectNode)nodeStore.peekFirst()).putObject(this.toLowerCamel(ctx.key().getText()))); + } + this.visitChildren(ctx); + return nodeStore.removeFirst(); + + + } + + @Override + public ContainerNode visitList(ASDCLoggingParser.ListContext ctx) { + nodeStore.addFirst(((ObjectNode)nodeStore.peekFirst()).putArray(this.keyMapper(ctx.listName().getText()))); + this.visitChildren(ctx); + return nodeStore.removeFirst(); + } + + private String keyMapper(String key) { + if ("Service Artifacts List".equals(key)) { + return "serviceArtifacts"; + } else if ("Resource Instances List".equals(key)) { + return "resources"; + } else if ("Resource Artifacts List".equals(key)) { + return "artifacts"; + } else { + return key; + } + } + + private String toLowerCamel(String key) { + String result = key.replaceAll("\\s", ""); + if ("ServiceArtifactsInfo".equals(result)) { + return "artifactInfo"; + } + return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, result); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreePrinterListener.java b/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreePrinterListener.java new file mode 100644 index 0000000000..c4a84c0540 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreePrinterListener.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.utils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.RuleContext; +import org.antlr.v4.runtime.misc.Utils; +import org.antlr.v4.runtime.tree.ErrorNode; +import org.antlr.v4.runtime.tree.ParseTreeListener; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.antlr.v4.runtime.tree.Trees; + +public class TreePrinterListener implements ParseTreeListener { + private final List<String> ruleNames; + private final StringBuilder builder = new StringBuilder(); + Map<RuleContext,ArrayList<String>> stack = new HashMap<RuleContext,ArrayList<String>>(); + + public TreePrinterListener(Parser parser) { + this.ruleNames = Arrays.asList(parser.getRuleNames()); + } + + public TreePrinterListener(List<String> ruleNames) { + this.ruleNames = ruleNames; + } + + @Override + public void visitTerminal(TerminalNode node) { + String text = Utils.escapeWhitespace(Trees.getNodeText(node, ruleNames), false); + if(text.startsWith(" ") || text.endsWith(" ")){ + text = "'" + text + "'"; + } + stack.get(node.getParent()).add(text); + } + + @Override + public void visitErrorNode(ErrorNode node) { + stack.get(node.getParent()).add(Utils.escapeWhitespace(Trees.getNodeText(node, ruleNames), false)); + } + + @Override + public void enterEveryRule(ParserRuleContext ctx) { + if(!stack.containsKey(ctx.parent)){ + stack.put(ctx.parent, new ArrayList<String>()); + } + if(!stack.containsKey(ctx)){ + stack.put(ctx, new ArrayList<String>()); + } + + final StringBuilder sb = new StringBuilder(); + int ruleIndex = ctx.getRuleIndex(); + String ruleName; + if (ruleIndex >= 0 && ruleIndex < ruleNames.size()) { + ruleName = ruleNames.get(ruleIndex); + } + else { + ruleName = Integer.toString(ruleIndex); + } + sb.append(ruleName); + stack.get(ctx).add(sb.toString()); + } + + @Override + public void exitEveryRule(ParserRuleContext ctx) { + ArrayList<String> ruleStack = stack.remove(ctx); + StringBuilder sb = new StringBuilder(); + boolean brackit =ruleStack.size()>1; + if(brackit){ + sb.append("("); + } + sb.append(ruleStack.get(0)); + for(int i=1; i<ruleStack.size(); i++){ + sb.append(" "); + sb.append(ruleStack.get(i)); + } + if(brackit){ + sb.append(")"); + } + if(sb.length() < 80){ + stack.get(ctx.parent).add(sb.toString()); + }else{ + // Current line is too long, regenerate it using 1 line per item. + sb.setLength(0); + if(brackit){ + sb.append("("); + } + if(!ruleStack.isEmpty()){ + sb.append(ruleStack.remove(0)).append("\r\n"); + } + while(!ruleStack.isEmpty()){ + sb.append(indent(ruleStack.remove(0))).append("\r\n"); + } + if(brackit){ + sb.append(")"); + } + stack.get(ctx.parent).add(sb.toString()); + } + if(ctx.parent == null){ + builder.append(sb.toString()); + } + } + + static String indent(String input){ + return " " + input.replaceAll("\r\n(.)","\r\n $1"); + } + + @Override + public String toString() { + return builder.toString(); + } + + +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreeUtils.java b/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreeUtils.java new file mode 100644 index 0000000000..8de9f362b7 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreeUtils.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.utils; + +import java.util.Arrays; + +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.ParseTreeWalker; + + +public class TreeUtils { + + /** + * Print the tree, splitting at appropriate points, instead of rendering a single long line. + * @param parseTree + * @param parser + * @return + */ + public static String printTree(final ParseTree parseTree, final Parser parser){ + final TreePrinterListener listener = new TreePrinterListener(Arrays.asList(parser.getRuleNames())); + ParseTreeWalker.DEFAULT.walk(listener, parseTree); + return listener.toString(); + } + + public static String normalizeWhiteSpace(String input){ + return input.replaceAll("\\s+", " ").replaceAll("([^\\w])\\s+", "$1"); + } +} |