From 1433a67a9e3dcad20d0dda8edcaad9403320f4f9 Mon Sep 17 00:00:00 2001 From: Edwin Lawrance Date: Fri, 22 Sep 2017 16:55:07 +0100 Subject: Initial code submit for Babel Change-Id: I3738ebe15eadbbd6d16e24e374c6e40c535b425d Issue-ID: AAI-46 Signed-off-by: Edwin Lawrance --- .../org/onap/aai/babel/MicroServiceAuthTest.java | 211 +++++++++++++++++++++ .../babel/csar/extractor/YamlExtractorTest.java | 141 ++++++++++++++ .../babel/csar/fixture/ArtifactInfoBuilder.java | 78 ++++++++ .../babel/csar/fixture/TestArtifactInfoImpl.java | 135 +++++++++++++ .../aai/babel/service/CsarToXmlConverterTest.java | 170 +++++++++++++++++ .../service/TestGenerateArtifactsServiceImpl.java | 111 +++++++++++ .../org/onap/aai/babel/util/ArtifactTestUtils.java | 100 ++++++++++ .../onap/aai/babel/util/TestRequestValidator.java | 72 +++++++ 8 files changed, 1018 insertions(+) create mode 100644 src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java create mode 100644 src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java create mode 100644 src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java create mode 100644 src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java create mode 100644 src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java create mode 100644 src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java create mode 100644 src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java create mode 100644 src/test/java/org/onap/aai/babel/util/TestRequestValidator.java (limited to 'src/test/java') diff --git a/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java b/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java new file mode 100644 index 0000000..f24cbf1 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java @@ -0,0 +1,211 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.babel; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Test; +import org.onap.aai.auth.AAIAuthException; +import org.onap.aai.auth.AAIMicroServiceAuth; +import org.onap.aai.auth.AAIMicroServiceAuthCore; +import org.onap.aai.babel.config.BabelAuthConfig; +import org.springframework.mock.web.MockHttpServletRequest; + +/** + * Tests @{link AAIMicroServiceAuth} + */ + +public class MicroServiceAuthTest { + + private static final String VALID_ADMIN_USER = "cn=common-name, ou=org-unit, o=org, l=location, st=state, c=us"; + private static final String authPolicyFile = "auth_policy.json"; + + static { + System.setProperty("CONFIG_HOME", + System.getProperty("user.dir") + File.separator + "src/test/resources"); + } + + /** + * Temporarily invalidate the default policy file and then try to initialise the authorisation class using the name + * of a policy file that does not exist. + * + * @throws AAIAuthException + * @throws IOException + */ + @Test(expected = AAIAuthException.class) + public void missingPolicyFile() throws AAIAuthException, IOException { + String defaultFile = AAIMicroServiceAuthCore.getDefaultAuthFileName(); + try { + AAIMicroServiceAuthCore.setDefaultAuthFileName("invalid.default.file"); + BabelAuthConfig gapServiceAuthConfig = new BabelAuthConfig(); + gapServiceAuthConfig.setAuthPolicyFile("invalid.file.name"); + new AAIMicroServiceAuth(gapServiceAuthConfig); + } finally { + AAIMicroServiceAuthCore.setDefaultAuthFileName(defaultFile); + } + } + + /** + * Test loading of a temporary file created with the specified roles + * + * @throws AAIAuthException + * @throws IOException + * @throws JSONException + */ + @Test + public void createLocalAuthFile() throws AAIAuthException, IOException, JSONException { + JSONObject roles = createRoleObject("role", createUserObject("user"), createFunctionObject("func")); + AAIMicroServiceAuth auth = createAuthService(roles); + assertThat(auth.authorize("nosuchuser", "method:func"), is(false)); + assertThat(auth.authorize("user", "method:func"), is(true)); + } + + /** + * Test that the default policy file is loaded when a non-existent file is passed to the authorisation clas. + * + * @throws AAIAuthException + */ + @Test + public void createAuthFromDefaultFile() throws AAIAuthException { + BabelAuthConfig gapServiceAuthConfig = new BabelAuthConfig(); + gapServiceAuthConfig.setAuthPolicyFile("non-existent-file"); + AAIMicroServiceAuth auth = new AAIMicroServiceAuth(gapServiceAuthConfig); + // The default policy will have been loaded + assertAdminUserAuthorisation(auth, VALID_ADMIN_USER); + } + + /** + * Test loading of the policy file relative to CONFIG_HOME + * + * @throws AAIAuthException + */ + @Test + public void createAuth() throws AAIAuthException { + AAIMicroServiceAuth auth = createStandardAuth(); + assertAdminUserAuthorisation(auth, VALID_ADMIN_USER); + } + + @Test + public void testAuthUser() throws AAIAuthException { + AAIMicroServiceAuth auth = createStandardAuth(); + assertThat(auth.authenticate(VALID_ADMIN_USER, "GET:actions"), is(equalTo("OK"))); + assertThat(auth.authenticate(VALID_ADMIN_USER, "WRONG:action"), is(equalTo("AAI_9101"))); + } + + + + @Test + public void testValidateRequest() throws AAIAuthException { + AAIMicroServiceAuth auth = createStandardAuth(); + assertThat(auth.validateRequest(null, new MockHttpServletRequest(), null, "app/v1/gap"), is(false)); + } + + private AAIMicroServiceAuth createStandardAuth() throws AAIAuthException { + BabelAuthConfig gapServiceAuthConfig = new BabelAuthConfig(); + gapServiceAuthConfig.setAuthPolicyFile(authPolicyFile); + return new AAIMicroServiceAuth(gapServiceAuthConfig); + } + + /** + * @param rolesJson + * @return + * @throws IOException + * @throws AAIAuthException + */ + private AAIMicroServiceAuth createAuthService(JSONObject roles) throws IOException, AAIAuthException { + BabelAuthConfig babelAuthConfig = new BabelAuthConfig(); + File file = File.createTempFile("auth-policy", "json"); + file.deleteOnExit(); + FileWriter fileWriter = new FileWriter(file); + fileWriter.write(roles.toString()); + fileWriter.flush(); + fileWriter.close(); + + babelAuthConfig.setAuthPolicyFile(file.getAbsolutePath()); + return new AAIMicroServiceAuth(babelAuthConfig); + } + + /** + * Assert authorisation results for an admin user based on the test policy file + * + * @param auth + * @param adminUser + * @throws AAIAuthException + */ + private void assertAdminUserAuthorisation(AAIMicroServiceAuth auth, String adminUser) throws AAIAuthException { + assertThat(auth.authorize(adminUser, "GET:actions"), is(true)); + assertThat(auth.authorize(adminUser, "POST:actions"), is(true)); + assertThat(auth.authorize(adminUser, "PUT:actions"), is(true)); + assertThat(auth.authorize(adminUser, "DELETE:actions"), is(true)); + } + + private JSONArray createFunctionObject(String functionName) throws JSONException { + JSONArray functionsArray = new JSONArray(); + JSONObject func = new JSONObject(); + func.put("name", functionName); + func.put("methods", createMethodObject("method")); + functionsArray.put(func); + return functionsArray; + } + + private JSONArray createMethodObject(String methodName) throws JSONException { + JSONArray methodsArray = new JSONArray(); + JSONObject method = new JSONObject(); + method.put("name", methodName); + methodsArray.put(method); + return methodsArray; + } + + private JSONArray createUserObject(String username) throws JSONException { + JSONArray usersArray = new JSONArray(); + JSONObject user = new JSONObject(); + user.put("username", username); + usersArray.put(user); + return usersArray; + } + + private JSONObject createRoleObject(String roleName, JSONArray usersArray, JSONArray functionsArray) + throws JSONException { + JSONObject roles = new JSONObject(); + + JSONObject role = new JSONObject(); + role.put("name", roleName); + role.put("functions", functionsArray); + role.put("users", usersArray); + + JSONArray rolesArray = new JSONArray(); + rolesArray.put(role); + roles.put("roles", rolesArray); + + return roles; + } + +} diff --git a/src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java b/src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java new file mode 100644 index 0000000..54f4c65 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java @@ -0,0 +1,141 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.babel.csar.extractor; + +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.apache.commons.io.IOUtils; +import org.junit.Test; +import org.onap.aai.babel.util.ArtifactTestUtils; +import org.openecomp.sdc.generator.data.Artifact; + +/** + * Tests @see YamlExtractor + */ +public class YamlExtractorTest { + + private static final String FOO = "foo"; + private static final String SOME_BYTES = "just some bytes that will pass the firsts validation"; + private static final String SUPPLY_AN_ARCHIVE = "An archive must be supplied for processing."; + private static final String SUPPLY_NAME = "The name of the archive must be supplied for processing."; + private static final String SUPPLY_VERSION = "The version must be supplied for processing."; + + @Test + public void extract_nullContentSupplied() { + invalidArgumentsTest(null, FOO, FOO, SUPPLY_AN_ARCHIVE); + } + + private void invalidArgumentsTest(byte[] archive, String name, String version, String expectedErrorMessage) { + try { + YamlExtractor.extract(archive, name, version); + fail("An instance of InvalidArchiveException should have been thrown"); + } catch (Exception ex) { + assertTrue(ex instanceof InvalidArchiveException); + assertEquals(expectedErrorMessage, ex.getLocalizedMessage()); + } + } + + @Test + public void extract_emptyContentSupplied() { + invalidArgumentsTest(new byte[0], FOO, FOO, SUPPLY_AN_ARCHIVE); + } + + @Test + public void extract_nullNameSupplied() { + invalidArgumentsTest(SOME_BYTES.getBytes(), null, FOO, SUPPLY_NAME); + } + + @Test + public void extract_blankNameSupplied() { + invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), " \t ", FOO, + SUPPLY_NAME); + } + + @Test + public void extract_emptyNameSupplied() { + invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), "", FOO, SUPPLY_NAME); + } + + @Test + public void extract_nullVersionSupplied() { + invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), FOO, null, + SUPPLY_VERSION); + } + + @Test + public void extract_blankVersionSupplied() { + invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), FOO, " \t ", + SUPPLY_VERSION); + } + + @Test + public void extract_emptyVersionSupplied() { + invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), FOO, "", + SUPPLY_VERSION); + } + + @Test + public void extract_invalidContentSupplied() { + invalidArgumentsTest("This is a piece of nonsense and not a zip file".getBytes(), FOO, FOO, + "An error occurred trying to create a ZipFile. Is the content being converted really a csar file?"); + } + + @Test + public void extract_archiveContainsNoYmlFiles() throws IOException { + try { + YamlExtractor.extract(loadResource("compressedArtifacts/noYmlFilesArchive.zip"), "noYmlFilesArchive.zip", + "v1"); + fail("An instance of InvalidArchiveException should have been thrown."); + } catch (Exception e) { + assertTrue("An instance of InvalidArchiveException should have been thrown.", + e instanceof InvalidArchiveException); + assertEquals("Incorrect message was returned", "No valid yml files were found in the csar file.", + e.getMessage()); + } + } + + private byte[] loadResource(final String archiveName) throws IOException { + return IOUtils.toByteArray(YamlExtractor.class.getClassLoader().getResource(archiveName)); + } + + @Test + public void extract_archiveContainsThreeRelevantYmlFilesFromSdWanService() + throws IOException, InvalidArchiveException { + List ymlFiles = + YamlExtractor.extract(loadResource("compressedArtifacts/service-SdWanServiceTest-csar.csar"), + "service-SdWanServiceTest-csar.csar", "v1"); + + List payloads = new ArrayList<>(); + payloads.add("ymlFiles/resource-SdWanTestVsp-template.yml"); + payloads.add("ymlFiles/resource-TunnelXconntest-template.yml"); + payloads.add("ymlFiles/service-SdWanServiceTest-template.yml"); + + new ArtifactTestUtils().performYmlAsserts(ymlFiles, payloads); + } +} + diff --git a/src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java b/src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java new file mode 100644 index 0000000..0ff8fa1 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java @@ -0,0 +1,78 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.babel.csar.fixture; + +import java.util.ArrayList; +import java.util.List; +import org.openecomp.sdc.api.notification.IArtifactInfo; + +/** + * This class builds an instance of IArtifactInfo for test purposes. + */ +public class ArtifactInfoBuilder { + + /** + * Builds an implementation of IArtifactInfo for test purposes. + *

+ * + * @param type type of artifact + * @param name name of artifact + * @param description description of artifact + * @param version version of artifact + * @return IArtifactInfo implementation of IArtifactInfo from given parameters for test purposes + */ + public static IArtifactInfo build(final String type, final String name, final String description, + final String version) { + IArtifactInfo artifact = new TestArtifactInfoImpl(); + + ((TestArtifactInfoImpl) artifact).setArtifactType(type); + ((TestArtifactInfoImpl) artifact).setArtifactName(name); + ((TestArtifactInfoImpl) artifact).setArtifactDescription(description); + ((TestArtifactInfoImpl) artifact).setArtifactVersion(version); + + return artifact; + } + + /** + * This method is responsible for building a collection of artifacts from a given set of info. + *

+ * The info supplied is a two dimensional array with each element of the first dimension representing a single + * artifact and each element of the second dimension represents a property of the artifact. + *

+ * The method will call {@link #build(String, String, String, String)} to build each element in the first dimension + * where the elements of the second dimension are the arguments to {@link #build(String, String, String, String)}. + *

+ * + * @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 + */ + static List buildArtifacts(final String[][] artifactInfoBits) { + List artifacts = new ArrayList<>(); + + for (String[] artifactInfoBit : artifactInfoBits) { + artifacts.add(build(artifactInfoBit[0], artifactInfoBit[1], artifactInfoBit[2], artifactInfoBit[3])); + } + + return artifacts; + } +} diff --git a/src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java b/src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java new file mode 100644 index 0000000..bbf4a43 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java @@ -0,0 +1,135 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.babel.csar.fixture; + +import org.openecomp.sdc.api.notification.IArtifactInfo; + +/** + * This class is an implementation of IArtifactInfo for test purposes. + */ +public class TestArtifactInfoImpl implements IArtifactInfo { + + private String artifactName; + private String artifactType; + private String artifactDescription; + private String artifactVersion; + + @Override + public String getArtifactName() { + return artifactName; + } + + void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + @Override + public String getArtifactType() { + return artifactType; + } + + void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + @Override + public String getArtifactURL() { + return null; + } + + @Override + public String getArtifactChecksum() { + return null; + } + + @Override + public String getArtifactDescription() { + return artifactDescription; + } + + void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + @Override + public Integer getArtifactTimeout() { + return null; + } + + @Override + public String getArtifactVersion() { + return artifactVersion; + } + + void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + @Override + public String getArtifactUUID() { + return null; + } + + @Override + public IArtifactInfo getGeneratedArtifact() { + return null; + } + + @Override + public java.util.List getRelatedArtifacts() { + return null; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + TestArtifactInfoImpl that = (TestArtifactInfoImpl) o; + + if (artifactName != null ? !artifactName.equals(that.artifactName) : that.artifactName != null) { + return false; + } + if (artifactType != null ? !artifactType.equals(that.artifactType) : that.artifactType != null) { + return false; + } + if (artifactDescription != null ? !artifactDescription.equals(that.artifactDescription) + : that.artifactDescription != null) { + return false; + } + return artifactVersion != null ? artifactVersion.equals(that.artifactVersion) : that.artifactVersion == null; + } + + @Override + public int hashCode() { + int result = artifactName != null ? artifactName.hashCode() : 0; + result = 31 * result + (artifactType != null ? artifactType.hashCode() : 0); + result = 31 * result + (artifactDescription != null ? artifactDescription.hashCode() : 0); + result = 31 * result + (artifactVersion != null ? artifactVersion.hashCode() : 0); + return result; + } +} diff --git a/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java b/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java new file mode 100644 index 0000000..5c1e213 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java @@ -0,0 +1,170 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.babel.service; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.custommonkey.xmlunit.XMLTestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.onap.aai.babel.csar.CsarConverterException; +import org.onap.aai.babel.csar.CsarToXmlConverter; +import org.onap.aai.babel.service.data.BabelArtifact; +import org.onap.aai.babel.util.ArtifactTestUtils; +import org.onap.aai.babel.xml.generator.ModelGenerator; +import org.onap.aai.babel.xml.generator.XmlArtifactGenerationException; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.xml.sax.SAXException; + +/** + * Tests {@link CsarToXmlConverter} + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(ModelGenerator.class) +public class CsarToXmlConverterTest extends XMLTestCase { + + private static final String NAME = "the_name_of_the_csar_file.csar"; + private static final String VERSION = "v1"; + + private CsarToXmlConverter converter; + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Before + public void setUp() { + converter = new CsarToXmlConverter(); + URL url = CsarToXmlConverterTest.class.getClassLoader().getResource("artifact-generator.properties"); + System.setProperty("artifactgenerator.config", url.getPath()); + } + + @After + public void tearDown() { + converter = null; + } + + @Test(expected = NullPointerException.class) + public void generateXmlFromCsar_nullArtifactSupplied() throws CsarConverterException { + converter.generateXmlFromCsar(null, null, null); + } + + @Test(expected = NullPointerException.class) + public void generateXmlFromCsar_missingName() throws CsarConverterException, IOException { + byte[] csarArchive = new ArtifactTestUtils().loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"); + converter.generateXmlFromCsar(csarArchive, null, null); + } + + @Test(expected = NullPointerException.class) + public void generateXmlFromCsar_missingVersion() throws CsarConverterException, IOException { + byte[] csarArchive = new ArtifactTestUtils().loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"); + converter.generateXmlFromCsar(csarArchive, NAME, null); + } + + @Test(expected = CsarConverterException.class) + public void generateXmlFromCsar_noPayloadExists() throws CsarConverterException { + converter.generateXmlFromCsar(new byte[0], NAME, VERSION); + } + + @Test(expected = CsarConverterException.class) + public void generateXmlFromCsar_csarFileHasNoYmlFiles() throws CsarConverterException, IOException { + byte[] csarArchive = new ArtifactTestUtils().loadResource("compressedArtifacts/noYmlFilesArchive.zip"); + converter.generateXmlFromCsar(csarArchive, "noYmlFilesArchive.zip", VERSION); + } + + @Test + public void generateXmlFromCsar_artifactgenerator_config_systemPropertyNotSet() + throws IOException, XmlArtifactGenerationException, CsarConverterException { + exception.expect(CsarConverterException.class); + exception.expectMessage("Cannot generate artifacts. artifactgenerator.config system property not configured"); + + byte[] csarArchive = + new ArtifactTestUtils().loadResource("compressedArtifacts/service-SdWanServiceTest-csar.csar"); + + // Unset the required system property + System.clearProperty("artifactgenerator.config"); + converter.generateXmlFromCsar(csarArchive, VERSION, "service-SdWanServiceTest-csar.csar"); + } + + @Test + public void generateXmlFromCsar() throws CsarConverterException, IOException, XmlArtifactGenerationException { + byte[] csarArchive = + new ArtifactTestUtils().loadResource("compressedArtifacts/service-SdWanServiceTest-csar.csar"); + + Map expectedXmlFiles = createExpectedXmlFiles(); + List generatedArtifacts = + converter.generateXmlFromCsar(csarArchive, VERSION, "service-SdWanServiceTest-csar.csar"); + + generatedArtifacts.forEach(ga -> { + try { + + String x1 = expectedXmlFiles.get(ga.getName()); + + String x2 = bytesToString(ga.getPayload()); + + assertXMLEqual("The content of " + ga.getName() + " must match the expected content", x1, x2); + + } catch (SAXException | IOException e) { + fail("There was an Exception parsing the XML: "+e.getMessage()); + } + }); + } + + public String bytesToString(byte[] source) { + ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(source)); + + String result = new BufferedReader(new InputStreamReader(bis)).lines().collect(Collectors.joining("\n")); + + return result; + + } + + private Map createExpectedXmlFiles() throws IOException { + Map xml = new HashMap<>(); + + ArtifactTestUtils utils = new ArtifactTestUtils(); + + String[] filesToLoad = + {"AAI-SD-WAN-Service-Test-service-1.0.xml", "AAI-SdWanTestVsp..DUMMY..module-0-resource-2.xml", + "AAI-Tunnel_XConnTest-resource-2.0.xml", "AAI-SD-WAN-Test-VSP-resource-1.0.xml"}; + + for (String s : filesToLoad) { + xml.put(s, utils.loadResourceAsString("generatedXml/" + s)); + + } + + return xml; + } +} diff --git a/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java b/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java new file mode 100644 index 0000000..5d2309f --- /dev/null +++ b/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java @@ -0,0 +1,111 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.babel.service; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.stream.Collectors; +import javax.ws.rs.core.Response; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Direct invocation of the generate artifacts service implementation + * + */ +public class TestGenerateArtifactsServiceImpl { + + @BeforeClass + public static void setup() { + URL url = TestGenerateArtifactsServiceImpl.class.getClassLoader().getResource("artifact-generator.properties"); + System.setProperty("artifactgenerator.config", url.getPath()); + } + + @Test + public void testGenerateArtifacts() throws Exception { + String jsonRequest = readstringFromFile("jsonFiles/success_request.json"); + Response response = processJsonRequest(jsonRequest); + assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode())); + assertThat(response.getEntity(), is(readstringFromFile("response/response.json"))); + } + + + @Test + public void testInvalidCsarFile() throws URISyntaxException, IOException{ + String jsonRequest = readstringFromFile("jsonFiles/invalid_csar_request.json"); + Response response = processJsonRequest(jsonRequest); + assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model.")); + } + + @Test + public void testInvalidJsonFile() throws URISyntaxException, IOException{ + String jsonRequest = readstringFromFile("jsonFiles/invalid_json_request.json"); + Response response = processJsonRequest(jsonRequest); + assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); + assertThat(response.getEntity(), is("Malformed request.")); + } + + @Test + public void testMissingArtifactName() throws Exception { + String jsonRequest = readstringFromFile("jsonFiles/missing_artifact_name_request.json"); + Response response = processJsonRequest(jsonRequest); + assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); + assertThat(response.getEntity(), is("No artifact name attribute found in the request body." )); + } + + @Test + public void testMissingArtifactVersion() throws Exception { + String jsonRequest = readstringFromFile("jsonFiles/missing_artifact_version_request.json"); + Response response = processJsonRequest(jsonRequest); + assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); + assertThat(response.getEntity(), is("No artifact version attribute found in the request body.")); + } + + @Test + public void testMissingCsarFile() throws Exception { + String jsonRequest = readstringFromFile("jsonFiles/missing_csar_request.json"); + Response response = processJsonRequest(jsonRequest); + assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); + assertThat(response.getEntity(), is("No csar attribute found in the request body.")); + } + + + private Response processJsonRequest(String jsonRequest) { + GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(/* No authentiction required */ null); + return service.generateArtifacts(jsonRequest); + } + + private String readstringFromFile(String resourceFile) throws IOException, URISyntaxException { + return Files.lines(Paths.get(ClassLoader.getSystemResource(resourceFile).toURI())) + .collect(Collectors.joining()); + } + + +} diff --git a/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java b/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java new file mode 100644 index 0000000..74f0c0e --- /dev/null +++ b/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java @@ -0,0 +1,100 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.babel.util; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import com.google.common.base.Throwables; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Base64; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.commons.io.IOUtils; +import org.openecomp.sdc.generator.data.Artifact; + +/** + * This class provides some utilities to assist with running tests. + */ +public class ArtifactTestUtils { + + public void performYmlAsserts(List toscaFiles, List ymlPayloadsToLoad) { + assertThat("An unexpected number of yml files have been extracted", toscaFiles.size(), + is(ymlPayloadsToLoad.size())); + + Set ymlPayloads = ymlPayloadsToLoad.stream().map(s -> { + try { + return loadResourceAsString(s); + } catch (IOException e) { + throw Throwables.propagate(e); + } + }).collect(Collectors.toSet()); + + toscaFiles.forEach(ts -> { + boolean payloadFound = false; + + String s = bytesToString(ts.getPayload()); + + for (String ymlPayload : ymlPayloads) { + String tscontent = ymlPayload; + + if (s.endsWith(tscontent)) { + payloadFound = true; + break; + } + } + assertThat("The content of each yml file must match the actual content of the file extracted (" + + ts.getName() + ")", payloadFound, is(true)); + }); + } + + public byte[] loadResource(String resourceName) throws IOException { + + return IOUtils.toByteArray(ArtifactTestUtils.class.getClassLoader().getResource(resourceName)); + } + + public String loadResourceAsString(String resourceName) throws IOException { + + InputStream is = ArtifactTestUtils.class.getClassLoader().getResource(resourceName).openStream(); + + String result = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n")); + + return result; + + } + + public String bytesToString(byte[] source) { + ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(source)); + + String result = new BufferedReader(new InputStreamReader(bis)).lines().collect(Collectors.joining("\n")); + + return result; + + } + +} diff --git a/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java b/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java new file mode 100644 index 0000000..030c24d --- /dev/null +++ b/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java @@ -0,0 +1,72 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.babel.util; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.aai.babel.service.data.BabelRequest; + +public class TestRequestValidator { + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Test + public void testMissingArtifactNameExceptionThrown() throws Exception{ + exception.expect(RequestValidationException.class); + exception.expectMessage("No artifact name attribute found in the request body."); + + BabelRequest request = new BabelRequest(); + request.setCsar("UEsDBBQACAgIAGsrz0oAAAAAAAAAAAAAAAAJAAAAY3Nhci5tZXRhC3Z"); + request.setArtifactVersion("1.0"); + request.setArtifactName(null); + RequestValidator.validateRequest(request); + } + + + @Test + public void testMissingArtifactVersionExceptionThrown() throws Exception{ + exception.expect(RequestValidationException.class); + exception.expectMessage("No artifact version attribute found in the request body."); + + BabelRequest request = new BabelRequest(); + request.setCsar("UEsDBBQACAgIAGsrz0oAAAAAAAAAAAAAAAAJAAAAY3Nhci5tZXRhC3Z"); + request.setArtifactVersion(null); + request.setArtifactName("hello"); + RequestValidator.validateRequest(request); + } + + @Test + public void testMissingCsarFile() throws Exception{ + exception.expect(RequestValidationException.class); + exception.expectMessage("No csar attribute found in the request body."); + + BabelRequest request = new BabelRequest(); + request.setCsar(null); + request.setArtifactVersion("1.0"); + request.setArtifactName("hello"); + RequestValidator.validateRequest(request); + } + +} -- cgit 1.2.3-korg