From c5aea4a8bc398fc1c6220875e55b9520fd7f7524 Mon Sep 17 00:00:00 2001 From: "mark.j.leonard" Date: Wed, 6 Jun 2018 14:47:42 +0100 Subject: Refactor for Sonar smells and code coverage Various code formatting and style fixes (to address Sonar code smells). Introduce a BabelServiceClientException to replace the use of the base Exception class. Make both the BabelServiceClient class and its Factory class use an interface, to allow for Spring injection (using annotations) and for simplified mocking. Refactor the Notification Publishing by making this the responsibility of the main Service classes and not the deployment manager. Issue-ID: AAI-1207 Change-Id: I6bf8a504fa7b98e9158c9976fd1d88c6c54027c1 Signed-off-by: mark.j.leonard --- .../modelloader/TestModelLoaderApplication.java | 42 +++ .../modelloader/config/ModelLoaderConfigTest.java | 192 ---------- .../modelloader/config/TestModelLoaderConfig.java | 193 ++++++++++ .../catalog/TestVnfCatalogArtifactHandler.java | 130 +++++++ .../entity/catalog/TestVnfImageException.java | 7 +- .../catalog/VnfCatalogArtifactHandlerTest.java | 100 ------ .../entity/model/ModelArtifactParserTest.java | 122 ------- .../modelloader/entity/model/ModelSorterTest.java | 56 ++- .../entity/model/NamedQueryArtifactParserTest.java | 61 ---- .../entity/model/TestModelArtifactHandler.java | 2 +- .../entity/model/TestModelArtifactParser.java | 102 ++++++ .../entity/model/TestNamedQueryArtifactParser.java | 64 ++++ .../extraction/ArtifactInfoExtractorTest.java | 108 ------ .../extraction/TestArtifactInfoExtractor.java | 108 ++++++ .../modelloader/fixture/ArtifactInfoBuilder.java | 14 +- .../fixture/MockNotificationDataImpl.java | 101 ++++++ .../fixture/NotificationDataFixtureBuilder.java | 40 ++- .../fixture/ResourceInstanceBuilder.java | 8 +- .../fixture/TestNotificationDataImpl.java | 101 ------ .../fixture/TestResourceInstanceImpl.java | 2 +- .../ArtifactDeploymentManagerTest.java | 189 ---------- .../notification/ArtifactDownloadManagerTest.java | 398 --------------------- .../notification/BabelArtifactConverterTest.java | 77 ---- .../notification/EventCallbackTest.java | 116 ------ .../TestArtifactDeploymentManager.java | 235 ++++++++++++ .../notification/TestArtifactDownloadManager.java | 351 ++++++++++++++++++ .../notification/TestBabelArtifactConverter.java | 95 +++++ .../notification/TestEventCallback.java | 119 ++++++ .../notification/TestNotificationDataImpl.java | 83 +++++ .../notification/TestNotificationPublisher.java | 2 +- .../restclient/MockBabelServiceClient.java | 41 +++ .../modelloader/restclient/TestAaiRestClient.java | 144 ++++++++ .../restclient/TestAaiServiceClient.java | 8 +- .../restclient/TestBabelServiceClient.java | 27 +- .../service/MockBabelServiceClientFactory.java | 37 ++ .../modelloader/service/TestArtifactInfoImpl.java | 8 +- .../service/TestModelLoaderApplication.java | 41 --- .../service/TestModelLoaderService.java | 86 +++++ .../service/TestModelLoaderServiceWithSdc.java | 63 ++++ .../service/TestNotificationDataImpl.java | 83 ----- .../aai/modelloader/util/ArtifactTestUtils.java | 24 +- .../aai/modelloader/util/JsonXmlConverterTest.java | 78 ---- .../aai/modelloader/util/TestJsonXmlConverter.java | 82 +++++ src/test/resources/auth/aai-client-dummy.p12 | Bin 0 -> 2514 bytes .../AAI-SCP-Test-VSP-resource-1.0.xml | 51 +++ .../model-loader-empty-auth-password.properties | 25 +- .../model-loader-no-auth-password.properties | 25 +- src/test/resources/model-loader.properties | 12 +- .../resources/sdc_test/model-loader.properties | 30 ++ 49 files changed, 2316 insertions(+), 1767 deletions(-) create mode 100644 src/test/java/org/onap/aai/modelloader/TestModelLoaderApplication.java delete mode 100644 src/test/java/org/onap/aai/modelloader/config/ModelLoaderConfigTest.java create mode 100644 src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java create mode 100644 src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java delete mode 100644 src/test/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandlerTest.java delete mode 100644 src/test/java/org/onap/aai/modelloader/entity/model/ModelArtifactParserTest.java delete mode 100644 src/test/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifactParserTest.java create mode 100644 src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactParser.java create mode 100644 src/test/java/org/onap/aai/modelloader/entity/model/TestNamedQueryArtifactParser.java delete mode 100644 src/test/java/org/onap/aai/modelloader/extraction/ArtifactInfoExtractorTest.java create mode 100644 src/test/java/org/onap/aai/modelloader/extraction/TestArtifactInfoExtractor.java create mode 100644 src/test/java/org/onap/aai/modelloader/fixture/MockNotificationDataImpl.java delete mode 100644 src/test/java/org/onap/aai/modelloader/fixture/TestNotificationDataImpl.java delete mode 100644 src/test/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManagerTest.java delete mode 100644 src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java delete mode 100644 src/test/java/org/onap/aai/modelloader/notification/BabelArtifactConverterTest.java delete mode 100644 src/test/java/org/onap/aai/modelloader/notification/EventCallbackTest.java create mode 100644 src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java create mode 100644 src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java create mode 100644 src/test/java/org/onap/aai/modelloader/notification/TestBabelArtifactConverter.java create mode 100644 src/test/java/org/onap/aai/modelloader/notification/TestEventCallback.java create mode 100644 src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java create mode 100644 src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java create mode 100644 src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java create mode 100644 src/test/java/org/onap/aai/modelloader/service/MockBabelServiceClientFactory.java delete mode 100644 src/test/java/org/onap/aai/modelloader/service/TestModelLoaderApplication.java create mode 100644 src/test/java/org/onap/aai/modelloader/service/TestModelLoaderService.java create mode 100644 src/test/java/org/onap/aai/modelloader/service/TestModelLoaderServiceWithSdc.java delete mode 100644 src/test/java/org/onap/aai/modelloader/service/TestNotificationDataImpl.java delete mode 100644 src/test/java/org/onap/aai/modelloader/util/JsonXmlConverterTest.java create mode 100644 src/test/java/org/onap/aai/modelloader/util/TestJsonXmlConverter.java create mode 100644 src/test/resources/auth/aai-client-dummy.p12 create mode 100644 src/test/resources/convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml create mode 100644 src/test/resources/sdc_test/model-loader.properties (limited to 'src/test') diff --git a/src/test/java/org/onap/aai/modelloader/TestModelLoaderApplication.java b/src/test/java/org/onap/aai/modelloader/TestModelLoaderApplication.java new file mode 100644 index 0000000..c54f43e --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/TestModelLoaderApplication.java @@ -0,0 +1,42 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader; + +import org.junit.Test; +import org.onap.aai.modelloader.ModelLoaderApplication; + +/** + * Tests for ModelLoaderApplication class. + * + */ +public class TestModelLoaderApplication { + + static { + System.setProperty("CONFIG_HOME", "src/test/resources"); + } + + @Test + public void testServiceStarts() { + // The SDC Distribution Client is disabled. + ModelLoaderApplication.main(new String[0]); + } + +} diff --git a/src/test/java/org/onap/aai/modelloader/config/ModelLoaderConfigTest.java b/src/test/java/org/onap/aai/modelloader/config/ModelLoaderConfigTest.java deleted file mode 100644 index e8060e2..0000000 --- a/src/test/java/org/onap/aai/modelloader/config/ModelLoaderConfigTest.java +++ /dev/null @@ -1,192 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.config; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.List; -import java.util.Properties; -import org.eclipse.jetty.util.security.Password; -import org.junit.Test; -import org.onap.aai.modelloader.restclient.AaiRestClient; -import org.onap.sdc.utils.ArtifactTypeEnum; - -/** - * Tests for ModelLoaderConfig class - * - */ -public class ModelLoaderConfigTest { - - @Test - public void testYangModelArtifactType() { - Properties props = new Properties(); - props.setProperty("ml.distribution.ARTIFACT_TYPES", "MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG"); - ModelLoaderConfig config = new ModelLoaderConfig(props, null); - - List types = config.getRelevantArtifactTypes(); - - System.out.println("ArtifactType: " + types.get(0)); - assertEquals(0, types.get(0).compareToIgnoreCase(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.toString())); - - System.out.println("ArtifactType: " + types.get(1)); - assertEquals(0, types.get(1).compareToIgnoreCase(ArtifactTypeEnum.MODEL_QUERY_SPEC.toString())); - - System.out.println("ArtifactType: " + types.get(2)); - assertEquals(0, types.get(2).compareToIgnoreCase(ArtifactTypeEnum.VNF_CATALOG.toString())); - - assertEquals(3, types.size()); - } - - @Test - public void testMsgBusAddrs() { - Properties props = new Properties(); - props.setProperty("ml.distribution.MSG_BUS_ADDRESSES", "host1.onap.com:3904,host2.onap.com:3904"); - ModelLoaderConfig config = new ModelLoaderConfig(props, null); - - List addrs = config.getMsgBusAddress(); - - assertEquals(2, addrs.size()); - assertEquals(0, addrs.get(0).compareToIgnoreCase("host1.onap.com:3904")); - assertEquals(0, addrs.get(1).compareToIgnoreCase("host2.onap.com:3904")); - } - - @Test - public void testDecryptPassword() { - String password = "youshallnotpass"; - ModelLoaderConfig config = - createObfuscatedTestConfig(ModelLoaderConfig.PROP_ML_DISTRIBUTION_PASSWORD, password); - assertEquals(password, config.getPassword()); - } - - @Test - public void testDecryptKeystorePassword() { - String password = "youshallnotpass"; - ModelLoaderConfig config = - createObfuscatedTestConfig(ModelLoaderConfig.PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD, password); - assertEquals(password, config.getKeyStorePassword()); - } - - @Test - public void testDecryptAAIAuthenticationPassword() { - String password = "myvoiceismypassword"; - ModelLoaderConfig config = - createObfuscatedTestConfig(ModelLoaderConfig.PROP_AAI_AUTHENTICATION_PASSWORD, password); - assertEquals(password, config.getAaiAuthenticationPassword()); - } - - @Test - public void testDecryptAAIKeystorePassword() { - String password = "myvoiceismypassword"; - ModelLoaderConfig config = createObfuscatedTestConfig(ModelLoaderConfig.PROP_AAI_KEYSTORE_PASSWORD, password); - assertEquals(password, config.getAaiKeyStorePassword()); - } - - @Test - public void testAaiBaseUrl() { - String url = "http://localhost:1234/"; - Properties props = new Properties(); - props.put(ModelLoaderConfig.PROP_AAI_BASE_URL, url); - ModelLoaderConfig config = new ModelLoaderConfig(props, null); - assertEquals(url, config.getAaiBaseUrl()); - } - - @Test - public void testDecryptBabelKeystorePassword() { - String password = "babelpassword"; - ModelLoaderConfig config = createObfuscatedTestConfig(ModelLoaderConfig.PROP_BABEL_KEYSTORE_PASSWORD, password); - assertEquals(password, config.getBabelKeyStorePassword()); - } - - @Test - public void testBabelKeystorePath() { - String root = "path_to_keystore"; - String path = "relative_keystore_path"; - Properties props = new Properties(); - props.put(ModelLoaderConfig.PROP_BABEL_KEYSTORE_FILE, path); - ModelLoaderConfig config = new ModelLoaderConfig(props, root); - assertEquals(root + File.separator + path, config.getBabelKeyStorePath()); - } - - @Test - public void testBabelBaseUrl() { - String url = "http://localhost/"; - Properties props = new Properties(); - props.put(ModelLoaderConfig.PROP_BABEL_BASE_URL, url); - ModelLoaderConfig config = new ModelLoaderConfig(props, null); - assertEquals(url, config.getBabelBaseUrl()); - } - - @Test - public void testBabelGenerateArtifactsUrl() { - String url = "/path/to/the/resource"; - Properties props = new Properties(); - props.put(ModelLoaderConfig.PROP_BABEL_GENERATE_RESOURCE_URL, url); - ModelLoaderConfig config = new ModelLoaderConfig(props, null); - assertEquals(url, config.getBabelGenerateArtifactsUrl()); - } - - @Test - public void testNoAAIAuth() throws IOException { - - Properties props = new Properties(); - props.load(new FileInputStream("src/test/resources/model-loader-empty-auth-password.properties")); - - ModelLoaderConfig config = new ModelLoaderConfig(props, null); - AaiRestClient aaiClient = new AaiRestClient(config); - - assertFalse("Empty AAI Password should result in no basic authentication", aaiClient.useBasicAuth()); - - props.load(new FileInputStream("src/test/resources/model-loader-no-auth-password.properties")); - config = new ModelLoaderConfig(props, null); - aaiClient = new AaiRestClient(config); - - assertFalse("No AAI Password should result in no basic authentication", aaiClient.useBasicAuth()); - } - - @Test - public void testGetUrls() { - Properties props = new Properties(); - props.put(ModelLoaderConfig.PROP_AAI_MODEL_RESOURCE_URL, "/aai/v*/service-design-and-creation/models/model/"); - props.put(ModelLoaderConfig.PROP_AAI_NAMED_QUERY_RESOURCE_URL, - "/aai/v*/service-design-and-creation/named-queries/named-query/"); - ModelLoaderConfig config = new ModelLoaderConfig(props, null); - - assertEquals("/aai/v9/service-design-and-creation/models/model/", config.getAaiModelUrl("v9")); - assertEquals("/aai/v10/service-design-and-creation/named-queries/named-query/", - config.getAaiNamedQueryUrl("v10")); - } - - - /** - * @param propertyName - * @param propertyValue - * @return a new ModelLoaderConfig object containing a single obfuscated property value - */ - private ModelLoaderConfig createObfuscatedTestConfig(String propertyName, String propertyValue) { - Properties props = new Properties(); - props.put(propertyName, Password.obfuscate(propertyValue)); - return new ModelLoaderConfig(props, null); - } -} diff --git a/src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java b/src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java new file mode 100644 index 0000000..bfd793a --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java @@ -0,0 +1,193 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.config; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import org.eclipse.jetty.util.security.Password; +import org.junit.Test; +import org.onap.aai.modelloader.restclient.AaiRestClient; +import org.onap.sdc.utils.ArtifactTypeEnum; + +/** + * Tests for ModelLoaderConfig class. + * + */ +public class TestModelLoaderConfig { + + @Test + public void testYangModelArtifactType() { + Properties props = new Properties(); + props.setProperty("ml.distribution.ARTIFACT_TYPES", "MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG"); + ModelLoaderConfig config = new ModelLoaderConfig(props, null); + + List types = config.getRelevantArtifactTypes(); + + System.out.println("ArtifactType: " + types.get(0)); + assertEquals(0, types.get(0).compareToIgnoreCase(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.toString())); + + System.out.println("ArtifactType: " + types.get(1)); + assertEquals(0, types.get(1).compareToIgnoreCase(ArtifactTypeEnum.MODEL_QUERY_SPEC.toString())); + + System.out.println("ArtifactType: " + types.get(2)); + assertEquals(0, types.get(2).compareToIgnoreCase(ArtifactTypeEnum.VNF_CATALOG.toString())); + + assertEquals(3, types.size()); + } + + @Test + public void testMsgBusAddrs() { + Properties props = new Properties(); + props.setProperty("ml.distribution.MSG_BUS_ADDRESSES", "host1.onap.com:3904,host2.onap.com:3904"); + ModelLoaderConfig config = new ModelLoaderConfig(props, null); + + List addrs = config.getMsgBusAddress(); + + assertEquals(2, addrs.size()); + assertEquals(0, addrs.get(0).compareToIgnoreCase("host1.onap.com:3904")); + assertEquals(0, addrs.get(1).compareToIgnoreCase("host2.onap.com:3904")); + } + + @Test + public void testDecryptPassword() { + String password = "youshallnotpass"; + ModelLoaderConfig config = + createObfuscatedTestConfig(ModelLoaderConfig.PROP_ML_DISTRIBUTION_PASSWORD, password); + assertEquals(password, config.getPassword()); + } + + @Test + public void testDecryptKeystorePassword() { + String password = "youshallnotpass"; + ModelLoaderConfig config = + createObfuscatedTestConfig(ModelLoaderConfig.PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD, password); + assertEquals(password, config.getKeyStorePassword()); + } + + @Test + public void testDecryptAaiAuthenticationPassword() { + String password = "myvoiceismypassword"; + ModelLoaderConfig config = + createObfuscatedTestConfig(ModelLoaderConfig.PROP_AAI_AUTHENTICATION_PASSWORD, password); + assertEquals(password, config.getAaiAuthenticationPassword()); + } + + @Test + public void testDecryptAaiKeystorePassword() { + String password = "myvoiceismypassword"; + ModelLoaderConfig config = createObfuscatedTestConfig(ModelLoaderConfig.PROP_AAI_KEYSTORE_PASSWORD, password); + assertEquals(password, config.getAaiKeyStorePassword()); + } + + @Test + public void testAaiBaseUrl() { + String url = "http://localhost:1234/"; + Properties props = new Properties(); + props.put(ModelLoaderConfig.PROP_AAI_BASE_URL, url); + ModelLoaderConfig config = new ModelLoaderConfig(props, null); + assertEquals(url, config.getAaiBaseUrl()); + } + + @Test + public void testDecryptBabelKeystorePassword() { + String password = "babelpassword"; + ModelLoaderConfig config = createObfuscatedTestConfig(ModelLoaderConfig.PROP_BABEL_KEYSTORE_PASSWORD, password); + assertEquals(password, config.getBabelKeyStorePassword()); + } + + @Test + public void testBabelKeystorePath() { + String root = "path_to_keystore"; + String path = "relative_keystore_path"; + Properties props = new Properties(); + props.put(ModelLoaderConfig.PROP_BABEL_KEYSTORE_FILE, path); + ModelLoaderConfig config = new ModelLoaderConfig(props, root); + assertEquals(root + File.separator + path, config.getBabelKeyStorePath()); + } + + @Test + public void testBabelBaseUrl() { + String url = "http://localhost/"; + Properties props = new Properties(); + props.put(ModelLoaderConfig.PROP_BABEL_BASE_URL, url); + ModelLoaderConfig config = new ModelLoaderConfig(props, null); + assertEquals(url, config.getBabelBaseUrl()); + } + + @Test + public void testBabelGenerateArtifactsUrl() { + String url = "/path/to/the/resource"; + Properties props = new Properties(); + props.put(ModelLoaderConfig.PROP_BABEL_GENERATE_RESOURCE_URL, url); + ModelLoaderConfig config = new ModelLoaderConfig(props, null); + assertEquals(url, config.getBabelGenerateArtifactsUrl()); + } + + @Test + public void testMissingAuthenticationProperties() throws IOException { + Properties props = new Properties(); + props.load(new FileInputStream("src/test/resources/model-loader-empty-auth-password.properties")); + + ModelLoaderConfig config = new ModelLoaderConfig(props, null); + AaiRestClient aaiClient = new AaiRestClient(config); + + assertFalse("Empty AAI Password should result in no basic authentication", aaiClient.useBasicAuth()); + + props.load(new FileInputStream("src/test/resources/model-loader-no-auth-password.properties")); + config = new ModelLoaderConfig(props, null); + aaiClient = new AaiRestClient(config); + + assertFalse("No AAI Password should result in no basic authentication", aaiClient.useBasicAuth()); + } + + @Test + public void testGetUrls() { + Properties props = new Properties(); + props.put(ModelLoaderConfig.PROP_AAI_MODEL_RESOURCE_URL, "/aai/v*/service-design-and-creation/models/model/"); + props.put(ModelLoaderConfig.PROP_AAI_NAMED_QUERY_RESOURCE_URL, + "/aai/v*/service-design-and-creation/named-queries/named-query/"); + ModelLoaderConfig config = new ModelLoaderConfig(props, null); + + assertEquals("/aai/v9/service-design-and-creation/models/model/", config.getAaiModelUrl("v9")); + assertEquals("/aai/v10/service-design-and-creation/named-queries/named-query/", + config.getAaiNamedQueryUrl("v10")); + } + + + /** + * Create a Model Loader Configuration object from the supplied Property. + * + * @param propertyName property key + * @param propertyValue value of the property + * @return a new ModelLoaderConfig object containing a single obfuscated property value + */ + private ModelLoaderConfig createObfuscatedTestConfig(String propertyName, String propertyValue) { + Properties props = new Properties(); + props.put(propertyName, Password.obfuscate(propertyValue)); + return new ModelLoaderConfig(props, null); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java new file mode 100644 index 0000000..b54bb20 --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java @@ -0,0 +1,130 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.entity.catalog; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.entity.Artifact; +import org.onap.aai.modelloader.restclient.AaiRestClient; +import org.onap.aai.restclient.client.OperationResult; + +public class TestVnfCatalogArtifactHandler { + + protected static String CONFIG_FILE = "model-loader.properties"; + + private AaiRestClient mockRestClient = mock(AaiRestClient.class); + + /** + * Update A&AI with 4 images, 2 of which already exist. + * + * @throws Exception + */ + @Test + public void testUpdateVnfImages() throws Exception { + // GET operation + OperationResult mockGetResp = mock(OperationResult.class); + + // @formatter:off + when(mockGetResp.getResultCode()) + .thenReturn(Response.Status.OK.getStatusCode()) + .thenReturn(Response.Status.NOT_FOUND.getStatusCode()) + .thenReturn(Response.Status.NOT_FOUND.getStatusCode()) + .thenReturn(Response.Status.OK.getStatusCode()); + // @formatter:on + + when(mockRestClient.getResource(Mockito.anyString(), Mockito.anyString(), Mockito.any(MediaType.class))) + .thenReturn(mockGetResp); + mockPutOperations(); + + // Example VNF Catalog XML + VnfCatalogArtifactHandler handler = new VnfCatalogArtifactHandler(createConfig()); + assertThat(handler.pushArtifacts(createVnfCatalogArtifact(), "test", new ArrayList(), mockRestClient), + is(true)); + + assertPutOperationsSucceeded(); + } + + private ModelLoaderConfig createConfig() { + Properties configProperties = new Properties(); + try { + configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE)); + } catch (IOException e) { + fail(); + } + ModelLoaderConfig config = new ModelLoaderConfig(configProperties, null); + return config; + } + + /** + * Example VNF Catalog based on JSON data (returned by Babel) + * + * @return test Artifacts + * @throws IOException + * @throws UnsupportedEncodingException + */ + private List createVnfCatalogArtifact() throws IOException, UnsupportedEncodingException { + String examplePath = "src/test/resources/imagedataexample.json"; + byte[] encoded = Files.readAllBytes(Paths.get(examplePath)); + List artifacts = new ArrayList(); + artifacts.add(new VnfCatalogArtifact(new String(encoded, "utf-8"))); + return artifacts; + } + + /** + * Always return CREATED (success) for a PUT operation. + */ + private void mockPutOperations() { + OperationResult mockPutResp = mock(OperationResult.class); + when(mockPutResp.getResultCode()).thenReturn(Response.Status.CREATED.getStatusCode()); + when(mockRestClient.putResource(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.any(MediaType.class))).thenReturn(mockPutResp); + } + + private void assertPutOperationsSucceeded() { + // Only two of the VNF images should be pushed + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + AaiRestClient mockedClient = Mockito.verify(mockRestClient, Mockito.times(2)); + mockedClient.putResource(Mockito.anyString(), argument.capture(), Mockito.anyString(), + Mockito.any(MediaType.class)); + assertThat(argument.getAllValues().get(0), containsString("3.16.9")); + assertThat(argument.getAllValues().get(0), containsString("VM00")); + assertThat(argument.getAllValues().get(1), containsString("3.16.1")); + assertThat(argument.getAllValues().get(1), containsString("VM01")); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java index a41ddf9..c8b14f7 100644 --- a/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java +++ b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -27,7 +27,7 @@ import static org.junit.Assert.assertThat; import org.junit.Test; /** - * Tests for NotificationDataImpl class + * Tests for NotificationDataImpl class. * */ public class TestVnfImageException { @@ -41,8 +41,7 @@ public class TestVnfImageException { assertThat(exception.getImageId(), is(equalTo("id2"))); assertThat(exception.getResultCode().get(), is(equalTo(1))); - Exception e = new Exception("message"); - exception = new VnfImageException(e); + exception = new VnfImageException(new Exception("message")); assertThat(exception.getImageId(), is(equalTo("message"))); } diff --git a/src/test/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandlerTest.java b/src/test/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandlerTest.java deleted file mode 100644 index b6d4564..0000000 --- a/src/test/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandlerTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.entity.catalog; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.onap.aai.modelloader.config.ModelLoaderConfig; -import org.onap.aai.modelloader.entity.Artifact; -import org.onap.aai.modelloader.restclient.AaiRestClient; -import org.onap.aai.restclient.client.OperationResult; - -public class VnfCatalogArtifactHandlerTest { - - protected static String CONFIG_FILE = "model-loader.properties"; - - @Test - public void testWithMocks() throws Exception { - - Properties configProperties = new Properties(); - try { - configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE)); - } catch (IOException e) { - fail(); - } - ModelLoaderConfig config = new ModelLoaderConfig(configProperties, null); - config.setModelVersion("11"); - - AaiRestClient mockRestClient = mock(AaiRestClient.class); - - // GET operation - OperationResult mockGetResp = mock(OperationResult.class); - - // @formatter:off - when(mockGetResp.getResultCode()) - .thenReturn(Response.Status.OK.getStatusCode()) - .thenReturn(Response.Status.NOT_FOUND.getStatusCode()) - .thenReturn(Response.Status.NOT_FOUND.getStatusCode()) - .thenReturn(Response.Status.OK.getStatusCode()); - // @formatter:on - when(mockRestClient.getResource(Mockito.anyString(), Mockito.anyString(), Mockito.any(MediaType.class))) - .thenReturn(mockGetResp); - - // PUT operation - OperationResult mockPutResp = mock(OperationResult.class); - - when(mockPutResp.getResultCode()).thenReturn(Response.Status.CREATED.getStatusCode()); - when(mockRestClient.putResource(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), - Mockito.any(MediaType.class))).thenReturn(mockPutResp); - - // Example VNF Catalog with - VnfCatalogArtifactHandler vnfCAH = new VnfCatalogArtifactHandler(config); - String examplePath = "src/test/resources/imagedataexample.json"; - byte[] encoded = Files.readAllBytes(Paths.get(examplePath)); - List artifacts = new ArrayList(); - artifacts.add(new VnfCatalogArtifact(new String(encoded, "utf-8"))); - - assertTrue(vnfCAH.pushArtifacts(artifacts, "test", new ArrayList(), mockRestClient)); - - // Only two of the VNF images should be pushed - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - AaiRestClient r = Mockito.verify(mockRestClient, Mockito.times(2)); - r.putResource(Mockito.anyString(), argument.capture(), Mockito.anyString(), Mockito.any(MediaType.class)); - assertTrue(argument.getAllValues().get(0).contains("3.16.9")); - assertTrue(argument.getAllValues().get(0).contains("VM00")); - assertTrue(argument.getAllValues().get(1).contains("3.16.1")); - assertTrue(argument.getAllValues().get(1).contains("VM01")); - } -} diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/ModelArtifactParserTest.java b/src/test/java/org/onap/aai/modelloader/entity/model/ModelArtifactParserTest.java deleted file mode 100644 index 84a4313..0000000 --- a/src/test/java/org/onap/aai/modelloader/entity/model/ModelArtifactParserTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.entity.model; - -import static org.junit.Assert.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.List; -import org.junit.Test; -import org.onap.aai.modelloader.entity.Artifact; - -public class ModelArtifactParserTest { - - @Test - public void testParseModelFileNoDeps() throws Exception { - final String MODEL_FILE = "src/test/resources/models/l3-network-widget.xml"; - - try { - String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE))); - - ModelArtifactParser parser = new ModelArtifactParser(); - List modelList = parser.parse(fileString, "test-artifact"); - - assertTrue(modelList.size() == 1); - - ModelArtifact model = (ModelArtifact) modelList.get(0); - System.out.println(model.toString()); - - assertTrue(model.getModelInvariantId().equalsIgnoreCase("3d560d81-57d0-438b-a2a1-5334dba0651a")); - assertTrue(model.getModelNamespace().equalsIgnoreCase("http://org.openecomp.aai.inventory/v9")); - assertTrue(model.getModelNamespaceVersion().equalsIgnoreCase("v9")); - assertTrue(model.getType().toString().equalsIgnoreCase("MODEL")); - System.out.println(model.getDependentModelIds().size()); - assertTrue(model.getDependentModelIds().size() == 0); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void testParseModelFileDeps() throws Exception { - final String MODEL_FILE = "src/test/resources/models/AAI-stellService-service-1.xml"; - - try { - String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE))); - - ModelArtifactParser parser = new ModelArtifactParser(); - List modelList = parser.parse(fileString, "test-artifact"); - - assertTrue(modelList.size() == 1); - - ModelArtifact model = (ModelArtifact) modelList.get(0); - System.out.println(model.toString()); - - assertTrue(model.getModelInvariantId().equalsIgnoreCase("fedf9da3-6a74-4813-8fa2-221a98b0e7ad")); - assertTrue(model.getModelVerId().equalsIgnoreCase("e0373537-7f66-4094-9939-e2f5de6ff5f6")); - assertTrue(model.getType().toString().equalsIgnoreCase("MODEL")); - assertTrue(model.getDependentModelIds().size() == 3); - assertTrue(model.getDependentModelIds() - .contains("5c12984d-db0f-4300-a0e0-9791775cc40f|88bdbadf-db8a-490f-881e-c8effcbc3f66")); - assertTrue(model.getDependentModelIds() - .contains("959b7c09-9f34-4e5f-8b63-505381db176e|374d0899-bbc2-4403-9320-fe9bebef75c6")); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void testParseModelFileInvalidArtifact() throws Exception { - final String MODEL_FILE = "src/test/resources/models/invalid-model.xml"; - - try { - String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE))); - - ModelArtifactParser parser = new ModelArtifactParser(); - List modelList = parser.parse(fileString, "test-artifact"); - - assertTrue(modelList == null || modelList.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void testParseModelFileIncompleteArtifact() throws Exception { - final String MODEL_FILE = "src/test/resources/models/incomplete-model.xml"; - - try { - String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE))); - - ModelArtifactParser parser = new ModelArtifactParser(); - List modelList = parser.parse(fileString, "test-artifact"); - - assertTrue(modelList == null || modelList.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } -} diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java b/src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java index d1d54b7..8f4bf8d 100644 --- a/src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java +++ b/src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -24,6 +24,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.isEmptyString; import static org.junit.Assert.assertThat; import java.util.ArrayList; @@ -40,17 +41,18 @@ public class ModelSorterTest { ModelArtifact model = buildTestModel(); ModelSorter.Node nodeA = new ModelSorter.Node(model); ModelSorter.Node nodeB = new ModelSorter.Node(model); - ModelSorter.Node nodeC = new ModelSorter.Node(model); ModelSorter.Edge edgeA = new ModelSorter.Edge(nodeA, nodeB); - ModelSorter.Edge edgeB = new ModelSorter.Edge(nodeA, nodeB); - ModelSorter.Edge edgeC = new ModelSorter.Edge(nodeB, nodeA); - ModelSorter.Edge edgeD = new ModelSorter.Edge(nodeA, nodeC); assertThat(edgeA, is(equalTo(edgeA))); assertThat(edgeA, is(not(equalTo(null)))); assertThat(edgeA, is(not(equalTo(model)))); + ModelSorter.Edge edgeB = new ModelSorter.Edge(nodeA, nodeB); + ModelSorter.Edge edgeC = new ModelSorter.Edge(nodeB, nodeA); + + ModelSorter.Node nodeC = new ModelSorter.Node(model); + ModelSorter.Edge edgeD = new ModelSorter.Edge(nodeA, nodeC); assertThat(edgeA, is(equalTo(edgeB))); assertThat(edgeA, is(not(equalTo(edgeC)))); assertThat(edgeA, is(not(equalTo(edgeD)))); @@ -60,17 +62,31 @@ public class ModelSorterTest { public void nodeEquality() throws BabelArtifactParsingException { ModelArtifact model = buildTestModel(); ModelSorter.Node nodeA = new ModelSorter.Node(model); - ModelSorter.Node nodeB = new ModelSorter.Node(model); assertThat(nodeA, is(equalTo(nodeA))); assertThat(nodeA, is(not(equalTo(null)))); assertThat(nodeA, is(not(equalTo(model)))); + ModelSorter.Node nodeB = new ModelSorter.Node(model); assertThat(nodeA, is(equalTo(nodeB))); assertThat(nodeA.toString(), is(equalTo(nodeB.toString()))); assertThat(nodeA, is(not(equalTo(new ModelSorter.Node(new ModelArtifact()))))); } + @Test + public void testToString() throws BabelArtifactParsingException { + ModelArtifact model = buildTestModel(); + + ModelSorter.Node nodeA = new ModelSorter.Node(model); + assertThat(nodeA.toString(), not(isEmptyString())); + + ModelSorter.Node nodeB = new ModelSorter.Node(model); + nodeA.addEdge(nodeB); + assertThat(nodeA.toString(), not(isEmptyString())); + assertThat(nodeB.toString(), not(isEmptyString())); + + } + @Test public void noModels() throws BabelArtifactParsingException { assertThat(new ModelSorter().sort(null), is(nullValue())); @@ -84,20 +100,32 @@ public class ModelSorterTest { @Test public void multipleModels() throws BabelArtifactParsingException { - Artifact a = buildTestModel("aaaa", "mvaaaa", "cccc|mvcccc"); - Artifact b = buildTestModel("bbbb", "mvbbbb", "aaaa|mvaaaa"); - Artifact c = buildTestModel("cccc", "mvcccc"); - List expected = Arrays.asList(c, a, b); - assertThat(new ModelSorter().sort(Arrays.asList(a, b, c)), is(expected)); + Artifact artA = buildTestModel("aaaa", "mvaaaa", "cccc|mvcccc"); + Artifact artB = buildTestModel("bbbb", "mvbbbb", "aaaa|mvaaaa"); + Artifact artC = buildTestModel("cccc", "mvcccc"); + List expected = Arrays.asList(artC, artA, artB); + assertThat(new ModelSorter().sort(Arrays.asList(artA, artB, artC)), is(expected)); + } + + + @Test + public void multipleModelsWithMultipleIncomingEdges() throws BabelArtifactParsingException { + ModelArtifact artA = buildTestModel("aaaa", "mvaaaa", "cccc|mvcccc"); + Artifact artB = buildTestModel("bbbb", "mvbbbb", "aaaa|mvaaaa"); + Artifact artC = buildTestModel("cccc", "mvcccc"); + Artifact artD = buildTestModel("dddd", "mvdddd", "cccc|mvcccc"); + artA.addDependentModelId("dddd|mvdddd"); + List expected = Arrays.asList(artC, artD, artA, artB); + assertThat(new ModelSorter().sort(Arrays.asList(artA, artB, artC, artD)), is(expected)); } @Test public void multipleModelsAndNamedQueries() throws BabelArtifactParsingException { - Artifact a = buildTestModel("aaaa", "1111", "cccc|2222"); + Artifact artifact = buildTestModel("aaaa", "1111", "cccc|2222"); Artifact nq1 = buildTestNamedQuery("nq1", "aaaa|1111"); Artifact nq2 = buildTestNamedQuery("nqw", "existing-model"); - List expected = Arrays.asList(a, nq2, nq1); - assertThat(new ModelSorter().sort(Arrays.asList(nq1, nq2, a)), is(expected)); + List expected = Arrays.asList(artifact, nq2, nq1); + assertThat(new ModelSorter().sort(Arrays.asList(nq1, nq2, artifact)), is(expected)); } @Test(expected = BabelArtifactParsingException.class) diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifactParserTest.java b/src/test/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifactParserTest.java deleted file mode 100644 index fa2d2d7..0000000 --- a/src/test/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifactParserTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.entity.model; - -import static org.junit.Assert.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.List; -import org.junit.Test; -import org.onap.aai.modelloader.entity.Artifact; - -public class NamedQueryArtifactParserTest { - - @Test - public void testParseNamedQuery() throws Exception { - final String MODEL_FILE = "src/test/resources/models/named-query-wan-connector.xml"; - - try { - String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE))); - - NamedQueryArtifactParser parser = new NamedQueryArtifactParser(); - List modelList = parser.parse(fileString, "test-artifact"); - - assertTrue(modelList.size() == 1); - - NamedQueryArtifact model = (NamedQueryArtifact) modelList.get(0); - System.out.println(model.toString()); - - assertTrue(model.getNamedQueryUuid().equalsIgnoreCase("94cac189-8d88-4d63-a194-f44214e080ff")); - assertTrue(model.getType().toString().equalsIgnoreCase("NAMED_QUERY")); - assertTrue(model.getDependentModelIds().size() == 4); - assertTrue(model.getDependentModelIds().contains("d09dd9da-0148-46cd-a947-591afc844d24")); - assertTrue(model.getDependentModelIds().contains("997fc7-fca1-451f-b953-9a1e6197b4d6")); - assertTrue(model.getDependentModelIds().contains("897df7ea-8938-42b0-bc57-46e913a4d93b")); - assertTrue(model.getDependentModelIds().contains("f2b24d95-c582-48d5-b2d6-c5b3a94ce812")); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - -} diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java index 82990de..2a951a8 100644 --- a/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java +++ b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactParser.java b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactParser.java new file mode 100644 index 0000000..aef0acc --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactParser.java @@ -0,0 +1,102 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.entity.model; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase; +import static org.junit.Assert.assertThat; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; +import org.junit.Test; +import org.onap.aai.modelloader.entity.Artifact; +import org.springframework.util.CollectionUtils; + +public class TestModelArtifactParser { + + private static final String MODEL_FILE = "src/test/resources/models/l3-network-widget.xml"; + private static final String MODEL_FILE_SERVICE = "src/test/resources/models/AAI-stellService-service-1.xml"; + private static final String MODEL_FILE_INCOMPLETE = "src/test/resources/models/incomplete-model.xml"; + private static final String MODEL_FILE_INVALID = "src/test/resources/models/invalid-model.xml"; + + @Test + public void testParseModelFileNoDeps() throws Exception { + String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE))); + + ModelArtifactParser parser = new ModelArtifactParser(); + List modelList = parser.parse(fileString, "test-artifact"); + + assertThat(modelList.size(), is(1)); + + ModelArtifact model = (ModelArtifact) modelList.get(0); + assertThat(model.toString(), is(not(nullValue()))); + + assertThat(model.getModelInvariantId(), equalToIgnoringCase("3d560d81-57d0-438b-a2a1-5334dba0651a")); + assertThat(model.getModelNamespace(), equalToIgnoringCase("http://org.openecomp.aai.inventory/v9")); + assertThat(model.getModelNamespaceVersion(), equalToIgnoringCase("v9")); + assertThat(model.getType().toString(), equalToIgnoringCase("MODEL")); + assertThat(model.getDependentModelIds().size(), is(0)); + } + + @Test + public void testParseModelFileDeps() throws Exception { + String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE_SERVICE))); + + ModelArtifactParser parser = new ModelArtifactParser(); + List modelList = parser.parse(fileString, "test-artifact"); + + assertThat(modelList.size(), is(1)); + + ModelArtifact model = (ModelArtifact) modelList.get(0); + assertThat(model.toString(), is(not(nullValue()))); + assertThat(model.getModelInvariantId(), equalToIgnoringCase("fedf9da3-6a74-4813-8fa2-221a98b0e7ad")); + assertThat(model.getModelVerId(), equalToIgnoringCase("e0373537-7f66-4094-9939-e2f5de6ff5f6")); + assertThat(model.getType().toString(), equalToIgnoringCase("MODEL")); + assertThat(model.getDependentModelIds().size(), is(3)); + assertThat(model.getDependentModelIds() + .contains("5c12984d-db0f-4300-a0e0-9791775cc40f|88bdbadf-db8a-490f-881e-c8effcbc3f66"), is(true)); + assertThat(model.getDependentModelIds() + .contains("959b7c09-9f34-4e5f-8b63-505381db176e|374d0899-bbc2-4403-9320-fe9bebef75c6"), is(true)); + } + + @Test + public void testParseModelFileInvalidArtifact() throws Exception { + String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE_INVALID))); + + ModelArtifactParser parser = new ModelArtifactParser(); + List modelList = parser.parse(fileString, "test-artifact"); + + assertThat(CollectionUtils.isEmpty(modelList), is(true)); + } + + @Test + public void testParseModelFileIncompleteArtifact() throws Exception { + String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE_INCOMPLETE))); + + ModelArtifactParser parser = new ModelArtifactParser(); + List modelList = parser.parse(fileString, "test-artifact"); + + assertThat(CollectionUtils.isEmpty(modelList), is(true)); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/TestNamedQueryArtifactParser.java b/src/test/java/org/onap/aai/modelloader/entity/model/TestNamedQueryArtifactParser.java new file mode 100644 index 0000000..f676f8e --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/entity/model/TestNamedQueryArtifactParser.java @@ -0,0 +1,64 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.entity.model; + +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.Matchers.isEmptyString; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; +import org.junit.Test; +import org.onap.aai.modelloader.entity.Artifact; + +public class TestNamedQueryArtifactParser { + + private static final String MODEL_FILE = "src/test/resources/models/named-query-wan-connector.xml"; + + @Test + public void testParseNamedQuery() throws Exception { + try { + String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE))); + + NamedQueryArtifactParser parser = new NamedQueryArtifactParser(); + List modelList = parser.parse(fileString, "test-artifact"); + + assertTrue(modelList.size() == 1); + + NamedQueryArtifact model = (NamedQueryArtifact) modelList.get(0); + + assertThat(model.toString(), not(isEmptyString())); + assertTrue(model.getNamedQueryUuid().equalsIgnoreCase("94cac189-8d88-4d63-a194-f44214e080ff")); + assertTrue(model.getType().toString().equalsIgnoreCase("NAMED_QUERY")); + assertTrue(model.getDependentModelIds().size() == 4); + assertTrue(model.getDependentModelIds().contains("d09dd9da-0148-46cd-a947-591afc844d24")); + assertTrue(model.getDependentModelIds().contains("997fc7-fca1-451f-b953-9a1e6197b4d6")); + assertTrue(model.getDependentModelIds().contains("897df7ea-8938-42b0-bc57-46e913a4d93b")); + assertTrue(model.getDependentModelIds().contains("f2b24d95-c582-48d5-b2d6-c5b3a94ce812")); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + +} diff --git a/src/test/java/org/onap/aai/modelloader/extraction/ArtifactInfoExtractorTest.java b/src/test/java/org/onap/aai/modelloader/extraction/ArtifactInfoExtractorTest.java deleted file mode 100644 index 8ae2c7e..0000000 --- a/src/test/java/org/onap/aai/modelloader/extraction/ArtifactInfoExtractorTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.extraction; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getEmptyNotificationData; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneResource; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneService; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneServiceAndResources; - -import java.util.ArrayList; -import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.aai.modelloader.fixture.ArtifactInfoBuilder; -import org.onap.aai.modelloader.fixture.TestNotificationDataImpl; -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.INotificationData; - -/** - * Tests {@link ArtifactInfoExtractor} - */ -public class ArtifactInfoExtractorTest { - - private ArtifactInfoExtractor extractor; - - @Before - public void setup() { - extractor = new ArtifactInfoExtractor(); - } - - @After - public void tearDown() { - extractor = null; - } - - @Test - public void extract_nullDataSupplied() { - doEmptyArtifactsTest(null); - } - - private void doEmptyArtifactsTest(INotificationData notificationData) { - assertTrue("The list returned should have been empty", extractor.extract(notificationData).isEmpty()); - } - - @Test - public void extract_dataHasNullArtifacts() { - doEmptyArtifactsTest(new TestNotificationDataImpl()); - } - - @Test - public void extract_dataHasNoArtifacts() { - doEmptyArtifactsTest(getEmptyNotificationData()); - } - - @Test - public void dataHasOneServiceArtifact() { - IArtifactInfo expected = ArtifactInfoBuilder.build("S", "service", "description of service", "s1.0"); - - List artifacts = extractor.extract(getNotificationDataWithOneService()); - - assertTrue("One artifact should have been returned", artifacts.size() == 1); - assertEquals("The actual artifact did not match the expected one", expected, artifacts.get(0)); - } - - @Test - public void dataHasOneResourceArtifact() { - List expectedArtifacts = new ArrayList<>(); - expectedArtifacts.add(ArtifactInfoBuilder.build("R", "resource", "description of resource", "r1.0")); - - List artifacts = extractor.extract(getNotificationDataWithOneResource()); - - assertTrue("One artifact should have been returned", artifacts.size() == 1); - assertEquals("The actual artifact did not match the expected one", expectedArtifacts, artifacts); - } - - @Test - public void dataHasOneServiceAndTwoResources() { - List expectedArtifacts = new ArrayList<>(); - expectedArtifacts.add(ArtifactInfoBuilder.build("TOSCA_CSAR", "service", "description of service", "s1.0")); - expectedArtifacts.add(ArtifactInfoBuilder.build("TOSCA_CSAR", "resource", "description of resource", "r1.0")); - - List artifacts = extractor.extract(getNotificationDataWithOneServiceAndResources()); - - assertTrue("One artifact should have been returned", artifacts.size() == 2); - assertEquals("The actual artifact did not match the expected one", expectedArtifacts, artifacts); - } -} diff --git a/src/test/java/org/onap/aai/modelloader/extraction/TestArtifactInfoExtractor.java b/src/test/java/org/onap/aai/modelloader/extraction/TestArtifactInfoExtractor.java new file mode 100644 index 0000000..3957c7c --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/extraction/TestArtifactInfoExtractor.java @@ -0,0 +1,108 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.extraction; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getEmptyNotificationData; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneResource; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneService; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneServiceAndResources; + +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.modelloader.fixture.ArtifactInfoBuilder; +import org.onap.aai.modelloader.fixture.MockNotificationDataImpl; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; + +/** + * Tests {@link ArtifactInfoExtractor}. + */ +public class TestArtifactInfoExtractor { + + private ArtifactInfoExtractor extractor; + + @Before + public void setup() { + extractor = new ArtifactInfoExtractor(); + } + + @After + public void tearDown() { + extractor = null; + } + + @Test + public void extract_nullDataSupplied() { + doEmptyArtifactsTest(null); + } + + private void doEmptyArtifactsTest(INotificationData notificationData) { + assertTrue("The list returned should have been empty", extractor.extract(notificationData).isEmpty()); + } + + @Test + public void extract_dataHasNullArtifacts() { + doEmptyArtifactsTest(new MockNotificationDataImpl()); + } + + @Test + public void extract_dataHasNoArtifacts() { + doEmptyArtifactsTest(getEmptyNotificationData()); + } + + @Test + public void dataHasOneServiceArtifact() { + IArtifactInfo expected = ArtifactInfoBuilder.build("S", "service", "description of service", "s1.0"); + + List artifacts = extractor.extract(getNotificationDataWithOneService()); + + assertTrue("One artifact should have been returned", artifacts.size() == 1); + assertEquals("The actual artifact did not match the expected one", expected, artifacts.get(0)); + } + + @Test + public void dataHasOneResourceArtifact() { + List expectedArtifacts = new ArrayList<>(); + expectedArtifacts.add(ArtifactInfoBuilder.build("R", "resource", "description of resource", "r1.0")); + + List artifacts = extractor.extract(getNotificationDataWithOneResource()); + + assertTrue("One artifact should have been returned", artifacts.size() == 1); + assertEquals("The actual artifact did not match the expected one", expectedArtifacts, artifacts); + } + + @Test + public void dataHasOneServiceAndTwoResources() { + List expectedArtifacts = new ArrayList<>(); + expectedArtifacts.add(ArtifactInfoBuilder.build("TOSCA_CSAR", "service", "description of service", "s1.0")); + expectedArtifacts.add(ArtifactInfoBuilder.build("TOSCA_CSAR", "resource", "description of resource", "r1.0")); + + List artifacts = extractor.extract(getNotificationDataWithOneServiceAndResources()); + + assertTrue("One artifact should have been returned", artifacts.size() == 2); + assertEquals("The actual artifact did not match the expected one", expectedArtifacts, artifacts); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/fixture/ArtifactInfoBuilder.java b/src/test/java/org/onap/aai/modelloader/fixture/ArtifactInfoBuilder.java index aa475f3..a22e46f 100644 --- a/src/test/java/org/onap/aai/modelloader/fixture/ArtifactInfoBuilder.java +++ b/src/test/java/org/onap/aai/modelloader/fixture/ArtifactInfoBuilder.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -42,12 +42,12 @@ public class ArtifactInfoBuilder { */ public static IArtifactInfo build(final String type, final String name, final String description, final String version) { - IArtifactInfo artifact = new ArtifactInfoImpl(); + ArtifactInfoImpl artifact = new ArtifactInfoImpl(); - ((ArtifactInfoImpl) artifact).setArtifactType(type); - ((ArtifactInfoImpl) artifact).setArtifactName(name); - ((ArtifactInfoImpl) artifact).setArtifactDescription(description); - ((ArtifactInfoImpl) artifact).setArtifactVersion(version); + artifact.setArtifactType(type); + artifact.setArtifactName(name); + artifact.setArtifactDescription(description); + artifact.setArtifactVersion(version); return artifact; } @@ -63,7 +63,7 @@ public class ArtifactInfoBuilder { *

* * @param artifactInfoBits a two dimensional array of data used to build the artifacts - * @return List a list of artifacts built from the given array of info + * @return List<IArtifactInfo> a list of artifacts built from the given array of info */ static List buildArtifacts(final String[][] artifactInfoBits) { List artifacts = new ArrayList<>(); diff --git a/src/test/java/org/onap/aai/modelloader/fixture/MockNotificationDataImpl.java b/src/test/java/org/onap/aai/modelloader/fixture/MockNotificationDataImpl.java new file mode 100644 index 0000000..7851690 --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/fixture/MockNotificationDataImpl.java @@ -0,0 +1,101 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.fixture; + +import java.util.List; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; + +/** + * This class is an implementation of INotificationData for test purposes. + */ +public class MockNotificationDataImpl implements INotificationData { + + private String distributionId; + private List resources; + private List serviceArtifacts; + + @Override + public String getDistributionID() { + return distributionId; + } + + @Override + public String getServiceName() { + return null; + } + + @Override + public String getServiceVersion() { + return null; + } + + @Override + public String getServiceUUID() { + return null; + } + + @Override + public String getServiceDescription() { + return null; + } + + @Override + public List getResources() { + return resources; + } + + @Override + public List getServiceArtifacts() { + return serviceArtifacts; + } + + @Override + public IArtifactInfo getArtifactMetadataByUUID(String uuid) { + return null; + } + + @Override + public String getServiceInvariantUUID() { + return null; + } + + public void setResources(List resources) { + this.resources = resources; + } + + public void setServiceArtifacts(List serviceArtifacts) { + this.serviceArtifacts = serviceArtifacts; + } + + public void setDistributionId(String distributionId) { + this.distributionId = distributionId; + } + + @Override + public String getWorkloadContext() { + return null; + } + + @Override + public void setWorkloadContext(String arg0) {} +} diff --git a/src/test/java/org/onap/aai/modelloader/fixture/NotificationDataFixtureBuilder.java b/src/test/java/org/onap/aai/modelloader/fixture/NotificationDataFixtureBuilder.java index 44f59a3..133a7af 100644 --- a/src/test/java/org/onap/aai/modelloader/fixture/NotificationDataFixtureBuilder.java +++ b/src/test/java/org/onap/aai/modelloader/fixture/NotificationDataFixtureBuilder.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -32,17 +32,19 @@ import org.onap.sdc.api.notification.IResourceInstance; public class NotificationDataFixtureBuilder { private static final String DESCRIPTION_OF_RESOURCE = "description of resource"; - private static final INotificationData EMPTY_NOTIFICATION_DATA = new TestNotificationDataImpl(); + private static final MockNotificationDataImpl EMPTY_NOTIFICATION_DATA = new MockNotificationDataImpl(); private static final String MODEL_QUERY_SPEC = "MODEL_QUERY_SPEC"; - private static final INotificationData NOTIFICATION_DATA_WITH_CATALOG_FILE = new TestNotificationDataImpl(); - private static final INotificationData NOTIFICATION_DATA_WITH_MODEL_QUERY_SPEC = new TestNotificationDataImpl(); - private static final INotificationData NOTIFICATION_DATA_WITH_INVALID_TYPE = new TestNotificationDataImpl(); - private static final INotificationData NOTIFICATION_DATA_WITH_ONE_OF_EACH = new TestNotificationDataImpl(); - private static final INotificationData NOTIFICATION_DATA_WITH_ONE_RESOURCE = new TestNotificationDataImpl(); - private static final INotificationData NOTIFICATION_DATA_WITH_ONE_SERVICE = new TestNotificationDataImpl(); - private static final INotificationData NOTIFICATION_DATA_WITH_ONE_SERVICE_AND_RESOURCES = - new TestNotificationDataImpl(); - private static final INotificationData NOTIFICATION_DATA_WITH_TOSCA_CSAR_FILE = new TestNotificationDataImpl(); + private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_CATALOG_FILE = new MockNotificationDataImpl(); + private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_MODEL_QUERY_SPEC = + new MockNotificationDataImpl(); + private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_INVALID_TYPE = new MockNotificationDataImpl(); + private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_ONE_OF_EACH = new MockNotificationDataImpl(); + private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_ONE_RESOURCE = new MockNotificationDataImpl(); + private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_ONE_SERVICE = new MockNotificationDataImpl(); + private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_ONE_SERVICE_AND_RESOURCES = + new MockNotificationDataImpl(); + private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_TOSCA_CSAR_FILE = + new MockNotificationDataImpl(); private static final String RESOURCE = "resource"; private static final String TOSCA_CSAR = "TOSCA_CSAR"; private static final String INVALID_TYPE = "INVALID_TYPE"; @@ -61,8 +63,8 @@ public class NotificationDataFixtureBuilder { } private static void buildEmptyNotificationData() { - ((TestNotificationDataImpl) EMPTY_NOTIFICATION_DATA).setResources(new ArrayList<>()); - ((TestNotificationDataImpl) EMPTY_NOTIFICATION_DATA).setServiceArtifacts(new ArrayList<>()); + EMPTY_NOTIFICATION_DATA.setResources(new ArrayList<>()); + EMPTY_NOTIFICATION_DATA.setServiceArtifacts(new ArrayList<>()); } private static void buildWithCatalogFile() { @@ -74,7 +76,7 @@ public class NotificationDataFixtureBuilder { List artifacts = ArtifactInfoBuilder.buildArtifacts(new String[][] {{"R", RESOURCE, DESCRIPTION_OF_RESOURCE, VERSION}}); resources.add(ResourceInstanceBuilder.build(artifacts)); - ((TestNotificationDataImpl) NOTIFICATION_DATA_WITH_ONE_RESOURCE).setResources(resources); + NOTIFICATION_DATA_WITH_ONE_RESOURCE.setResources(resources); } private static void buildWithModelQuerySpec() { @@ -96,18 +98,18 @@ public class NotificationDataFixtureBuilder { artifacts = ArtifactInfoBuilder .buildArtifacts(new String[][] {{MODEL_QUERY_SPEC, "resource2", "description of resource2", VERSION}}); resources.add(ResourceInstanceBuilder.build(artifacts)); - ((TestNotificationDataImpl) NOTIFICATION_DATA_WITH_ONE_OF_EACH).setResources(resources); + NOTIFICATION_DATA_WITH_ONE_OF_EACH.setResources(resources); } private static void buildWithOneService() { buildService("S", NOTIFICATION_DATA_WITH_ONE_SERVICE); } - private static void buildService(String type, INotificationData data) { + private static void buildService(String type, MockNotificationDataImpl data) { List artifacts = new ArrayList<>(); artifacts.add(ArtifactInfoBuilder.build(type, "service", "description of service", "s1.0")); - ((TestNotificationDataImpl) data).setDistributionID("ID"); - ((TestNotificationDataImpl) data).setServiceArtifacts(artifacts); + data.setDistributionId("ID"); + data.setServiceArtifacts(artifacts); } private static void buildWithOneServiceAndResources() { @@ -117,7 +119,7 @@ public class NotificationDataFixtureBuilder { List artifacts = ArtifactInfoBuilder .buildArtifacts(new String[][] {{TOSCA_CSAR, RESOURCE, "description of resource", VERSION}}); resources.add(ResourceInstanceBuilder.build(artifacts)); - ((TestNotificationDataImpl) NOTIFICATION_DATA_WITH_ONE_SERVICE_AND_RESOURCES).setResources(resources); + NOTIFICATION_DATA_WITH_ONE_SERVICE_AND_RESOURCES.setResources(resources); } private static void buildWithToscaCsarFile() { diff --git a/src/test/java/org/onap/aai/modelloader/fixture/ResourceInstanceBuilder.java b/src/test/java/org/onap/aai/modelloader/fixture/ResourceInstanceBuilder.java index 01e00f8..b88614b 100644 --- a/src/test/java/org/onap/aai/modelloader/fixture/ResourceInstanceBuilder.java +++ b/src/test/java/org/onap/aai/modelloader/fixture/ResourceInstanceBuilder.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -36,10 +36,8 @@ class ResourceInstanceBuilder { * @return IResourceInstance implementation of IResourceInstance for test purposes */ static IResourceInstance build(final List artifacts) { - IResourceInstance instance = new TestResourceInstanceImpl(); - - ((TestResourceInstanceImpl) instance).setArtifacts(artifacts); - + TestResourceInstanceImpl instance = new TestResourceInstanceImpl(); + instance.setArtifacts(artifacts); return instance; } } diff --git a/src/test/java/org/onap/aai/modelloader/fixture/TestNotificationDataImpl.java b/src/test/java/org/onap/aai/modelloader/fixture/TestNotificationDataImpl.java deleted file mode 100644 index a7defdf..0000000 --- a/src/test/java/org/onap/aai/modelloader/fixture/TestNotificationDataImpl.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.fixture; - -import java.util.List; -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.INotificationData; -import org.onap.sdc.api.notification.IResourceInstance; - -/** - * This class is an implementation of INotificationData for test purposes. - */ -public class TestNotificationDataImpl implements INotificationData { - - private String distributionID; - private List resources; - private List serviceArtifacts; - - @Override - public String getDistributionID() { - return distributionID; - } - - @Override - public String getServiceName() { - return null; - } - - @Override - public String getServiceVersion() { - return null; - } - - @Override - public String getServiceUUID() { - return null; - } - - @Override - public String getServiceDescription() { - return null; - } - - @Override - public List getResources() { - return resources; - } - - @Override - public List getServiceArtifacts() { - return serviceArtifacts; - } - - @Override - public IArtifactInfo getArtifactMetadataByUUID(String s) { - return null; - } - - @Override - public String getServiceInvariantUUID() { - return null; - } - - public void setResources(List resources) { - this.resources = resources; - } - - public void setServiceArtifacts(List serviceArtifacts) { - this.serviceArtifacts = serviceArtifacts; - } - - public void setDistributionID(String distributionID) { - this.distributionID = distributionID; - } - - @Override - public String getWorkloadContext() { - return null; - } - - @Override - public void setWorkloadContext(String arg0) {} -} diff --git a/src/test/java/org/onap/aai/modelloader/fixture/TestResourceInstanceImpl.java b/src/test/java/org/onap/aai/modelloader/fixture/TestResourceInstanceImpl.java index 7eaebb5..0f2751b 100644 --- a/src/test/java/org/onap/aai/modelloader/fixture/TestResourceInstanceImpl.java +++ b/src/test/java/org/onap/aai/modelloader/fixture/TestResourceInstanceImpl.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. diff --git a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManagerTest.java b/src/test/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManagerTest.java deleted file mode 100644 index 9d6f3c4..0000000 --- a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManagerTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.notification; - -import static org.junit.Assert.assertFalse; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithCatalogFile; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneOfEach; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.internal.util.reflection.Whitebox; -import org.onap.aai.babel.service.data.BabelArtifact; -import org.onap.aai.modelloader.config.ModelLoaderConfig; -import org.onap.aai.modelloader.entity.Artifact; -import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifact; -import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifactHandler; -import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; -import org.onap.aai.modelloader.entity.model.ModelArtifactHandler; -import org.onap.aai.modelloader.extraction.InvalidArchiveException; -import org.onap.aai.modelloader.util.ArtifactTestUtils; -import org.onap.sdc.api.IDistributionClient; -import org.onap.sdc.api.notification.INotificationData; - -/** - * Tests {@link ArtifactDeploymentManager } - */ -public class ArtifactDeploymentManagerTest { - - private static final String CONFIG_FILE = "model-loader.properties"; - private static final String SHOULD_HAVE_RETURNED_FALSE = "This should have returned false"; - - private Properties configProperties; - private ArtifactDeploymentManager manager; - - private IDistributionClient mockDistributionClient; - private ModelArtifactHandler mockModelArtifactHandler; - private NotificationPublisher mockNotificationPublisher; - private VnfCatalogArtifactHandler mockVnfCatalogArtifactHandler; - - @Before - public void setup() throws IOException { - configProperties = new Properties(); - configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE)); - ModelLoaderConfig config = new ModelLoaderConfig(configProperties, null); - - mockDistributionClient = mock(IDistributionClient.class); - mockModelArtifactHandler = mock(ModelArtifactHandler.class); - mockNotificationPublisher = mock(NotificationPublisher.class); - mockVnfCatalogArtifactHandler = mock(VnfCatalogArtifactHandler.class); - - manager = new ArtifactDeploymentManager(mockDistributionClient, config); - - Whitebox.setInternalState(manager, "modelArtifactHandler", mockModelArtifactHandler); - Whitebox.setInternalState(manager, "notificationPublisher", mockNotificationPublisher); - Whitebox.setInternalState(manager, "vnfCatalogArtifactHandler", mockVnfCatalogArtifactHandler); - } - - @After - public void tearDown() { - configProperties = null; - mockDistributionClient = null; - mockModelArtifactHandler = null; - mockNotificationPublisher = null; - mockVnfCatalogArtifactHandler = null; - manager = null; - } - - private List setupTest(byte[] xml, INotificationData data) throws IOException { - List toscaArtifacts = new ArrayList<>(); - org.onap.sdc.api.notification.IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); - - BabelArtifact xmlArtifact = - new BabelArtifact(artifactInfo.getArtifactName(), BabelArtifact.ArtifactType.MODEL, new String(xml)); - toscaArtifacts.add(xmlArtifact); - - return toscaArtifacts; - } - - @Test - public void deploy_catalogDeploymentsFailed() - throws IOException, BabelArtifactParsingException, InvalidArchiveException { - INotificationData data = getNotificationDataWithCatalogFile(); - - List catalogFiles = new ArrayList<>(); - catalogFiles.add(new VnfCatalogArtifact("Some catalog content")); - - when(mockModelArtifactHandler.pushArtifacts(any(), any(), any(), any())).thenReturn(true); - when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any())) - .thenReturn(false); - Mockito.doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, - data.getServiceArtifacts().get(0)); - - assertFalse(SHOULD_HAVE_RETURNED_FALSE, - manager.deploy(data, data.getServiceArtifacts(), new ArrayList<>(), catalogFiles)); - - Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(new ArrayList()), - eq(data.getDistributionID()), any(), any()); - Mockito.verify(mockVnfCatalogArtifactHandler).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), - any(), any()); - Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList()), eq(data.getDistributionID()), - any()); - Mockito.verify(mockVnfCatalogArtifactHandler).rollback(eq(new ArrayList()), - eq(data.getDistributionID()), any()); - Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, - data.getServiceArtifacts().get(0)); - } - - private void doFailedCombinedTests(boolean modelsOK, boolean catalogsOK) - throws IOException, BabelArtifactParsingException, InvalidArchiveException { - INotificationData data = getNotificationDataWithOneOfEach(); - ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils(); - byte[] xml = artifactTestUtils.loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml"); - List toscaArtifacts = setupTest(xml, data); - List modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts); - - List catalogFiles = new ArrayList<>(); - catalogFiles.add(new VnfCatalogArtifact("Some catalog content")); - - when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any())) - .thenReturn(catalogsOK); - when(mockModelArtifactHandler.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any())) - .thenReturn(modelsOK); - - Mockito.doNothing().when(mockNotificationPublisher).publishDeploySuccess(mockDistributionClient, data, - data.getServiceArtifacts().get(0)); - Mockito.doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, - data.getServiceArtifacts().get(0)); - - assertFalse(SHOULD_HAVE_RETURNED_FALSE, - manager.deploy(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles)); - - // Catalog artifacts are only pushed if models are successful. - Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), - any()); - if (modelsOK) { - Mockito.verify(mockVnfCatalogArtifactHandler).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), - any(), any()); - } - - if (modelsOK && catalogsOK) { - Mockito.verify(mockNotificationPublisher).publishDeploySuccess(mockDistributionClient, data, - data.getServiceArtifacts().get(0)); - Mockito.verify(mockModelArtifactHandler, Mockito.never()).rollback(any(), any(), any()); - Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(any(), any(), any()); - } else { - Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, - data.getServiceArtifacts().get(0)); - if (modelsOK) { - Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList()), - eq(data.getDistributionID()), any()); - Mockito.verify(mockVnfCatalogArtifactHandler).rollback(eq(new ArrayList()), - eq(data.getDistributionID()), any()); - } else { - Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList()), - eq(data.getDistributionID()), any()); - Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(any(), any(), any()); - } - } - } - -} diff --git a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java b/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java deleted file mode 100644 index 2c02487..0000000 --- a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java +++ /dev/null @@ -1,398 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.notification; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithInvalidType; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithModelQuerySpec; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneOfEach; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneService; -import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile; - -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.mockito.internal.util.reflection.Whitebox; -import org.onap.aai.babel.service.data.BabelArtifact; -import org.onap.aai.modelloader.config.ModelLoaderConfig; -import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; -import org.onap.aai.modelloader.restclient.BabelServiceClient; -import org.onap.aai.modelloader.restclient.BabelServiceClient.BabelServiceException; -import org.onap.aai.modelloader.restclient.BabelServiceClientFactory; -import org.onap.aai.modelloader.util.ArtifactTestUtils; -import org.onap.sdc.api.IDistributionClient; -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.INotificationData; -import org.onap.sdc.api.results.IDistributionClientDownloadResult; -import org.onap.sdc.impl.DistributionClientDownloadResultImpl; -import org.onap.sdc.utils.DistributionActionResultEnum; - -/** - * Tests {@link ArtifactDownloadManager} - */ -public class ArtifactDownloadManagerTest { - - private static final String FALSE_SHOULD_HAVE_BEEN_RETURNED = "A value of 'false' should have been returned"; - private static final String OOPS = "oops"; - private static final String TRUE_SHOULD_HAVE_BEEN_RETURNED = "A value of 'true' should have been returned"; - - private ArtifactDownloadManager downloadManager; - private BabelServiceClient mockBabelClient; - private IDistributionClient mockDistributionClient; - private NotificationPublisher mockNotificationPublisher; - private BabelArtifactConverter mockBabelArtifactConverter; - private BabelServiceClientFactory mockClientFactory; - - @Before - public void setup() throws Exception { - mockBabelClient = mock(BabelServiceClient.class); - mockDistributionClient = mock(IDistributionClient.class); - mockNotificationPublisher = mock(NotificationPublisher.class); - mockBabelArtifactConverter = mock(BabelArtifactConverter.class); - mockClientFactory = mock(BabelServiceClientFactory.class); - when(mockClientFactory.create(Mockito.any())).thenReturn(mockBabelClient); - - Properties configProperties = new Properties(); - configProperties.load(this.getClass().getClassLoader().getResourceAsStream("model-loader.properties")); - downloadManager = new ArtifactDownloadManager(mockDistributionClient, - new ModelLoaderConfig(configProperties, "."), mockClientFactory); - - Whitebox.setInternalState(downloadManager, "notificationPublisher", mockNotificationPublisher); - Whitebox.setInternalState(downloadManager, "babelArtifactConverter", mockBabelArtifactConverter); - } - - @After - public void tearDown() { - downloadManager = null; - mockDistributionClient = null; - mockNotificationPublisher = null; - } - - @Test - public void downloadArtifacts_emptyListSupplied() { - List modelFiles = new ArrayList<>(); - List catalogFiles = new ArrayList<>(); - - assertTrue(TRUE_SHOULD_HAVE_BEEN_RETURNED, downloadManager - .downloadArtifacts(getNotificationDataWithOneService(), new ArrayList<>(), modelFiles, catalogFiles)); - - Mockito.verifyZeroInteractions(mockBabelClient, mockDistributionClient, mockNotificationPublisher, - mockBabelArtifactConverter); - } - - @Test - public void downloadArtifacts_artifactDownloadFails() { - INotificationData data = getNotificationDataWithOneService(); - IArtifactInfo artifact = data.getServiceArtifacts().get(0); - when(mockDistributionClient.download(artifact)) - .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.FAIL, OOPS, null)); - doNothing().when(mockNotificationPublisher).publishDownloadFailure(mockDistributionClient, data, artifact, - OOPS); - - assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED, - downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null)); - - Mockito.verify(mockDistributionClient).download(artifact); - Mockito.verify(mockNotificationPublisher).publishDownloadFailure(mockDistributionClient, data, artifact, OOPS); - - Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter); - } - - private IDistributionClientDownloadResult createDistributionClientDownloadResult( - DistributionActionResultEnum status, String message, byte[] payload) { - IDistributionClientDownloadResult downloadResult = new DistributionClientDownloadResultImpl(status, message); - - ((DistributionClientDownloadResultImpl) downloadResult).setArtifactPayload(payload); - - return downloadResult; - } - - @Test - public void downloadArtifacts_noSuchAlgorithmExceptionFromCreatingBabelClient() throws Exception { - doCreateBabelClientFailureTest(NoSuchAlgorithmException.class); - } - - @SuppressWarnings("unchecked") - private void doCreateBabelClientFailureTest(Class exception) throws Exception { - when(mockClientFactory.create(Mockito.any())).thenThrow(exception); - - INotificationData data = getNotificationDataWithToscaCsarFile(); - IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); - setupValidDownloadCsarMocks(data, artifactInfo, new ArtifactTestUtils()); - doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); - - assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED, - downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null)); - - Mockito.verify(mockDistributionClient).download(artifactInfo); - Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo); - Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); - - Mockito.verifyZeroInteractions(mockBabelArtifactConverter); - } - - @Test - public void downloadArtifacts_keyStoreExceptionFromCreatingBabelClient() throws Exception { - doCreateBabelClientFailureTest(KeyStoreException.class); - } - - @Test - public void downloadArtifacts_certificateExceptionFromCreatingBabelClient() throws Exception { - doCreateBabelClientFailureTest(CertificateException.class); - } - - @Test - public void downloadArtifacts_iOExceptionFromCreatingBabelClient() throws Exception { - doCreateBabelClientFailureTest(IOException.class); - } - - @Test - public void downloadArtifacts_unrecoverableKeyExceptionFromCreatingBabelClient() throws Exception { - doCreateBabelClientFailureTest(UnrecoverableKeyException.class); - } - - @Test - public void downloadArtifacts_keyManagementExceptionFromCreatingBabelClient() throws Exception { - doCreateBabelClientFailureTest(KeyManagementException.class); - } - - /** - * Test disabled as exception handling needs to be reworked - * - * @throws IOException - */ - @SuppressWarnings("unchecked") - @Test - public void downloadArtifacts_invalidToscaCsarFile() throws IOException, BabelServiceException { - INotificationData data = getNotificationDataWithToscaCsarFile(); - IArtifactInfo artifact = data.getServiceArtifacts().get(0); - when(mockDistributionClient.download(artifact)).thenReturn(createDistributionClientDownloadResult( - DistributionActionResultEnum.SUCCESS, null, "This is not a valid Tosca CSAR File".getBytes())); - doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - when(mockBabelClient.postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), - Matchers.anyString())).thenThrow(BabelServiceException.class); - doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); - - assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED, - downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null)); - - Mockito.verify(mockDistributionClient).download(artifact); - Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - Mockito.verify(mockBabelClient).postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), - Matchers.anyString()); - Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); - - Mockito.verifyZeroInteractions(mockBabelArtifactConverter); - - } - - @Test - public void downloadArtifacts_invalidModelQuerySpec() { - INotificationData data = getNotificationDataWithModelQuerySpec(); - IArtifactInfo artifact = data.getServiceArtifacts().get(0); - - List modelArtifacts = new ArrayList<>(); - - when(mockDistributionClient.download(artifact)).thenReturn(createDistributionClientDownloadResult( - DistributionActionResultEnum.SUCCESS, null, "This is not a valid Model Query Spec".getBytes())); - doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - - assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED, - downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, null)); - - Mockito.verify(mockDistributionClient).download(artifact); - Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); - - Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter); - } - - @Test - public void downloadArtifacts_validToscaCsarFile() - throws IOException, BabelServiceException, BabelArtifactParsingException { - INotificationData data = getNotificationDataWithToscaCsarFile(); - IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); - - setupValidDownloadCsarMocks(data, artifactInfo, new ArtifactTestUtils()); - - List modelArtifacts = new ArrayList<>(); - List catalogFiles = new ArrayList<>(); - assertTrue(TRUE_SHOULD_HAVE_BEEN_RETURNED, - downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles)); - - assertTrue("There should not have been any catalog files", catalogFiles.size() == 0); - - Mockito.verify(mockDistributionClient).download(artifactInfo); - Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo); - Mockito.verify(mockBabelClient).postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), - Matchers.anyString()); - Mockito.verify(mockBabelArtifactConverter).convertToModel(Matchers.any()); - Mockito.verify(mockBabelArtifactConverter).convertToCatalog(Matchers.any()); - } - - private void setupValidDownloadCsarMocks(INotificationData data, IArtifactInfo artifactInfo, - ArtifactTestUtils artifactTestUtils) throws IOException, BabelServiceException { - when(mockDistributionClient.download(artifactInfo)) - .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.SUCCESS, null, - artifactTestUtils.loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"))); - when(mockBabelClient.postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), - Matchers.anyString())).thenReturn(createBabelArtifacts()); - } - - private List createBabelArtifacts() { - List artifactList = new ArrayList<>(); - artifactList.add(new BabelArtifact("ModelArtifact", BabelArtifact.ArtifactType.MODEL, "Some model payload")); - artifactList.add(new BabelArtifact("VNFCArtifact", BabelArtifact.ArtifactType.VNFCATALOG, "Some VNFC payload")); - return artifactList; - } - - @Test - public void downloadArtifacts_validModelQuerySpec() - throws IOException, BabelServiceException, BabelArtifactParsingException { - ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils(); - INotificationData data = getNotificationDataWithModelQuerySpec(); - IArtifactInfo artifact = data.getServiceArtifacts().get(0); - setupValidModelQuerySpecMocks(artifactTestUtils, data, artifact); - - List modelFiles = new ArrayList<>(); - List catalogFiles = new ArrayList<>(); - assertTrue(TRUE_SHOULD_HAVE_BEEN_RETURNED, - downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelFiles, catalogFiles)); - - assertTrue("There should have been some model artifacts", !modelFiles.isEmpty()); - assertTrue("There should not have been any catalog artifacts", catalogFiles.isEmpty()); - - Mockito.verify(mockDistributionClient).download(artifact); - Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - - Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter); - } - - private void setupValidModelQuerySpecMocks(ArtifactTestUtils artifactTestUtils, INotificationData data, - IArtifactInfo artifact) throws IOException { - when(mockDistributionClient.download(artifact)) - .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.SUCCESS, null, - artifactTestUtils.loadResource("models/named-query-wan-connector.xml"))); - doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - } - - @Test - public void downloadArtifacts_validCsarAndModelFiles() - throws IOException, BabelServiceException, BabelArtifactParsingException { - ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils(); - INotificationData data = getNotificationDataWithOneOfEach(); - List artifacts = new ArrayList<>(); - - IArtifactInfo serviceArtifact = data.getServiceArtifacts().get(0); - IArtifactInfo modelSpecArtifact = data.getResources().get(1).getArtifacts().get(0); - - artifacts.add(serviceArtifact); - artifacts.add(modelSpecArtifact); - - setupValidDownloadCsarMocks(data, serviceArtifact, artifactTestUtils); - setupValidModelQuerySpecMocks(artifactTestUtils, data, modelSpecArtifact); - - List modelFiles = new ArrayList<>(); - List catalogFiles = new ArrayList<>(); - assertTrue(TRUE_SHOULD_HAVE_BEEN_RETURNED, - downloadManager.downloadArtifacts(data, artifacts, modelFiles, catalogFiles)); - - Mockito.verify(mockDistributionClient).download(serviceArtifact); - Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, serviceArtifact); - Mockito.verify(mockBabelClient).postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), - Matchers.anyString()); - Mockito.verify(mockBabelArtifactConverter).convertToModel(Matchers.any()); - Mockito.verify(mockBabelArtifactConverter).convertToCatalog(Matchers.any()); - - Mockito.verify(mockDistributionClient).download(modelSpecArtifact); - Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, - modelSpecArtifact); - - Mockito.verifyNoMoreInteractions(mockBabelClient, mockBabelArtifactConverter); - } - - @Test - @SuppressWarnings("unchecked") - public void activateCallback_toscaToModelConverterHasProcessToscaArtifactsException() throws Exception { - ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils(); - INotificationData data = getNotificationDataWithToscaCsarFile(); - IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); - - when(mockDistributionClient.download(artifactInfo)) - .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.SUCCESS, null, - artifactTestUtils.loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"))); - when(mockBabelArtifactConverter.convertToModel(Mockito.anyList())) - .thenThrow(BabelArtifactParsingException.class); - doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); - when(mockBabelClient.postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), - Matchers.anyString())).thenReturn(createBabelArtifacts()); - - List modelArtifacts = new ArrayList<>(); - List catalogFiles = new ArrayList<>(); - assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED, - downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles)); - - assertTrue("There should not have been any catalog files", catalogFiles.size() == 0); - - Mockito.verify(mockDistributionClient).download(artifactInfo); - Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); - Mockito.verify(mockBabelClient).postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), - Matchers.anyString()); - Mockito.verify(mockBabelArtifactConverter).convertToModel(Matchers.any()); - } - - @Test - public void downloadArtifacts_invalidType() - throws IOException, BabelServiceException, BabelArtifactParsingException { - INotificationData data = getNotificationDataWithInvalidType(); - IArtifactInfo artifact = data.getServiceArtifacts().get(0); - - List catalogArtifacts = new ArrayList<>(); - - when(mockDistributionClient.download(artifact)).thenReturn(createDistributionClientDownloadResult( - DistributionActionResultEnum.SUCCESS, null, "This content does not matter.".getBytes())); - doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - - assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED, - downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, catalogArtifacts)); - - Mockito.verify(mockDistributionClient).download(artifact); - Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); - - Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter); - } -} diff --git a/src/test/java/org/onap/aai/modelloader/notification/BabelArtifactConverterTest.java b/src/test/java/org/onap/aai/modelloader/notification/BabelArtifactConverterTest.java deleted file mode 100644 index e9e6059..0000000 --- a/src/test/java/org/onap/aai/modelloader/notification/BabelArtifactConverterTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.notification; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; -import org.onap.aai.babel.service.data.BabelArtifact; -import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; -import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder; -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.INotificationData; - -/** - * Tests {@link BabelArtifactConverter} - */ -public class BabelArtifactConverterTest { - - @Test(expected = NullPointerException.class) - public void convert_nullToscaFiles() throws BabelArtifactParsingException { - new BabelArtifactConverter().convertToModel(null); - fail("An instance of ArtifactGenerationException should have been thrown"); - } - - @Test - public void convert_emptyToscaFiles() throws BabelArtifactParsingException { - assertTrue("Nothing should have been returned", - new BabelArtifactConverter().convertToModel(new ArrayList<>()).isEmpty()); - } - - @Test(expected = BabelArtifactParsingException.class) - public void convert_problemWithConvertedXML() throws IOException, BabelArtifactParsingException { - byte[] problemXML = - "This is some xml that should cause the model artifact parser to throw an erorr" - .getBytes(); - - INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile(); - - List toscaArtifacts = setupTest(problemXML, data); - - new BabelArtifactConverter().convertToModel(toscaArtifacts); - fail("An instance of ModelArtifactParsingException should have been thrown"); - } - - private List setupTest(byte[] xml, INotificationData data) throws IOException { - List toscaArtifacts = new ArrayList<>(); - IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); - - BabelArtifact xmlArtifact = - new BabelArtifact(artifactInfo.getArtifactName(), BabelArtifact.ArtifactType.MODEL, new String(xml)); - toscaArtifacts.add(xmlArtifact); - - return toscaArtifacts; - } -} diff --git a/src/test/java/org/onap/aai/modelloader/notification/EventCallbackTest.java b/src/test/java/org/onap/aai/modelloader/notification/EventCallbackTest.java deleted file mode 100644 index 57a4c09..0000000 --- a/src/test/java/org/onap/aai/modelloader/notification/EventCallbackTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.notification; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.List; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.internal.util.reflection.Whitebox; -import org.onap.aai.modelloader.config.ModelLoaderConfig; -import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; -import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder; -import org.onap.sdc.api.IDistributionClient; -import org.onap.sdc.api.notification.INotificationData; - -/** - * Tests {@link EventCallback} - */ -public class EventCallbackTest { - - private static final String CONFIG_FILE = "model-loader.properties"; - - private ModelLoaderConfig config; - private Properties configProperties; - private EventCallback eventCallback; - - private ArtifactDeploymentManager mockArtifactDeploymentManager; - private ArtifactDownloadManager mockArtifactDownloadManager; - private IDistributionClient mockDistributionClient; - - @Before - public void setup() throws IOException { - configProperties = new Properties(); - configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE)); - config = new ModelLoaderConfig(configProperties, null); - - mockArtifactDeploymentManager = mock(ArtifactDeploymentManager.class); - mockArtifactDownloadManager = mock(ArtifactDownloadManager.class); - mockDistributionClient = mock(IDistributionClient.class); - - eventCallback = new EventCallback(mockDistributionClient, config); - - Whitebox.setInternalState(eventCallback, "artifactDeploymentManager", mockArtifactDeploymentManager); - Whitebox.setInternalState(eventCallback, "artifactDownloadManager", mockArtifactDownloadManager); - } - - @After - public void tearDown() { - config = null; - configProperties = null; - eventCallback = null; - mockArtifactDeploymentManager = null; - mockArtifactDownloadManager = null; - mockDistributionClient = null; - } - - @Test - @SuppressWarnings("unchecked") - public void activateCallback_downloadFails() { - INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile(); - - when(mockArtifactDownloadManager.downloadArtifacts(any(INotificationData.class), any(List.class), - any(List.class), any(List.class))).thenReturn(false); - - eventCallback.activateCallback(data); - - verify(mockArtifactDownloadManager).downloadArtifacts(any(INotificationData.class), any(List.class), - any(List.class), any(List.class)); - Mockito.verifyZeroInteractions(mockArtifactDeploymentManager); - } - - @SuppressWarnings("unchecked") - @Test - public void activateCallback() throws BabelArtifactParsingException { - INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile(); - - when(mockArtifactDownloadManager.downloadArtifacts(any(INotificationData.class), any(List.class), - any(List.class), any(List.class))).thenReturn(true); - - when(mockArtifactDeploymentManager.deploy(any(INotificationData.class), any(List.class), any(List.class), - any(List.class))).thenReturn(true); - - eventCallback.activateCallback(data); - - verify(mockArtifactDownloadManager).downloadArtifacts(any(INotificationData.class), any(List.class), - any(List.class), any(List.class)); - verify(mockArtifactDeploymentManager).deploy(any(INotificationData.class), any(List.class), any(List.class), - any(List.class)); - } -} diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java new file mode 100644 index 0000000..d8cb19a --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java @@ -0,0 +1,235 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.notification; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithCatalogFile; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneOfEach; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.Whitebox; +import org.onap.aai.babel.service.data.BabelArtifact; +import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.entity.Artifact; +import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifact; +import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifactHandler; +import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; +import org.onap.aai.modelloader.entity.model.ModelArtifactHandler; +import org.onap.aai.modelloader.extraction.InvalidArchiveException; +import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder; +import org.onap.aai.modelloader.service.ArtifactDeploymentManager; +import org.onap.aai.modelloader.util.ArtifactTestUtils; +import org.onap.sdc.api.notification.INotificationData; + +/** + * Tests {@link ArtifactDeploymentManager}. + */ +public class TestArtifactDeploymentManager { + + private static final String CONFIG_FILE = "model-loader.properties"; + private static final String SHOULD_HAVE_RETURNED_FALSE = "This should have returned false"; + + private Properties configProperties; + private ArtifactDeploymentManager manager; + + private ModelArtifactHandler mockModelArtifactHandler; + private VnfCatalogArtifactHandler mockVnfCatalogArtifactHandler; + + @Before + public void setup() throws IOException { + configProperties = new Properties(); + configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE)); + + mockModelArtifactHandler = mock(ModelArtifactHandler.class); + mockVnfCatalogArtifactHandler = mock(VnfCatalogArtifactHandler.class); + + manager = new ArtifactDeploymentManager(new ModelLoaderConfig(configProperties, null)); + + Whitebox.setInternalState(manager, "modelArtifactHandler", mockModelArtifactHandler); + Whitebox.setInternalState(manager, "vnfCatalogArtifactHandler", mockVnfCatalogArtifactHandler); + } + + @After + public void tearDown() { + configProperties = null; + mockModelArtifactHandler = null; + mockVnfCatalogArtifactHandler = null; + manager = null; + } + + @Test + public void deploy_csarDeploymentsFailed() throws IOException, BabelArtifactParsingException { + INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile(); + byte[] xml = new ArtifactTestUtils().loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml"); + List toscaArtifacts = setupTest(xml, data); + List modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts); + + when(mockModelArtifactHandler.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any())) + .thenReturn(false); + + assertThat(SHOULD_HAVE_RETURNED_FALSE, manager.deploy(data, modelArtifacts, new ArrayList<>()), is(false)); + + Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), + any()); + Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).pushArtifacts(eq(modelArtifacts), + eq(data.getDistributionID()), any(), any()); + Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList()), eq(data.getDistributionID()), + any()); + Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(eq(new ArrayList()), + eq(data.getDistributionID()), any()); + } + + private List setupTest(byte[] xml, INotificationData data) throws IOException { + List toscaArtifacts = new ArrayList<>(); + org.onap.sdc.api.notification.IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); + + BabelArtifact xmlArtifact = + new BabelArtifact(artifactInfo.getArtifactName(), BabelArtifact.ArtifactType.MODEL, new String(xml)); + toscaArtifacts.add(xmlArtifact); + + return toscaArtifacts; + } + + @Test + public void deploy_catalogDeploymentsFailed() + throws IOException, BabelArtifactParsingException, InvalidArchiveException { + INotificationData data = getNotificationDataWithCatalogFile(); + + List catalogFiles = new ArrayList<>(); + catalogFiles.add(new VnfCatalogArtifact("Some catalog content")); + + when(mockModelArtifactHandler.pushArtifacts(any(), any(), any(), any())).thenReturn(true); + when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any())) + .thenReturn(false); + + assertThat(SHOULD_HAVE_RETURNED_FALSE, manager.deploy(data, new ArrayList<>(), catalogFiles), is(false)); + + Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(new ArrayList()), + eq(data.getDistributionID()), any(), any()); + Mockito.verify(mockVnfCatalogArtifactHandler).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), + any(), any()); + Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList()), eq(data.getDistributionID()), + any()); + Mockito.verify(mockVnfCatalogArtifactHandler).rollback(eq(new ArrayList()), + eq(data.getDistributionID()), any()); + } + + @Test + public void testNoArtifactsDeployed() throws IOException, BabelArtifactParsingException, InvalidArchiveException { + doFailedCombinedTests(false, false); + } + + @Test + public void testModelsNotDeployed() throws IOException, BabelArtifactParsingException, InvalidArchiveException { + doFailedCombinedTests(false, true); + } + + @Test + public void testCatalogsNotDeployed() throws IOException, BabelArtifactParsingException, InvalidArchiveException { + doFailedCombinedTests(true, false); + } + + private void doFailedCombinedTests(boolean modelsDeployed, boolean catalogsDeployed) + throws IOException, BabelArtifactParsingException, InvalidArchiveException { + INotificationData data = getNotificationDataWithOneOfEach(); + byte[] xml = new ArtifactTestUtils().loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml"); + List toscaArtifacts = setupTest(xml, data); + List modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts); + + List catalogFiles = new ArrayList<>(); + catalogFiles.add(new VnfCatalogArtifact("Some catalog content")); + + when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any())) + .thenReturn(catalogsDeployed); + when(mockModelArtifactHandler.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any())) + .thenReturn(modelsDeployed); + + assertThat(SHOULD_HAVE_RETURNED_FALSE, manager.deploy(data, modelArtifacts, catalogFiles), is(false)); + + // Catalog artifacts are only pushed if models are successful. + Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), + any()); + if (modelsDeployed) { + Mockito.verify(mockVnfCatalogArtifactHandler).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), + any(), any()); + } + + if (modelsDeployed && catalogsDeployed) { + Mockito.verify(mockModelArtifactHandler, Mockito.never()).rollback(any(), any(), any()); + Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(any(), any(), any()); + } else { + if (modelsDeployed) { + Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList()), + eq(data.getDistributionID()), any()); + Mockito.verify(mockVnfCatalogArtifactHandler).rollback(eq(new ArrayList()), + eq(data.getDistributionID()), any()); + } else { + Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList()), + eq(data.getDistributionID()), any()); + Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(any(), any(), any()); + } + } + } + + /** + * Deploy both models and VNF images. + * + * @throws IOException + * @throws BabelArtifactParsingException + * @throws InvalidArchiveException + */ + @Test + public void testDeploySuccess() throws IOException, BabelArtifactParsingException, InvalidArchiveException { + INotificationData data = getNotificationDataWithOneOfEach(); + byte[] xml = new ArtifactTestUtils().loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml"); + List toscaArtifacts = setupTest(xml, data); + List modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts); + + List catalogFiles = new ArrayList<>(); + catalogFiles.add(new VnfCatalogArtifact("Some catalog content")); + + when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any())) + .thenReturn(true); + when(mockModelArtifactHandler.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any())) + .thenReturn(true); + + assertThat(manager.deploy(data, modelArtifacts, catalogFiles), is(true)); + + Mockito.verify(mockVnfCatalogArtifactHandler).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), + any(), any()); + Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), + any()); + Mockito.verify(mockModelArtifactHandler, Mockito.never()).rollback(any(), any(), any()); + Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(any(), any(), any()); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java new file mode 100644 index 0000000..030a0ff --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java @@ -0,0 +1,351 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.notification; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.collection.IsEmptyCollection.empty; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithInvalidType; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithModelQuerySpec; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneOfEach; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneService; +import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import org.hamcrest.collection.IsEmptyCollection; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.Whitebox; +import org.onap.aai.babel.service.data.BabelArtifact; +import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.entity.Artifact; +import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; +import org.onap.aai.modelloader.restclient.BabelServiceClient; +import org.onap.aai.modelloader.restclient.BabelServiceClientException; +import org.onap.aai.modelloader.service.BabelServiceClientFactory; +import org.onap.aai.modelloader.service.HttpsBabelServiceClientFactory; +import org.onap.aai.modelloader.util.ArtifactTestUtils; +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.impl.DistributionClientDownloadResultImpl; +import org.onap.sdc.utils.DistributionActionResultEnum; + +/** + * Tests {@link ArtifactDownloadManager}. + */ +public class TestArtifactDownloadManager { + + private ArtifactDownloadManager downloadManager; + private BabelServiceClient mockBabelClient; + private IDistributionClient mockDistributionClient; + private NotificationPublisher mockNotificationPublisher; + private BabelArtifactConverter mockBabelArtifactConverter; + private BabelServiceClientFactory mockClientFactory; + + @Before + public void setup() throws Exception { + mockBabelClient = mock(BabelServiceClient.class); + mockDistributionClient = mock(IDistributionClient.class); + mockNotificationPublisher = mock(NotificationPublisher.class); + mockBabelArtifactConverter = mock(BabelArtifactConverter.class); + mockClientFactory = mock(HttpsBabelServiceClientFactory.class); + when(mockClientFactory.create(Mockito.any())).thenReturn(mockBabelClient); + + Properties configProperties = new Properties(); + configProperties.load(this.getClass().getClassLoader().getResourceAsStream("model-loader.properties")); + downloadManager = new ArtifactDownloadManager(mockDistributionClient, + new ModelLoaderConfig(configProperties, "."), mockClientFactory); + + Whitebox.setInternalState(downloadManager, "notificationPublisher", mockNotificationPublisher); + Whitebox.setInternalState(downloadManager, "babelArtifactConverter", mockBabelArtifactConverter); + } + + @After + public void tearDown() { + downloadManager = null; + mockDistributionClient = null; + mockNotificationPublisher = null; + } + + /** + * Test downloading zero artifacts from SDC. + */ + @Test + public void testDownloadWithZeroArtifacts() { + List modelFiles = new ArrayList<>(); + List catalogFiles = new ArrayList<>(); + assertThat(downloadManager.downloadArtifacts(getNotificationDataWithOneService(), new ArrayList<>(), modelFiles, + catalogFiles), is(true)); + assertThat(modelFiles, is(empty())); + assertThat(catalogFiles, is(empty())); + Mockito.verifyZeroInteractions(mockBabelClient, mockDistributionClient, mockNotificationPublisher, + mockBabelArtifactConverter); + } + + @Test + public void testArtifactDownloadFails() { + INotificationData data = getNotificationDataWithOneService(); + IArtifactInfo artifact = data.getServiceArtifacts().get(0); + String errorMessage = "error msg"; + when(mockDistributionClient.download(artifact)).thenReturn( + createDistributionClientDownloadResult(DistributionActionResultEnum.FAIL, errorMessage, null)); + doNothing().when(mockNotificationPublisher).publishDownloadFailure(mockDistributionClient, data, artifact, + errorMessage); + + assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null), is(false)); + + Mockito.verify(mockDistributionClient).download(artifact); + Mockito.verify(mockNotificationPublisher).publishDownloadFailure(mockDistributionClient, data, artifact, + errorMessage); + + Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter); + } + + @Test + public void testErrorCreatingBabelClient() throws Exception { + when(mockClientFactory.create(Mockito.any())).thenThrow(new BabelServiceClientException(new Exception())); + + INotificationData data = getNotificationDataWithToscaCsarFile(); + IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); + setupValidDownloadCsarMocks(data, artifactInfo, new ArtifactTestUtils()); + doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); + + assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null), is(false)); + + Mockito.verify(mockDistributionClient).download(artifactInfo); + Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo); + Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); + + Mockito.verifyZeroInteractions(mockBabelArtifactConverter); + } + + @Test + public void downloadArtifacts_invalidToscaCsarFile() throws IOException, BabelServiceClientException { + INotificationData data = getNotificationDataWithToscaCsarFile(); + IArtifactInfo artifact = data.getServiceArtifacts().get(0); + when(mockDistributionClient.download(artifact)).thenReturn(createDistributionClientDownloadResult( + DistributionActionResultEnum.SUCCESS, null, "This is not a valid Tosca CSAR File".getBytes())); + doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); + when(mockBabelClient.postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), + Matchers.anyString())).thenThrow(new BabelServiceClientException("")); + doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); + + assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null), is(false)); + + Mockito.verify(mockDistributionClient).download(artifact); + Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); + Mockito.verify(mockBabelClient).postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), + Matchers.anyString()); + Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); + + Mockito.verifyZeroInteractions(mockBabelArtifactConverter); + + } + + @Test + public void downloadArtifacts_invalidModelQuerySpec() { + INotificationData data = getNotificationDataWithModelQuerySpec(); + IArtifactInfo artifact = data.getServiceArtifacts().get(0); + + List modelArtifacts = new ArrayList<>(); + + when(mockDistributionClient.download(artifact)).thenReturn(createDistributionClientDownloadResult( + DistributionActionResultEnum.SUCCESS, null, "This is not a valid Model Query Spec".getBytes())); + doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); + + assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, null), + is(false)); + + Mockito.verify(mockDistributionClient).download(artifact); + Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); + Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); + + Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter); + } + + @Test + public void downloadArtifacts_validToscaCsarFile() + throws IOException, BabelServiceClientException, BabelArtifactParsingException { + INotificationData data = getNotificationDataWithToscaCsarFile(); + IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); + + setupValidDownloadCsarMocks(data, artifactInfo, new ArtifactTestUtils()); + + List modelArtifacts = new ArrayList<>(); + List catalogFiles = new ArrayList<>(); + assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles), + is(true)); + assertThat(catalogFiles.size(), is(0)); + + Mockito.verify(mockDistributionClient).download(artifactInfo); + Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo); + Mockito.verify(mockBabelClient).postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), + Matchers.anyString()); + Mockito.verify(mockBabelArtifactConverter).convertToModel(Matchers.any()); + Mockito.verify(mockBabelArtifactConverter).convertToCatalog(Matchers.any()); + } + + private void setupValidDownloadCsarMocks(INotificationData data, IArtifactInfo artifactInfo, + ArtifactTestUtils artifactTestUtils) throws IOException, BabelServiceClientException { + when(mockDistributionClient.download(artifactInfo)) + .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.SUCCESS, null, + artifactTestUtils.loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"))); + when(mockBabelClient.postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), + Matchers.anyString())).thenReturn(createBabelArtifacts()); + } + + private List createBabelArtifacts() { + List artifactList = new ArrayList<>(); + artifactList.add(new BabelArtifact("ModelArtifact", BabelArtifact.ArtifactType.MODEL, "Some model payload")); + artifactList.add(new BabelArtifact("VNFCArtifact", BabelArtifact.ArtifactType.VNFCATALOG, "Some VNFC payload")); + return artifactList; + } + + @Test + public void downloadArtifactsWithValidModelQuerySpec() + throws IOException, BabelServiceClientException, BabelArtifactParsingException { + INotificationData data = getNotificationDataWithModelQuerySpec(); + IArtifactInfo artifact = data.getServiceArtifacts().get(0); + setupValidModelQuerySpecMocks(new ArtifactTestUtils(), data, artifact); + + List modelFiles = new ArrayList<>(); + List catalogFiles = new ArrayList<>(); + assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelFiles, catalogFiles), + is(true)); + + assertThat(modelFiles, is(not(IsEmptyCollection.empty()))); + assertThat(catalogFiles, is(empty())); + + Mockito.verify(mockDistributionClient).download(artifact); + Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); + + Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter); + } + + private void setupValidModelQuerySpecMocks(ArtifactTestUtils artifactTestUtils, INotificationData data, + IArtifactInfo artifact) throws IOException { + when(mockDistributionClient.download(artifact)) + .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.SUCCESS, null, + artifactTestUtils.loadResource("models/named-query-wan-connector.xml"))); + doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); + } + + @Test + public void downloadArtifacts_validCsarAndModelFiles() + throws IOException, BabelServiceClientException, BabelArtifactParsingException { + ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils(); + INotificationData data = getNotificationDataWithOneOfEach(); + List artifacts = new ArrayList<>(); + + IArtifactInfo serviceArtifact = data.getServiceArtifacts().get(0); + IArtifactInfo modelSpecArtifact = data.getResources().get(1).getArtifacts().get(0); + + artifacts.add(serviceArtifact); + artifacts.add(modelSpecArtifact); + + setupValidDownloadCsarMocks(data, serviceArtifact, artifactTestUtils); + setupValidModelQuerySpecMocks(artifactTestUtils, data, modelSpecArtifact); + + List modelFiles = new ArrayList<>(); + List catalogFiles = new ArrayList<>(); + assertThat(downloadManager.downloadArtifacts(data, artifacts, modelFiles, catalogFiles), is(true)); + + Mockito.verify(mockDistributionClient).download(serviceArtifact); + Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, serviceArtifact); + Mockito.verify(mockBabelClient).postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), + Matchers.anyString()); + Mockito.verify(mockBabelArtifactConverter).convertToModel(Matchers.any()); + Mockito.verify(mockBabelArtifactConverter).convertToCatalog(Matchers.any()); + + Mockito.verify(mockDistributionClient).download(modelSpecArtifact); + Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, + modelSpecArtifact); + + Mockito.verifyNoMoreInteractions(mockBabelClient, mockBabelArtifactConverter); + } + + @Test + @SuppressWarnings("unchecked") + public void activateCallback_toscaToModelConverterHasProcessToscaArtifactsException() throws Exception { + ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils(); + INotificationData data = getNotificationDataWithToscaCsarFile(); + IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); + + when(mockDistributionClient.download(artifactInfo)) + .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.SUCCESS, null, + artifactTestUtils.loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"))); + when(mockBabelArtifactConverter.convertToModel(Mockito.anyList())) + .thenThrow(BabelArtifactParsingException.class); + doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); + when(mockBabelClient.postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), + Matchers.anyString())).thenReturn(createBabelArtifacts()); + + List modelArtifacts = new ArrayList<>(); + List catalogFiles = new ArrayList<>(); + assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles), + is(false)); + assertThat(modelArtifacts, is(empty())); + assertThat(catalogFiles, is(empty())); + + Mockito.verify(mockDistributionClient).download(artifactInfo); + Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); + Mockito.verify(mockBabelClient).postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(), + Matchers.anyString()); + Mockito.verify(mockBabelArtifactConverter).convertToModel(Matchers.any()); + } + + @Test + public void downloadArtifactsWithInvalidType() + throws IOException, BabelServiceClientException, BabelArtifactParsingException { + INotificationData data = getNotificationDataWithInvalidType(); + IArtifactInfo artifact = data.getServiceArtifacts().get(0); + + when(mockDistributionClient.download(artifact)).thenReturn(createDistributionClientDownloadResult( + DistributionActionResultEnum.SUCCESS, null, "This content does not matter.".getBytes())); + doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); + + assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, new ArrayList<>()), + is(false)); + Mockito.verify(mockDistributionClient).download(artifact); + Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); + Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); + Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter); + } + + private IDistributionClientDownloadResult createDistributionClientDownloadResult( + DistributionActionResultEnum status, String message, byte[] payload) { + DistributionClientDownloadResultImpl downloadResult = new DistributionClientDownloadResultImpl(status, message); + downloadResult.setArtifactPayload(payload); + return downloadResult; + } +} diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestBabelArtifactConverter.java b/src/test/java/org/onap/aai/modelloader/notification/TestBabelArtifactConverter.java new file mode 100644 index 0000000..718c415 --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/notification/TestBabelArtifactConverter.java @@ -0,0 +1,95 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.notification; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; +import org.onap.aai.babel.service.data.BabelArtifact; +import org.onap.aai.modelloader.entity.Artifact; +import org.onap.aai.modelloader.entity.ArtifactType; +import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; +import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder; +import org.onap.aai.modelloader.util.ArtifactTestUtils; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; + +/** + * Tests {@link BabelArtifactConverter}. + */ +public class TestBabelArtifactConverter { + + @Test(expected = NullPointerException.class) + public void convert_nullToscaFiles() throws BabelArtifactParsingException { + new BabelArtifactConverter().convertToModel(null); + fail("An instance of ArtifactGenerationException should have been thrown"); + } + + @Test + public void testEmptyToscaFiles() throws BabelArtifactParsingException { + assertTrue("Nothing should have been returned", + new BabelArtifactConverter().convertToModel(new ArrayList<>()).isEmpty()); + } + + @Test(expected = BabelArtifactParsingException.class) + public void testInvalidXml() throws IOException, BabelArtifactParsingException { + byte[] problemXml = + "This is some xml that should cause the model artifact parser to throw an erorr" + .getBytes(); + + INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile(); + + List toscaArtifacts = setupTest(problemXml, data); + + new BabelArtifactConverter().convertToModel(toscaArtifacts); + fail("An instance of ModelArtifactParsingException should have been thrown"); + } + + private List setupTest(byte[] xml, INotificationData data) throws IOException { + List toscaArtifacts = new ArrayList<>(); + IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); + + BabelArtifact xmlArtifact = + new BabelArtifact(artifactInfo.getArtifactName(), BabelArtifact.ArtifactType.MODEL, new String(xml)); + toscaArtifacts.add(xmlArtifact); + + return toscaArtifacts; + } + + @Test + public void convert_singleResourceFile() throws BabelArtifactParsingException, IOException { + INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile(); + + byte[] xml = new ArtifactTestUtils().loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml"); + List toscaArtifacts = setupTest(xml, data); + + List modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts); + + assertTrue("There should have been 1 artifact", modelArtifacts.size() == 1); + assertEquals(new String(xml), modelArtifacts.get(0).getPayload()); + assertEquals(ArtifactType.MODEL, modelArtifacts.get(0).getType()); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestEventCallback.java b/src/test/java/org/onap/aai/modelloader/notification/TestEventCallback.java new file mode 100644 index 0000000..1215a7b --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/notification/TestEventCallback.java @@ -0,0 +1,119 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.notification; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.Whitebox; +import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; +import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder; +import org.onap.aai.modelloader.service.ArtifactDeploymentManager; +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.notification.INotificationData; + +/** + * Tests {@link EventCallback}. + */ +public class TestEventCallback { + + private static final String CONFIG_FILE = "model-loader.properties"; + + private ModelLoaderConfig config; + private Properties configProperties; + private EventCallback eventCallback; + + private ArtifactDeploymentManager mockArtifactDeploymentManager; + private ArtifactDownloadManager mockArtifactDownloadManager; + private IDistributionClient mockDistributionClient; + private NotificationPublisher mockNotificationPublisher; + + @Before + public void setup() throws IOException { + configProperties = new Properties(); + configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE)); + config = new ModelLoaderConfig(configProperties, null); + + mockArtifactDeploymentManager = mock(ArtifactDeploymentManager.class); + mockArtifactDownloadManager = mock(ArtifactDownloadManager.class); + mockDistributionClient = mock(IDistributionClient.class); + mockNotificationPublisher = mock(NotificationPublisher.class); + + eventCallback = new EventCallback(mockDistributionClient, config); + + Whitebox.setInternalState(eventCallback, "artifactDeploymentManager", mockArtifactDeploymentManager); + Whitebox.setInternalState(eventCallback, "artifactDownloadManager", mockArtifactDownloadManager); + Whitebox.setInternalState(eventCallback, "notificationPublisher", mockNotificationPublisher); + } + + @After + public void tearDown() { + config = null; + configProperties = null; + eventCallback = null; + mockArtifactDeploymentManager = null; + mockArtifactDownloadManager = null; + mockDistributionClient = null; + } + + @Test + @SuppressWarnings("unchecked") + public void activateCallback_downloadFails() { + INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile(); + + when(mockArtifactDownloadManager.downloadArtifacts(any(INotificationData.class), any(List.class), + any(List.class), any(List.class))).thenReturn(false); + + eventCallback.activateCallback(data); + + verify(mockArtifactDownloadManager).downloadArtifacts(any(INotificationData.class), any(List.class), + any(List.class), any(List.class)); + Mockito.verifyZeroInteractions(mockArtifactDeploymentManager); + } + + @SuppressWarnings("unchecked") + @Test + public void activateCallback() throws BabelArtifactParsingException { + INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile(); + + when(mockArtifactDownloadManager.downloadArtifacts(any(INotificationData.class), any(List.class), + any(List.class), any(List.class))).thenReturn(true); + + when(mockArtifactDeploymentManager.deploy(any(INotificationData.class), any(List.class), any(List.class))) + .thenReturn(true); + + eventCallback.activateCallback(data); + + verify(mockArtifactDownloadManager).downloadArtifacts(any(INotificationData.class), any(List.class), + any(List.class), any(List.class)); + verify(mockArtifactDeploymentManager).deploy(any(INotificationData.class), any(List.class), any(List.class)); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java b/src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java new file mode 100644 index 0000000..c045910 --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java @@ -0,0 +1,83 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.notification; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +/** + * Tests for NotificationDataImpl class + * + */ +public class TestNotificationDataImpl { + + @Test + public void testGettersAndSetters() { + NotificationDataImpl data = new NotificationDataImpl(); + String distributionId = "testid"; + + data.setDistributionID(distributionId); + assertThat(data.getDistributionID(), is(equalTo(distributionId))); + + // Getters return empty data + assertThat(data.getArtifactMetadataByUUID(null), is(equalTo(null))); + assertThat(data.getServiceDescription(), is(equalTo(null))); + assertThat(data.getServiceInvariantUUID(), is(equalTo(null))); + assertThat(data.getServiceName(), is(equalTo(null))); + assertThat(data.getServiceUUID(), is(equalTo(null))); + assertThat(data.getServiceVersion(), is(equalTo(null))); + assertThat(data.getResources().size(), is(0)); + assertThat(data.getServiceArtifacts().size(), is(0)); + + // Unsupported method! + String context = "testcontext"; + data.setWorkloadContext(context); + assertThat(data.getWorkloadContext(), is(equalTo(null))); + } + + + @Test + public void testEquality() { + NotificationDataImpl data = new NotificationDataImpl(); + assertThat(data, is(not(equalTo(null)))); + assertThat(data, is(not(equalTo("")))); // NOSONAR + assertThat(data, is(equalTo(data))); + + NotificationDataImpl other = new NotificationDataImpl(); + assertThat(data, is(equalTo(other))); + assertThat(data.hashCode(), is(equalTo(other.hashCode()))); + + other.setDistributionID(""); + assertThat(data, is(not(equalTo(other)))); + + data.setDistributionID("1234"); + assertThat(data, is(not(equalTo(other)))); + + other.setDistributionID("1234"); + assertThat(data, is(equalTo(other))); + assertThat(data.hashCode(), is(equalTo(other.hashCode()))); + } + +} diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java b/src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java index bc91b2f..4939fd6 100644 --- a/src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java +++ b/src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. diff --git a/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java b/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java new file mode 100644 index 0000000..604aca7 --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.restclient; + +import java.util.Collections; +import java.util.List; +import org.onap.aai.babel.service.data.BabelArtifact; +import org.onap.aai.modelloader.config.ModelLoaderConfig; + +/** + * Mocked Client for interfacing with Babel. + * + */ +public class MockBabelServiceClient implements BabelServiceClient { + + public MockBabelServiceClient(ModelLoaderConfig config) throws BabelServiceClientException {} + + @Override + public List postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion, + String transactionId) throws BabelServiceClientException { + return Collections.emptyList(); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java new file mode 100644 index 0000000..8b1b22c --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java @@ -0,0 +1,144 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.restclient; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Properties; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.xml.parsers.DocumentBuilderFactory; +import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.entity.ArtifactType; +import org.onap.aai.modelloader.entity.model.ModelArtifact; +import org.onap.aai.modelloader.entity.model.ModelArtifactParser; +import org.onap.aai.restclient.client.OperationResult; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class TestAaiRestClient { + + private static final String MODEL_FILE = "src/test/resources/models/l3-network-widget.xml"; + + // This test requires a running A&AI system. To test locally, annotate with org.junit.Test + public void testRestClient() throws Exception { + Properties props = new Properties(); + props.setProperty("ml.distribution.ARTIFACT_TYPES", "MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG"); + props.setProperty("ml.aai.BASE_URL", "https://localhost:8443"); + props.setProperty("ml.aai.MODEL_URL", "/aai/v9/service-design-and-creation/models/model/"); + props.setProperty("ml.aai.KEYSTORE_FILE", "aai-client-cert.p12"); + props.setProperty("ml.aai.KEYSTORE_PASSWORD", "OBF:1i9a1u2a1unz1lr61wn51wn11lss1unz1u301i6o"); + + ModelLoaderConfig config = new ModelLoaderConfig(props, "."); + + File xmlFile = new File(MODEL_FILE); + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + Document doc = dbFactory.newDocumentBuilder().parse(xmlFile); + + NodeList nodesList = doc.getDocumentElement().getChildNodes(); + + // Get the model IDs + + // @formatter:off + String modelInvariantId = + getNodesStream(nodesList) + .filter(childNode -> childNode.getNodeName().equals(ModelArtifactParser.MODEL_INVARIANT_ID)) + .findFirst() + .map(Node::getTextContent) + .orElse(null); + + String modelId = getNodesStream(nodesList) + .flatMap(n -> getNodesStream(n.getChildNodes())) + .filter(childNode -> childNode.getNodeName().equals(ModelArtifactParser.MODEL_VER)) + .findFirst() + .map(n -> n.getChildNodes().item(1).getTextContent()) + .orElse(null); + // @formatter:on + + try { + // Build the model artifact + ModelArtifact model = new ModelArtifact(); + model.setModelInvariantId(modelInvariantId); + model.setModelVerId(modelId); + model.setPayload(readFile(MODEL_FILE)); + model.setModelNamespace("http://org.openecomp.aai.inventory/v9"); + + AaiRestClient aaiClient = new AaiRestClient(config); + + // GET model + OperationResult opResult = + aaiClient.getResource(getUrl(model, config), "example-trans-id-0", MediaType.APPLICATION_XML_TYPE); + assertTrue(opResult.getResultCode() == Response.Status.NOT_FOUND.getStatusCode()); + + // PUT the model + opResult = aaiClient.putResource(getUrl(model, config), model.getPayload(), "example-trans-id-1", + MediaType.APPLICATION_XML_TYPE); + assertTrue(opResult.getResultCode() == Response.Status.CREATED.getStatusCode()); + + // DELETE the model + opResult = aaiClient.getAndDeleteResource(getUrl(model, config), "example-trans-id-3"); + assertTrue(opResult.getResultCode() == Response.Status.NO_CONTENT.getStatusCode()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private Stream getNodesStream(NodeList nodeList) { + return IntStream.range(0, nodeList.getLength()).mapToObj(nodeList::item); + } + + static String readFile(String path) throws IOException { + byte[] encoded = Files.readAllBytes(Paths.get(path)); + return new String(encoded); + } + + private String getUrl(ModelArtifact model, ModelLoaderConfig config) { + String subUrl; + if (model.getType().equals(ArtifactType.MODEL)) { + subUrl = config.getAaiModelUrl(model.getModelNamespaceVersion()).trim(); + } else { + subUrl = config.getAaiNamedQueryUrl(model.getModelNamespaceVersion()).trim(); + } + + String baseUrl = config.getAaiBaseUrl().trim(); + if (!baseUrl.endsWith("/") && !subUrl.startsWith("/")) { + baseUrl = baseUrl + "/"; + } + + if (baseUrl.endsWith("/") && subUrl.startsWith("/")) { + baseUrl = baseUrl.substring(0, baseUrl.length() - 1); + } + + if (!subUrl.endsWith("/")) { + subUrl = subUrl + "/"; + } + + return baseUrl + subUrl + model.getModelInvariantId(); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java index 96620ee..ac2d7e4 100644 --- a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java +++ b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -39,7 +39,7 @@ import org.junit.Test; import org.onap.aai.modelloader.config.ModelLoaderConfig; /** - * Local testing of the Babel service + * Local testing of the A&AI Service client. * */ public class TestAaiServiceClient { @@ -55,6 +55,8 @@ public class TestAaiServiceClient { Properties props = new Properties(); props.put("ml.aai.KEYSTORE_PASSWORD", "2244"); + props.put("ml.aai.KEYSTORE_FILE", "src/test/resources/auth/aai-client-cert.p12"); + props.put("ml.aai.KEYSTORE_PASSWORD", "OBF:1i9a1u2a1unz1lr61wn51wn11lss1unz1u301i6o"); ModelLoaderConfig config = new ModelLoaderConfig(props, "."); aaiClient = new AaiRestClient(config); } @@ -73,7 +75,7 @@ public class TestAaiServiceClient { @Test public void testOperations() { - String url = "http://localhost"; + String url = "http://localhost:8080"; String transId = ""; MediaType mediaType = MediaType.APPLICATION_JSON_TYPE; aaiClient.getResource(url, "", mediaType); diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java b/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java index b42fee4..4f99bfc 100644 --- a/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java +++ b/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -31,11 +31,6 @@ import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -51,10 +46,10 @@ import org.junit.Before; import org.junit.Test; import org.onap.aai.babel.service.data.BabelArtifact; import org.onap.aai.modelloader.config.ModelLoaderConfig; -import org.onap.aai.modelloader.restclient.BabelServiceClient.BabelServiceException; +import org.onap.aai.modelloader.service.HttpsBabelServiceClientFactory; /** - * Local testing of the Babel service + * Local testing of the Babel service client. * */ public class TestBabelServiceClient { @@ -62,16 +57,14 @@ public class TestBabelServiceClient { private Server server; private String responseBody; - { + @Before + public void startJetty() throws Exception { List response = new ArrayList<>(); response.add(new BabelArtifact("", null, "")); response.add(new BabelArtifact("", null, "")); response.add(new BabelArtifact("", null, "")); responseBody = new Gson().toJson(response); - } - @Before - public void startJetty() throws Exception { server = new Server(8080); server.setHandler(getMockHandler()); server.start(); @@ -83,14 +76,17 @@ public class TestBabelServiceClient { } @Test - public void testRestClient() throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, - KeyStoreException, CertificateException, IOException, BabelServiceException, URISyntaxException { + public void testRestClient() throws BabelServiceClientException, IOException, URISyntaxException { Properties configProperties = new Properties(); configProperties.put("ml.babel.KEYSTORE_PASSWORD", "OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0"); + configProperties.put("ml.babel.KEYSTORE_FILE", "src/test/resources/auth/aai-client-dummy.p12"); + configProperties.put("ml.babel.TRUSTSTORE_PASSWORD", "OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0"); + // In a real deployment this would be a different file (to the client keystore) + configProperties.put("ml.babel.TRUSTSTORE_FILE", "src/test/resources/auth/aai-client-dummy.p12"); configProperties.put("ml.babel.BASE_URL", "http://localhost:8080/"); configProperties.put("ml.babel.GENERATE_ARTIFACTS_URL", "generate"); BabelServiceClient client = - new BabelServiceClientFactory().create(new ModelLoaderConfig(configProperties, ".")); + new HttpsBabelServiceClientFactory().create(new ModelLoaderConfig(configProperties, ".")); List result = client.postArtifact(readBytesFromFile("compressedArtifacts/service-VscpaasTest-csar.csar"), "service-Vscpass-Test", "1.0", "Test-Transaction-ID-BabelClient"); @@ -120,4 +116,3 @@ public class TestBabelServiceClient { return handler; } } - diff --git a/src/test/java/org/onap/aai/modelloader/service/MockBabelServiceClientFactory.java b/src/test/java/org/onap/aai/modelloader/service/MockBabelServiceClientFactory.java new file mode 100644 index 0000000..fa369ce --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/service/MockBabelServiceClientFactory.java @@ -0,0 +1,37 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.service; + +import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.restclient.BabelServiceClient; +import org.onap.aai.modelloader.restclient.BabelServiceClientException; +import org.onap.aai.modelloader.restclient.MockBabelServiceClient; +import org.springframework.stereotype.Service; + +@Service +public class MockBabelServiceClientFactory implements BabelServiceClientFactory { + + @Override + public BabelServiceClient create(ModelLoaderConfig config) throws BabelServiceClientException { + return new MockBabelServiceClient(config); + } + +} diff --git a/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java b/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java index 366d5a5..ec55f15 100644 --- a/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java +++ b/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -39,19 +39,19 @@ public class TestArtifactInfoImpl { public void testGettersAndSetters() { ArtifactInfoImpl info = new ArtifactInfoImpl(); String artifactName = "testname"; - String artifactType = "test-type"; - String artifactVersion = "v1"; - String artifactDescription = "test description"; info.setArtifactName(artifactName); assertThat(info.getArtifactName(), is(equalTo(artifactName))); + String artifactType = "test-type"; info.setArtifactType(artifactType); assertThat(info.getArtifactType(), is(equalTo(artifactType))); + String artifactVersion = "v1"; info.setArtifactVersion(artifactVersion); assertThat(info.getArtifactVersion(), is(equalTo(artifactVersion))); + String artifactDescription = "test description"; info.setArtifactDescription(artifactDescription); assertThat(info.getArtifactDescription(), is(equalTo(artifactDescription))); diff --git a/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderApplication.java b/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderApplication.java deleted file mode 100644 index 0f3ed45..0000000 --- a/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderApplication.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.service; - -import org.junit.Test; - -/** - * Tests for ModelLoaderApplication class - * - */ -public class TestModelLoaderApplication { - - static { - System.setProperty("CONFIG_HOME", "src/test/resources"); - } - - @Test - public void testServiceStarts() { - // The SDC Distribution Client is expected to fail to initialise. - ModelLoaderApplication.main(new String[0]); - } - -} diff --git a/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderService.java b/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderService.java new file mode 100644 index 0000000..8e07650 --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderService.java @@ -0,0 +1,86 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.service; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.util.Base64; +import javax.ws.rs.core.Response; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.aai.modelloader.util.ArtifactTestUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * Tests for the ModelLoaderService class. + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {ModelLoaderService.class, MockBabelServiceClientFactory.class}) +@TestPropertySource(properties = {"CONFIG_HOME=src/test/resources",}) +public class TestModelLoaderService { + + @Autowired + private ModelLoaderService service; + + @After + public void shutdown() { + service.preShutdownOperations(); + } + + @Test + public void testMissingConfig() { + new ModelLoaderService().start(); + } + + @Test + public void testLoadModel() { + Response response = service.loadModel(""); + assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode())); + } + + @Test + public void testSaveModel() { + Response response = service.saveModel("", ""); + assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode())); + } + + @Test + public void testIngestModel() throws IOException { + byte[] csarPayload = new ArtifactTestUtils().loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"); + Response response = service.ingestModel("model-name", "", Base64.getEncoder().encodeToString(csarPayload)); + assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode())); + } + + @Test + public void testIngestModelMissingName() throws IOException { + byte[] csarPayload = new ArtifactTestUtils().loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"); + Response response = service.ingestModel("", "", Base64.getEncoder().encodeToString(csarPayload)); + assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode())); + } + +} diff --git a/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderServiceWithSdc.java b/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderServiceWithSdc.java new file mode 100644 index 0000000..ff0614b --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderServiceWithSdc.java @@ -0,0 +1,63 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.service; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.util.Base64; +import javax.ws.rs.core.Response; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.aai.modelloader.util.ArtifactTestUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * Tests for the ModelLoaderService class. + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {ModelLoaderService.class, HttpsBabelServiceClientFactory.class}) +@TestPropertySource(properties = {"CONFIG_HOME=src/test/resources/sdc_test",}) +public class TestModelLoaderServiceWithSdc { + + @Autowired + private ModelLoaderService service; + + @After + public void shutdown() { + service.preShutdownOperations(); + } + + @Test + public void testIngestModel() throws IOException { + byte[] csarPayload = new ArtifactTestUtils().loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"); + Response response = service.ingestModel("model-name", "", Base64.getEncoder().encodeToString(csarPayload)); + assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + } + + +} diff --git a/src/test/java/org/onap/aai/modelloader/service/TestNotificationDataImpl.java b/src/test/java/org/onap/aai/modelloader/service/TestNotificationDataImpl.java deleted file mode 100644 index 395b1f3..0000000 --- a/src/test/java/org/onap/aai/modelloader/service/TestNotificationDataImpl.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.service; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -/** - * Tests for NotificationDataImpl class - * - */ -public class TestNotificationDataImpl { - - @Test - public void testGettersAndSetters() { - NotificationDataImpl data = new NotificationDataImpl(); - String distributionId = "testid"; - String context = "testcontext"; - - data.setDistributionID(distributionId); - assertThat(data.getDistributionID(), is(equalTo(distributionId))); - - // Getters return empty data - assertThat(data.getArtifactMetadataByUUID(null), is(equalTo(null))); - assertThat(data.getServiceDescription(), is(equalTo(null))); - assertThat(data.getServiceInvariantUUID(), is(equalTo(null))); - assertThat(data.getServiceName(), is(equalTo(null))); - assertThat(data.getServiceUUID(), is(equalTo(null))); - assertThat(data.getServiceVersion(), is(equalTo(null))); - assertThat(data.getResources().size(), is(0)); - assertThat(data.getServiceArtifacts().size(), is(0)); - - // Unsupported method! - data.setWorkloadContext(context); - assertThat(data.getWorkloadContext(), is(equalTo(null))); - } - - - @Test - public void testEquality() { - NotificationDataImpl data = new NotificationDataImpl(); - assertThat(data, is(not(equalTo(null)))); - assertThat(data, is(not(equalTo("")))); // NOSONAR - assertThat(data, is(equalTo(data))); - - NotificationDataImpl other = new NotificationDataImpl(); - assertThat(data, is(equalTo(other))); - assertThat(data.hashCode(), is(equalTo(other.hashCode()))); - - other.setDistributionID(""); - assertThat(data, is(not(equalTo(other)))); - - data.setDistributionID("1234"); - assertThat(data, is(not(equalTo(other)))); - - other.setDistributionID("1234"); - assertThat(data, is(equalTo(other))); - assertThat(data.hashCode(), is(equalTo(other.hashCode()))); - } - -} diff --git a/src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java b/src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java index 9b6ea06..752f389 100644 --- a/src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java +++ b/src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -21,14 +21,34 @@ package org.onap.aai.modelloader.util; import java.io.IOException; +import java.net.URL; import org.apache.commons.io.IOUtils; +import org.onap.aai.babel.service.data.BabelArtifact; /** * This class provides some utilities to assist with running tests. */ public class ArtifactTestUtils { + public static BabelArtifact loadModelArtifact(String resource) throws IOException { + return new BabelArtifact("ModelArtifact", BabelArtifact.ArtifactType.MODEL, + ArtifactTestUtils.loadResourceAsString(resource)); + } public byte[] loadResource(String resourceName) throws IOException { - return IOUtils.toByteArray(ArtifactTestUtils.class.getClassLoader().getResource(resourceName)); + URL resource = getResource(resourceName); + if (resource != null) { + return IOUtils.toByteArray(resource); + } else { + throw new IOException("Cannot locate resource: " + resourceName); + } + } + + public static String loadResourceAsString(String resourceName) throws IOException { + return IOUtils.toString(getResource(resourceName)); } + + private static URL getResource(String resourceName) { + return ArtifactTestUtils.class.getClassLoader().getResource(resourceName); + } + } diff --git a/src/test/java/org/onap/aai/modelloader/util/JsonXmlConverterTest.java b/src/test/java/org/onap/aai/modelloader/util/JsonXmlConverterTest.java deleted file mode 100644 index 2271c57..0000000 --- a/src/test/java/org/onap/aai/modelloader/util/JsonXmlConverterTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.util; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.nio.file.Files; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -public class JsonXmlConverterTest { - - @Test - public void testConversion() throws Exception { - final String XML_MODEL_FILE = "src/test/resources/models/l3-network-widget.xml"; - final String JSON_MODEL_FILE = "src/test/resources/models/l3-network-widget.json"; - - try { - byte[] encoded = Files.readAllBytes(Paths.get(XML_MODEL_FILE)); - String originalXML = new String(encoded); - - assertFalse(JsonXmlConverter.isValidJson(originalXML)); - - encoded = Files.readAllBytes(Paths.get(JSON_MODEL_FILE)); - String originalJSON = new String(encoded); - - assertTrue(JsonXmlConverter.isValidJson(originalJSON)); - - String xmlFromJson = JsonXmlConverter.convertJsonToXml(originalJSON); - - // Spot check one of the attributes - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.parse(new ByteArrayInputStream(xmlFromJson.getBytes())); - NodeList nodeList = doc.getDocumentElement().getChildNodes(); - - String modelVid = "notFound"; - for (int i = 0; i < nodeList.getLength(); i++) { - Node currentNode = nodeList.item(i); - if (currentNode.getNodeName().equals("model-invariant-id")) { - modelVid = currentNode.getTextContent(); - break; - } - } - - assertTrue(modelVid.equals("3d560d81-57d0-438b-a2a1-5334dba0651a")); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } -} diff --git a/src/test/java/org/onap/aai/modelloader/util/TestJsonXmlConverter.java b/src/test/java/org/onap/aai/modelloader/util/TestJsonXmlConverter.java new file mode 100644 index 0000000..4b7db56 --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/util/TestJsonXmlConverter.java @@ -0,0 +1,82 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.util; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.ByteArrayInputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class TestJsonXmlConverter { + + private static final String XML_MODEL_FILE = "src/test/resources/models/l3-network-widget.xml"; + private static final String JSON_MODEL_FILE = "src/test/resources/models/l3-network-widget.json"; + + @Test + public void testJsonIsValid() { + assertThat(JsonXmlConverter.isValidJson("{}"), is(true)); + assertThat(JsonXmlConverter.isValidJson("[]"), is(true)); + + assertThat(JsonXmlConverter.isValidJson("{"), is(false)); + assertThat(JsonXmlConverter.isValidJson("["), is(false)); + } + + @Test + public void testConversion() throws Exception { + byte[] encoded = Files.readAllBytes(Paths.get(XML_MODEL_FILE)); + assertThat(JsonXmlConverter.isValidJson(new String(encoded)), is(false)); + encoded = Files.readAllBytes(Paths.get(JSON_MODEL_FILE)); + String originalJson = new String(encoded); + + assertThat(JsonXmlConverter.isValidJson(originalJson), is(true)); + + String xmlFromJson = JsonXmlConverter.convertJsonToXml(originalJson); + + // Spot check one of the attributes + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document doc = builder.parse(new ByteArrayInputStream(xmlFromJson.getBytes())); + NodeList nodeList = doc.getDocumentElement().getChildNodes(); + + String modelVid = "notFound"; + for (int i = 0; i < nodeList.getLength(); i++) { + Node currentNode = nodeList.item(i); + if (currentNode.getNodeName().equals("model-invariant-id")) { + modelVid = currentNode.getTextContent(); + break; + } + } + + assertThat(modelVid.equals("3d560d81-57d0-438b-a2a1-5334dba0651a"), is(true)); + + // Convert the XML form back into JSON + JsonXmlConverter.convertXmlToJson(xmlFromJson); + } +} diff --git a/src/test/resources/auth/aai-client-dummy.p12 b/src/test/resources/auth/aai-client-dummy.p12 new file mode 100644 index 0000000..ce363f5 Binary files /dev/null and b/src/test/resources/auth/aai-client-dummy.p12 differ diff --git a/src/test/resources/convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml b/src/test/resources/convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml new file mode 100644 index 0000000..bc723c1 --- /dev/null +++ b/src/test/resources/convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml @@ -0,0 +1,51 @@ + + b2b88a73-5c55-4984-99dd-a35c55935d14 + resource + + + 2e42bac2-318a-410c-b8ff-3b3a31351be7 + SCP-Test-VSP + 1.0 + SCP Test VSP + + + T + unbounded + + + T + unbounded + + + + model-ver + + model-ver.model-version-id + 06258c44-ab48-4b4b-a5db-16892f7d1e76 + + + model.model-invariant-id + 6f288081-b321-47c9-b038-6de70079a3bf + + + + + + + + model-ver + + model-ver.model-version-id + 93a6166f-b3d5-4f06-b4ba-aed48d009ad9 + + + model.model-invariant-id + acc6edd8-a8d4-4b93-afaa-0994068be14c + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/model-loader-empty-auth-password.properties b/src/test/resources/model-loader-empty-auth-password.properties index 91fd527..fabd855 100644 --- a/src/test/resources/model-loader-empty-auth-password.properties +++ b/src/test/resources/model-loader-empty-auth-password.properties @@ -1,22 +1,27 @@ # Model Loader Distribution Client Configuration ml.distribution.ACTIVE_SERVER_TLS_AUTH=false -ml.distribution.ASDC_ADDRESS= +ml.distribution.ASDC_ADDRESS=localhost:8443 +ml.distribution.MSG_BUS_ADDRESSES=localhost ml.distribution.CONSUMER_GROUP=aai-ml-group-test ml.distribution.CONSUMER_ID=aai-ml-id-test -ml.distribution.ENVIRONMENT_NAME= +ml.distribution.ENVIRONMENT_NAME=env ml.distribution.KEYSTORE_PASSWORD= -ml.distribution.KEYSTORE_FILE=asdc-client.jks -ml.distribution.PASSWORD= +ml.distribution.KEYSTORE_FILE= +ml.distribution.PASSWORD=Aa123456 ml.distribution.POLLING_INTERVAL=30 ml.distribution.POLLING_TIMEOUT=20 ml.distribution.USER=ci -ml.distribution.ARTIFACT_TYPES=MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG +ml.distribution.ARTIFACT_TYPES=MODEL_QUERY_SPEC,TOSCA_CSAR -# Model Loader AAI REST Client Configuration -ml.aai.BASE_URL= -ml.aai.MODEL_URL=/aai/v8/service-design-and-creation/models/model/ -ml.aai.NAMED_QUERY_URL=/aai/v8/service-design-and-creation/named-queries/named-query/ -ml.aai.VNF_IMAGE_URL=/aai/v8/service-design-and-creation/vnf-images +# Disable ASDC polling & enable REST interface +ml.distribution.ASDC_CONNECTION_DISABLE=true +ml.debug.INGEST_SIMULATOR=enabled + +# Model Loader Client Configuration for the A&AI REST interface +ml.aai.BASE_URL=https://localhost:8443 +ml.aai.MODEL_URL=/aai/v*/service-design-and-creation/models/model/ +ml.aai.NAMED_QUERY_URL=/aai/v*/service-design-and-creation/named-queries/named-query/ +ml.aai.VNF_IMAGE_URL=/aai/v*/service-design-and-creation/vnf-images ml.aai.KEYSTORE_FILE=aai-client-cert.p12 ml.aai.KEYSTORE_PASSWORD= ml.aai.AUTH_USER=ModelLoader diff --git a/src/test/resources/model-loader-no-auth-password.properties b/src/test/resources/model-loader-no-auth-password.properties index 2f36934..96b24c8 100644 --- a/src/test/resources/model-loader-no-auth-password.properties +++ b/src/test/resources/model-loader-no-auth-password.properties @@ -1,21 +1,26 @@ # Model Loader Distribution Client Configuration ml.distribution.ACTIVE_SERVER_TLS_AUTH=false -ml.distribution.ASDC_ADDRESS= +ml.distribution.ASDC_ADDRESS=localhost:8443 +ml.distribution.MSG_BUS_ADDRESSES=localhost ml.distribution.CONSUMER_GROUP=aai-ml-group-test ml.distribution.CONSUMER_ID=aai-ml-id-test -ml.distribution.ENVIRONMENT_NAME= +ml.distribution.ENVIRONMENT_NAME=env ml.distribution.KEYSTORE_PASSWORD= -ml.distribution.KEYSTORE_FILE=asdc-client.jks -ml.distribution.PASSWORD= +ml.distribution.KEYSTORE_FILE= +ml.distribution.PASSWORD=Aa123456 ml.distribution.POLLING_INTERVAL=30 ml.distribution.POLLING_TIMEOUT=20 ml.distribution.USER=ci -ml.distribution.ARTIFACT_TYPES=MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG +ml.distribution.ARTIFACT_TYPES=MODEL_QUERY_SPEC,TOSCA_CSAR -# Model Loader AAI REST Client Configuration -ml.aai.BASE_URL= -ml.aai.MODEL_URL=/aai/v8/service-design-and-creation/models/model/ -ml.aai.NAMED_QUERY_URL=/aai/v8/service-design-and-creation/named-queries/named-query/ -ml.aai.VNF_IMAGE_URL=/aai/v8/service-design-and-creation/vnf-images +# Disable ASDC polling & enable REST interface +ml.distribution.ASDC_CONNECTION_DISABLE=true +ml.debug.INGEST_SIMULATOR=enabled + +# Model Loader Client Configuration for the A&AI REST interface +ml.aai.BASE_URL=https://localhost:8443 +ml.aai.MODEL_URL=/aai/v*/service-design-and-creation/models/model/ +ml.aai.NAMED_QUERY_URL=/aai/v*/service-design-and-creation/named-queries/named-query/ +ml.aai.VNF_IMAGE_URL=/aai/v*/service-design-and-creation/vnf-images ml.aai.KEYSTORE_FILE=aai-client-cert.p12 ml.aai.KEYSTORE_PASSWORD= diff --git a/src/test/resources/model-loader.properties b/src/test/resources/model-loader.properties index 9f3226a..3ba1519 100644 --- a/src/test/resources/model-loader.properties +++ b/src/test/resources/model-loader.properties @@ -1,20 +1,24 @@ # Model Loader Distribution Client Configuration ml.distribution.ACTIVE_SERVER_TLS_AUTH=false -ml.distribution.ASDC_ADDRESS=localhost +ml.distribution.ASDC_ADDRESS=localhost:8443 ml.distribution.MSG_BUS_ADDRESSES=localhost ml.distribution.CONSUMER_GROUP=aai-ml-group-test ml.distribution.CONSUMER_ID=aai-ml-id-test ml.distribution.ENVIRONMENT_NAME=env ml.distribution.KEYSTORE_PASSWORD= -ml.distribution.KEYSTORE_FILE=asdc-client.jks +ml.distribution.KEYSTORE_FILE= ml.distribution.PASSWORD=Aa123456 ml.distribution.POLLING_INTERVAL=30 ml.distribution.POLLING_TIMEOUT=20 ml.distribution.USER=ci -ml.distribution.ARTIFACT_TYPES=MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG +ml.distribution.ARTIFACT_TYPES=MODEL_QUERY_SPEC,TOSCA_CSAR + +# Disable ASDC polling & enable REST interface +ml.distribution.ASDC_CONNECTION_DISABLE=true +ml.debug.INGEST_SIMULATOR=enabled # Model Loader Client Configuration for the A&AI REST interface -ml.aai.BASE_URL= +ml.aai.BASE_URL=https://localhost:8443 ml.aai.MODEL_URL=/aai/v*/service-design-and-creation/models/model/ ml.aai.NAMED_QUERY_URL=/aai/v*/service-design-and-creation/named-queries/named-query/ ml.aai.VNF_IMAGE_URL=/aai/v*/service-design-and-creation/vnf-images diff --git a/src/test/resources/sdc_test/model-loader.properties b/src/test/resources/sdc_test/model-loader.properties new file mode 100644 index 0000000..ee5c0ed --- /dev/null +++ b/src/test/resources/sdc_test/model-loader.properties @@ -0,0 +1,30 @@ +# Model Loader Distribution Client Configuration +ml.distribution.ACTIVE_SERVER_TLS_AUTH=false +ml.distribution.ASDC_ADDRESS=localhost:8443 +ml.distribution.MSG_BUS_ADDRESSES=localhost +ml.distribution.CONSUMER_GROUP=aai-ml-group-test +ml.distribution.CONSUMER_ID=aai-ml-id-test +ml.distribution.ENVIRONMENT_NAME=env +ml.distribution.KEYSTORE_PASSWORD= +ml.distribution.KEYSTORE_FILE= +ml.distribution.PASSWORD=Aa123456 +ml.distribution.POLLING_INTERVAL=30 +ml.distribution.POLLING_TIMEOUT=20 +ml.distribution.USER=ci +ml.distribution.ARTIFACT_TYPES=MODEL_QUERY_SPEC,TOSCA_CSAR + +# Model Loader Client Configuration for the A&AI REST interface +ml.aai.BASE_URL=https://localhost:8443 +ml.aai.MODEL_URL=/aai/v*/service-design-and-creation/models/model/ +ml.aai.NAMED_QUERY_URL=/aai/v*/service-design-and-creation/named-queries/named-query/ +ml.aai.VNF_IMAGE_URL=/aai/v*/service-design-and-creation/vnf-images +ml.aai.KEYSTORE_FILE=aai-client-cert.p12 +ml.aai.KEYSTORE_PASSWORD= +ml.aai.AUTH_USER=ModelLoader +ml.aai.AUTH_PASSWORD= + +# Model Loader Client Configuration for the Babel Service +ml.babel.BASE_URL= +ml.babel.GENERATE_ARTIFACTS_URL= +ml.babel.KEYSTORE_FILE= +ml.babel.KEYSTORE_PASSWORD= -- cgit 1.2.3-korg