diff options
Diffstat (limited to 'src/test/java/org')
14 files changed, 933 insertions, 221 deletions
diff --git a/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java b/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java index f24cbf1..6912d90 100644 --- a/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java +++ b/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 European Software Marketing Ltd. + * 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. @@ -17,8 +17,6 @@ * 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; @@ -49,14 +47,13 @@ public class MicroServiceAuthTest { private static final String authPolicyFile = "auth_policy.json"; static { - System.setProperty("CONFIG_HOME", - System.getProperty("user.dir") + File.separator + "src/test/resources"); + 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 */ @@ -65,9 +62,9 @@ public class MicroServiceAuthTest { String defaultFile = AAIMicroServiceAuthCore.getDefaultAuthFileName(); try { AAIMicroServiceAuthCore.setDefaultAuthFileName("invalid.default.file"); - BabelAuthConfig gapServiceAuthConfig = new BabelAuthConfig(); - gapServiceAuthConfig.setAuthPolicyFile("invalid.file.name"); - new AAIMicroServiceAuth(gapServiceAuthConfig); + BabelAuthConfig babelServiceAuthConfig = new BabelAuthConfig(); + babelServiceAuthConfig.setAuthPolicyFile("invalid.file.name"); + new AAIMicroServiceAuth(babelServiceAuthConfig); } finally { AAIMicroServiceAuthCore.setDefaultAuthFileName(defaultFile); } @@ -75,7 +72,7 @@ public class MicroServiceAuthTest { /** * Test loading of a temporary file created with the specified roles - * + * * @throws AAIAuthException * @throws IOException * @throws JSONException @@ -90,21 +87,21 @@ public class MicroServiceAuthTest { /** * 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); + BabelAuthConfig babelServiceAuthConfig = new BabelAuthConfig(); + babelServiceAuthConfig.setAuthPolicyFile("non-existent-file"); + AAIMicroServiceAuth auth = new AAIMicroServiceAuth(babelServiceAuthConfig); // 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 @@ -125,13 +122,13 @@ public class MicroServiceAuthTest { @Test public void testValidateRequest() throws AAIAuthException { AAIMicroServiceAuth auth = createStandardAuth(); - assertThat(auth.validateRequest(null, new MockHttpServletRequest(), null, "app/v1/gap"), is(false)); + assertThat(auth.validateRequest(null, new MockHttpServletRequest(), null, "app/v1/babel"), is(false)); } private AAIMicroServiceAuth createStandardAuth() throws AAIAuthException { - BabelAuthConfig gapServiceAuthConfig = new BabelAuthConfig(); - gapServiceAuthConfig.setAuthPolicyFile(authPolicyFile); - return new AAIMicroServiceAuth(gapServiceAuthConfig); + BabelAuthConfig babelServiceAuthConfig = new BabelAuthConfig(); + babelServiceAuthConfig.setAuthPolicyFile(authPolicyFile); + return new AAIMicroServiceAuth(babelServiceAuthConfig); } /** @@ -155,7 +152,7 @@ public class MicroServiceAuthTest { /** * Assert authorisation results for an admin user based on the test policy file - * + * * @param auth * @param adminUser * @throws AAIAuthException 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 index 54f4c65..9024efa 100644 --- a/src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java +++ b/src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 European Software Marketing Ltd. + * 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. @@ -17,8 +17,6 @@ * 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; @@ -32,7 +30,7 @@ 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; +import org.onap.aai.babel.xml.generator.data.Artifact; /** * Tests @see YamlExtractor @@ -124,7 +122,7 @@ public class YamlExtractorTest { } @Test - public void extract_archiveContainsThreeRelevantYmlFilesFromSdWanService() + public void extract_archiveContainsOnlyTheExpectedYmlFilesFromSdWanService() throws IOException, InvalidArchiveException { List<Artifact> ymlFiles = YamlExtractor.extract(loadResource("compressedArtifacts/service-SdWanServiceTest-csar.csar"), @@ -134,6 +132,8 @@ public class YamlExtractorTest { payloads.add("ymlFiles/resource-SdWanTestVsp-template.yml"); payloads.add("ymlFiles/resource-TunnelXconntest-template.yml"); payloads.add("ymlFiles/service-SdWanServiceTest-template.yml"); + payloads.add("ymlFiles/artifacts.yml"); + payloads.add("ymlFiles/data.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 index 0ff8fa1..20c8254 100644 --- a/src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java +++ b/src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 European Software Marketing Ltd. + * 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. @@ -17,8 +17,6 @@ * 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; 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 index bbf4a43..dfca951 100644 --- a/src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java +++ b/src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 European Software Marketing Ltd. + * 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. @@ -17,11 +17,11 @@ * 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.Objects; +import org.apache.commons.lang3.builder.EqualsBuilder; import org.openecomp.sdc.api.notification.IArtifactInfo; /** @@ -101,35 +101,24 @@ public class TestArtifactInfoImpl implements IArtifactInfo { } @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) { + public boolean equals(Object obj) { + if (!(obj instanceof TestArtifactInfoImpl)) { return false; + } else if (obj == this) { + return true; } - return artifactVersion != null ? artifactVersion.equals(that.artifactVersion) : that.artifactVersion == null; + TestArtifactInfoImpl rhs = (TestArtifactInfoImpl) obj; + // @formatter:off + return new EqualsBuilder() + .append(artifactType, rhs.artifactType) + .append(artifactDescription, rhs.artifactDescription) + .append(artifactVersion, rhs.artifactVersion) + .isEquals(); + // @formatter:on } @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; + return Objects.hash(this.artifactType, this.artifactDescription, this.artifactVersion); } } diff --git a/src/test/java/org/onap/aai/babel/logging/LogReader.java b/src/test/java/org/onap/aai/babel/logging/LogReader.java new file mode 100644 index 0000000..c2a8e64 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/logging/LogReader.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.babel.logging; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import org.apache.commons.lang.time.StopWatch; +import org.junit.Assert; + +public class LogReader { + + private Map<String, Path> cachedLogMap = new HashMap<>(); + private Map<String, BufferedReader> readersMap = new HashMap<>(); + private BufferedReader cachedReader; + + public LogReader(String logDirectory, String logFilePrefix) throws IOException { + cachedReader = getReader(logDirectory, logFilePrefix); + } + + private BufferedReader getReader(String logDirectory, String logFilePrefix) throws IOException { + BufferedReader reader = readersMap.get(logFilePrefix); + if (reader == null) { + reader = new BufferedReader(new FileReader(getLogFile(logDirectory, logFilePrefix))); + while (reader.readLine() != null) { + // Consume all lines + } + readersMap.put(logFilePrefix, reader); + } + return reader; + } + + /** + * @param logDirectory + * @return the most recently created log file. + * @throws IOException + */ + public File getLogFile(String logDirectory, String filenamePrefix) throws IOException { + Path cachedLog = cachedLogMap.get(filenamePrefix); + + if (cachedLog == null) { + Optional<Path> latestFilePath = Files.list(Paths.get(logDirectory)) + .filter(f -> Files.isDirectory(f) == false && f.getFileName().toString().startsWith(filenamePrefix)) + .max((f1, f2) -> (int) (f1.toFile().lastModified() - f2.toFile().lastModified())); + if (latestFilePath.isPresent()) { + cachedLog = latestFilePath.get(); + } else { + throw new IOException("No validation log files were found!"); + } + } + return cachedLog.toFile(); + } + + /** + * @return new lines appended to the log file + * @throws IOException + */ + public String getNewLines() throws IOException { + StopWatch stopwatch = new StopWatch(); + stopwatch.start(); + + while (!cachedReader.ready()) { + if (stopwatch.getTime() > TimeUnit.SECONDS.toMillis(30)) { + Assert.fail("Test took too long"); + } + // else keep waiting + } + + StringBuilder lines = new StringBuilder(); + String line; + while ((line = cachedReader.readLine()) != null) { + lines.append(line).append(System.lineSeparator()); + } + return lines.toString(); + } +} diff --git a/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java b/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java new file mode 100644 index 0000000..8a038b2 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.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.babel.logging; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.io.IOException; +import java.util.Arrays; +import javax.ws.rs.core.HttpHeaders; +import org.apache.commons.lang.time.StopWatch; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.babel.logging.LogHelper.TriConsumer; +import org.onap.aai.cl.api.LogFields; +import org.onap.aai.cl.api.Logger; +import org.onap.aai.cl.mdc.MdcOverride; + +/** + * Simple test to log each of the validation messages in turn. + * + * This version tests only the error logger at INFO level. + * + */ +public class TestApplicationLogger { + + @BeforeClass + public static void setupClass() { + System.setProperty("AJSC_HOME", "."); + } + + /** + * Check that each message can be logged and that (by implication of successful logging) there is a corresponding + * resource (message format). + * + * @throws IOException + */ + @Test + public void logAllMessages() throws IOException { + Logger logger = LogHelper.INSTANCE; + LogReader errorReader = new LogReader(LogHelper.getLogDirectory(), "error"); + LogReader debugReader = new LogReader(LogHelper.getLogDirectory(), "debug"); + String[] args = {"1", "2", "3", "4"}; + for (ApplicationMsgs msg : Arrays.asList(ApplicationMsgs.values())) { + if (msg.name().endsWith("ERROR")) { + logger.error(msg, args); + validateLoggedMessage(msg, errorReader, "ERROR"); + + logger.error(msg, new RuntimeException("fred"), args); + validateLoggedMessage(msg, errorReader, "fred"); + } else { + logger.info(msg, args); + validateLoggedMessage(msg, errorReader, "INFO"); + + logger.warn(msg, args); + validateLoggedMessage(msg, errorReader, "WARN"); + } + + logger.debug(msg, args); + validateLoggedMessage(msg, debugReader, "DEBUG"); + + // The trace level is not enabled + logger.trace(msg, args); + } + } + + /** + * Check that each message can be logged and that (by implication of successful logging) there is a corresponding + * resource (message format). + * + * @throws IOException + */ + @Test + public void logDebugMessages() throws IOException { + LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug"); + LogHelper.INSTANCE.debug("a message"); + String s = reader.getNewLines(); + assertThat(s, is(notNullValue())); + } + + /** + * Check logAudit with HTTP headers + * + * @throws IOException + */ + @Test + public void logAuditMessage() throws IOException { + LogHelper logger = LogHelper.INSTANCE; + LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit"); + + HttpHeaders headers = Mockito.mock(HttpHeaders.class); + Mockito.when(headers.getHeaderString("X-ECOMP-RequestID")).thenReturn("ecomp-request-id"); + Mockito.when(headers.getHeaderString("X-FromAppId")).thenReturn("app-id"); + + // Call logAudit without first calling startAudit + logger.logAuditSuccess("first call: bob"); + String s = reader.getNewLines(); + assertThat(s, is(notNullValue())); + assertThat("audit message log level", s, containsString("INFO")); + assertThat("audit message content", s, containsString("bob")); + + // This time call the start method + logger.startAudit(headers, null); + logger.logAuditSuccess("second call: foo"); + s = reader.getNewLines(); + assertThat(s, is(notNullValue())); + assertThat("audit message log level", s, containsString("INFO")); + assertThat("audit message content", s, containsString("foo")); + assertThat("audit message content", s, containsString("ecomp-request-id")); + assertThat("audit message content", s, containsString("app-id")); + } + + /** + * Check logAudit with no HTTP headers + * + * @throws IOException + */ + @Test + public void logAuditMessageWithoutHeaders() throws IOException { + LogHelper logger = LogHelper.INSTANCE; + LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit"); + logger.startAudit(null, null); + logger.logAuditSuccess("foo"); + String s = reader.getNewLines(); + assertThat(s, is(notNullValue())); + assertThat("audit message log level", s, containsString("INFO")); + assertThat("audit message content", s, containsString("foo")); + } + + /** + * Check logMetrics + * + * @throws IOException + */ + @Test + public void logMetricsMessage() throws IOException { + LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics"); + LogHelper logger = LogHelper.INSTANCE; + logger.logMetrics("metrics: fred"); + String s = reader.getNewLines(); + assertThat(s, is(notNullValue())); + assertThat("metrics message log level", s, containsString("INFO")); + assertThat("metrics message content", s, containsString("fred")); + } + + @Test + public void logMetricsMessageWithStopwatch() throws IOException { + LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics"); + LogHelper logger = LogHelper.INSTANCE; + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + logger.logMetrics(stopWatch, "joe", "bloggs"); + String logLine = reader.getNewLines(); + assertThat(logLine, is(notNullValue())); + assertThat("metrics message log level", logLine, containsString("INFO")); + assertThat("metrics message content", logLine, containsString("joe")); + } + + @Test + public void callUnsupportedMethods() throws IOException { + LogHelper logger = LogHelper.INSTANCE; + ApplicationMsgs dummyMsg = ApplicationMsgs.LOAD_PROPERTIES; + callUnsupportedOperationMethod(logger::error, dummyMsg); + callUnsupportedOperationMethod(logger::info, dummyMsg); + callUnsupportedOperationMethod(logger::warn, dummyMsg); + callUnsupportedOperationMethod(logger::debug, dummyMsg); + callUnsupportedOperationMethod(logger::trace, dummyMsg); + try { + logger.error(dummyMsg, new LogFields(), new RuntimeException("test"), ""); + } catch (UnsupportedOperationException e) { + // Expected to reach here + } + try { + logger.info(dummyMsg, new LogFields(), new MdcOverride(), ""); + } catch (UnsupportedOperationException e) { + // Expected to reach here + } + try { + logger.formatMsg(dummyMsg, ""); + } catch (UnsupportedOperationException e) { + // Expected to reach here + } + } + + /** + * Call a logger method which is expected to throw an UnsupportedOperationException + * + * @param logMethod + * @param dummyMsg + */ + private void callUnsupportedOperationMethod(TriConsumer<Enum<?>, LogFields, String[]> logMethod, + ApplicationMsgs dummyMsg) { + try { + logMethod.accept(dummyMsg, new LogFields(), new String[] {""}); + org.junit.Assert.fail("method should have thrown execption"); // NOSONAR as code not reached + } catch (UnsupportedOperationException e) { + // Expected to reach here + } + } + + /** + * Assert that a log message was logged to the expected log file at the expected severity + * + * @param msg + * @param reader + * @param severity + * @throws IOException + */ + private void validateLoggedMessage(ApplicationMsgs msg, LogReader reader, String severity) throws IOException { + String s = reader.getNewLines(); + assertThat(s, is(notNullValue())); + assertThat(msg.toString() + " log level", s, containsString(severity)); + } +} diff --git a/src/test/java/org/onap/aai/babel/parser/TestToscaParser.java b/src/test/java/org/onap/aai/babel/parser/TestToscaParser.java new file mode 100644 index 0000000..b1f2c01 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/parser/TestToscaParser.java @@ -0,0 +1,88 @@ +/** + * ============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.babel.parser; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import org.apache.commons.io.IOUtils; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.babel.csar.extractor.InvalidArchiveException; +import org.onap.aai.babel.csar.extractor.YamlExtractor; +import org.onap.aai.babel.xml.generator.api.AaiArtifactGenerator; +import org.onap.aai.babel.xml.generator.data.AdditionalParams; +import org.onap.aai.babel.xml.generator.data.Artifact; +import org.onap.aai.babel.xml.generator.data.GenerationData; +import org.onap.aai.babel.xml.generator.data.GeneratorConstants; +import org.onap.aai.babel.xml.generator.data.WidgetConfigurationUtil; + +/** + * Direct tests of the Model so as to improve code coverage + */ +public class TestToscaParser { + + static { + if (System.getProperty("AJSC_HOME") == null) { + System.setProperty("AJSC_HOME", "."); + } + } + + @Before + public void setup() throws FileNotFoundException, IOException { + URL url = TestToscaParser.class.getClassLoader().getResource("artifact-generator.properties"); + System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, url.getPath()); + + InputStream in = TestToscaParser.class.getClassLoader().getResourceAsStream("artifact-generator.properties"); + Properties properties = new Properties(); + properties.load(in); + in.close(); + WidgetConfigurationUtil.setConfig(properties); + } + + @Test + public void testParserWithCsarFile() throws IOException, InvalidArchiveException { + byte[] csar = loadResource("compressedArtifacts/catalog_csar.csar"); + List<Artifact> ymlFiles = YamlExtractor.extract(csar, "catalog_csar.csar", "1.0"); + + Map<String, String> additionalParams = new HashMap<>(); + additionalParams.put(AdditionalParams.SERVICE_VERSION.getName(), "1.0"); + + AaiArtifactGenerator generator = new AaiArtifactGenerator(); + GenerationData data = generator.generateArtifact(csar, ymlFiles, additionalParams); + + assertThat(data.getErrorData().size(), is(equalTo(0))); + assertThat(data.getResultData().size(), is(equalTo(2))); + } + + private byte[] loadResource(String resourceName) throws IOException { + return IOUtils.toByteArray(TestToscaParser.class.getClassLoader().getResource(resourceName)); + } +} diff --git a/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java b/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java index 5c1e213..c8080e9 100644 --- a/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java +++ b/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 European Software Marketing Ltd. + * 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. @@ -17,58 +17,61 @@ * 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 static org.junit.Assert.assertThat; + +import java.io.File; import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.Base64; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; -import org.custommonkey.xmlunit.XMLTestCase; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; 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; +import org.onap.aai.babel.xml.generator.data.GeneratorConstants; /** * Tests {@link CsarToXmlConverter} */ -@RunWith(PowerMockRunner.class) -@PrepareForTest(ModelGenerator.class) -public class CsarToXmlConverterTest extends XMLTestCase { +public class CsarToXmlConverterTest { - private static final String NAME = "the_name_of_the_csar_file.csar"; - private static final String VERSION = "v1"; + private static final String ARTIFACT_GENERATOR_CONFIG = "artifact-generator.properties"; + private static final String CSAR_FOLDER = "compressedArtifacts"; + private static final String VALID_CSAR_FILE = "service-SdWanServiceTest-csar.csar"; + private static final String INCORRECT_CSAR_NAME = "the_name_of_the_csar_file.csar"; + private static final String SERVICE_VERSION = "1.0"; private CsarToXmlConverter converter; + static { + if (System.getProperty("AJSC_HOME") == null) { + System.setProperty("AJSC_HOME", "."); + } + } + @Rule public ExpectedException exception = ExpectedException.none(); + private ArtifactTestUtils artifactTestUtils; @Before - public void setUp() { + public void setup() { + System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, + CsarToXmlConverterTest.class.getClassLoader().getResource(ARTIFACT_GENERATOR_CONFIG).getPath()); converter = new CsarToXmlConverter(); - URL url = CsarToXmlConverterTest.class.getClassLoader().getResource("artifact-generator.properties"); - System.setProperty("artifactgenerator.config", url.getPath()); + artifactTestUtils = new ArtifactTestUtils(); } @After @@ -83,25 +86,22 @@ public class CsarToXmlConverterTest extends XMLTestCase { @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); + converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), 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); + converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), INCORRECT_CSAR_NAME, null); } @Test(expected = CsarConverterException.class) public void generateXmlFromCsar_noPayloadExists() throws CsarConverterException { - converter.generateXmlFromCsar(new byte[0], NAME, VERSION); + converter.generateXmlFromCsar(new byte[0], INCORRECT_CSAR_NAME, SERVICE_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); + converter.generateXmlFromCsar(getCsar("noYmlFilesArchive.zip"), "noYmlFilesArchive.zip", SERVICE_VERSION); } @Test @@ -110,61 +110,55 @@ public class CsarToXmlConverterTest extends XMLTestCase { 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"); + System.clearProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE); + converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), VALID_CSAR_FILE, SERVICE_VERSION); } @Test public void generateXmlFromCsar() throws CsarConverterException, IOException, XmlArtifactGenerationException { - byte[] csarArchive = - new ArtifactTestUtils().loadResource("compressedArtifacts/service-SdWanServiceTest-csar.csar"); - Map<String, String> expectedXmlFiles = createExpectedXmlFiles(); List<BabelArtifact> generatedArtifacts = - converter.generateXmlFromCsar(csarArchive, VERSION, "service-SdWanServiceTest-csar.csar"); - - generatedArtifacts.forEach(ga -> { - try { + converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), VALID_CSAR_FILE, SERVICE_VERSION); - String x1 = expectedXmlFiles.get(ga.getName()); + generatedArtifacts + .forEach(ga -> assertThat("The content of " + ga.getName() + " must match the expected content", + ga.getPayload(), matches(expectedXmlFiles.get(ga.getName())))); + } - String x2 = bytesToString(ga.getPayload()); + public Matcher<String> matches(final String expected) { + return new BaseMatcher<String>() { + protected String theExpected = expected; - assertXMLEqual("The content of " + ga.getName() + " must match the expected content", x1, x2); + @Override + public boolean matches(Object o) { + return artifactTestUtils.compareXMLStrings((String) o, theExpected); + } - } catch (SAXException | IOException e) { - fail("There was an Exception parsing the XML: "+e.getMessage()); + @Override + public void describeTo(Description description) { + description.appendText(theExpected.toString()); } - }); + }; } - 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 byte[] getCsar(String csarFileName) throws IOException { + return artifactTestUtils.loadResource(CSAR_FOLDER + File.separator + csarFileName); } private Map<String, String> createExpectedXmlFiles() throws IOException { - Map<String, String> 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"}; + Map<String, String> xmlMap = new HashMap<>(); - for (String s : filesToLoad) { - xml.put(s, utils.loadResourceAsString("generatedXml/" + s)); + List<String> filesToLoad = new ArrayList<>(); + filesToLoad.add("AAI-SD-WAN-Service-Test-service-1.0.xml"); + filesToLoad.add("AAI-SdWanTestVsp..DUMMY..module-0-resource-2.xml"); + filesToLoad.add("AAI-Tunnel_XConnTest-resource-2.0.xml"); + filesToLoad.add("AAI-SD-WAN-Test-VSP-resource-1.0.xml"); + for (String filename : filesToLoad) { + xmlMap.put(filename, artifactTestUtils.loadResourceAsString("generatedXml" + File.separator + filename)); } - return xml; + return xmlMap; } } diff --git a/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java b/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java index 5d2309f..b1423b7 100644 --- a/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java +++ b/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 European Software Marketing Ltd. + * 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. @@ -17,8 +17,6 @@ * 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; @@ -26,60 +24,79 @@ import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.io.IOException; +import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; +import java.security.cert.X509Certificate; +import java.util.Collections; +import java.util.List; +import java.util.Map.Entry; import java.util.stream.Collectors; +import javax.inject.Inject; +import javax.security.auth.x500.X500Principal; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.aai.auth.AAIMicroServiceAuth; +import org.onap.aai.babel.xml.generator.data.GeneratorConstants; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Direct invocation of the generate artifacts service implementation * */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:/babel-beans.xml"}) public class TestGenerateArtifactsServiceImpl { - + + static { + if (System.getProperty("AJSC_HOME") == null) { + System.setProperty("AJSC_HOME", "."); + } + } + + @Inject + private AAIMicroServiceAuth auth; + @BeforeClass public static void setup() { URL url = TestGenerateArtifactsServiceImpl.class.getClassLoader().getResource("artifact-generator.properties"); - System.setProperty("artifactgenerator.config", url.getPath()); + System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, url.getPath()); } - + @Test - public void testGenerateArtifacts() throws Exception { - String jsonRequest = readstringFromFile("jsonFiles/success_request.json"); + public void testInvalidCsarFile() throws URISyntaxException, IOException { + String jsonRequest = readstringFromFile("jsonFiles/invalid_csar_request.json"); Response response = processJsonRequest(jsonRequest); - assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode())); - assertThat(response.getEntity(), is(readstringFromFile("response/response.json"))); + assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model.")); } - @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.")); + 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." )); + 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"); @@ -87,7 +104,7 @@ public class TestGenerateArtifactsServiceImpl { 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"); @@ -95,17 +112,59 @@ public class TestGenerateArtifactsServiceImpl { 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); + /** + * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API + * + * @param request for the Babel Service + * @return the Response from the HTTP API + * @throws URISyntaxException + */ + private Response processJsonRequest(String jsonRequest) throws URISyntaxException { + UriInfo mockUriInfo = Mockito.mock(UriInfo.class); + Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked) + Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing + Mockito.when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>()); + + // Create mocked request headers map + MultivaluedHashMap<String, String> headersMap = new MultivaluedHashMap<>(); + headersMap.put("X-TransactionId", createSingletonList("transaction-id")); + headersMap.put("X-FromAppId", createSingletonList("app-id")); + headersMap.put("Host", createSingletonList("hostname")); + + HttpHeaders headers = Mockito.mock(HttpHeaders.class); + for (Entry<String, List<String>> entry : headersMap.entrySet()) { + Mockito.when(headers.getRequestHeader(entry.getKey())).thenReturn(entry.getValue()); + } + Mockito.when(headers.getRequestHeaders()).thenReturn(headersMap); + + MockHttpServletRequest servletRequest = new MockHttpServletRequest(); + servletRequest.setSecure(true); + servletRequest.setScheme("https"); + servletRequest.setServerPort(9501); + servletRequest.setServerName("localhost"); + servletRequest.setRequestURI("/services/validation-service/v1/app/validate"); + + X509Certificate mockCertificate = Mockito.mock(X509Certificate.class); + Mockito.when(mockCertificate.getSubjectX500Principal()) + .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB")); + + servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] {mockCertificate}); + servletRequest.setAttribute("javax.servlet.request.cipher_suite", ""); + + GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth); + return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonRequest); + } + + private List<String> createSingletonList(String listItem) { + return Collections.<String>singletonList(listItem); } private String readstringFromFile(String resourceFile) throws IOException, URISyntaxException { - return Files.lines(Paths.get(ClassLoader.getSystemResource(resourceFile).toURI())) + return Files + .lines(Paths + .get(TestGenerateArtifactsServiceImpl.class.getClassLoader().getResource(resourceFile).toURI())) .collect(Collectors.joining()); } - - + } diff --git a/src/test/java/org/onap/aai/babel/service/TestInfoService.java b/src/test/java/org/onap/aai/babel/service/TestInfoService.java new file mode 100644 index 0000000..b97aa92 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/service/TestInfoService.java @@ -0,0 +1,69 @@ +/** + * ============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.babel.service; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.startsWith; +import static org.junit.Assert.assertThat; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import org.junit.Test; + +public class TestInfoService { + + @Test + public void testInitialisedInfoService() { + String info = new InfoService().getInfo(""); + assertThat(info, startsWith("Status: Up\n")); + assertThat(info, containsString("Started at")); + assertThat(info, containsString("total=1")); + } + + @Test + public void testStatusReport() { + InfoService infoService = new InfoService(); + LocalDateTime now = LocalDateTime.now(); + Clock clock = buildClock(now); + + String info = infoService.statusReport(clock); + assertThat(info, containsString("Started at")); + assertThat(info, containsString("total=1")); + + // Skip ahead 1 day + clock = buildClock(now.plusDays(1)); + info = infoService.statusReport(clock); + assertThat(info, containsString("Up time 1 day ")); + assertThat(info, containsString("total=2")); + + // Skip ahead 5 days + clock = buildClock(now.plusDays(5)); + info = infoService.statusReport(clock); + assertThat(info, containsString("Up time 5 days ")); + assertThat(info, containsString("total=3")); + } + + private Clock buildClock(LocalDateTime now) { + return Clock.fixed(now.toInstant(OffsetDateTime.now().getOffset()), Clock.systemDefaultZone().getZone()); + } + +} diff --git a/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java b/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java index 74f0c0e..5a4224c 100644 --- a/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java +++ b/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 European Software Marketing Ltd. + * 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. @@ -17,26 +17,23 @@ * 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.net.URL; +import java.nio.charset.Charset; 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; +import org.custommonkey.xmlunit.Diff; +import org.onap.aai.babel.xml.generator.data.Artifact; +import org.xml.sax.SAXException; /** * This class provides some utilities to assist with running tests. @@ -51,50 +48,60 @@ public class ArtifactTestUtils { try { return loadResourceAsString(s); } catch (IOException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } }).collect(Collectors.toSet()); - toscaFiles.forEach(ts -> { - boolean payloadFound = false; + compareXMLPayloads(toscaFiles, ymlPayloads); + } + + /** + * Compare 2 XML strings to see if they have the same content + * + * @param string1 + * @param string2 + * @return true if similar + */ + public boolean compareXMLStrings(String string1, String string2) { + boolean similar = false; + + try { + similar = new Diff(string1, string2).similar(); + } catch (SAXException | IOException e) { // NOSONAR + similar = true; + } + + return similar; + } + + public byte[] loadResource(String resourceName) throws IOException { + return IOUtils.toByteArray(getResource(resourceName)); + } - String s = bytesToString(ts.getPayload()); + public String loadResourceAsString(String resourceName) throws IOException { + return IOUtils.toString(getResource(resourceName)); + } + private void compareXMLPayloads(List<Artifact> toscaFiles, Set<String> ymlPayloads) { + for (Artifact artifact : toscaFiles) { + boolean payloadFound = false; for (String ymlPayload : ymlPayloads) { - String tscontent = ymlPayload; - if (s.endsWith(tscontent)) { + if (compareXMLStrings(convertToString(artifact.getPayload()), ymlPayload)) { 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)); + + artifact.getName() + ")", payloadFound, is(true)); + } } - 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; - + private URL getResource(String resourceName) { + return ArtifactTestUtils.class.getClassLoader().getResource(resourceName); } - 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 String convertToString(byte[] byteArray) { + return new String(Base64.getDecoder().decode(byteArray), Charset.defaultCharset()); } - } diff --git a/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java b/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java index 030c24d..bffe419 100644 --- a/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java +++ b/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 European Software Marketing Ltd. + * 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. @@ -17,8 +17,6 @@ * 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; @@ -28,45 +26,45 @@ 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{ + 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); - } - + RequestValidator.validateRequest(request); + } + + + @Test + public void testMissingArtifactVersionExceptionThrown() throws Exception { + exception.expect(RequestValidationException.class); + exception.expectMessage("No artifact version attribute found in the request body."); - @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); + RequestValidator.validateRequest(request); } - + @Test - public void testMissingCsarFile() throws Exception{ + 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); + RequestValidator.validateRequest(request); } } diff --git a/src/test/java/org/onap/aai/babel/xml/generator/model/TestVfModule.java b/src/test/java/org/onap/aai/babel/xml/generator/model/TestVfModule.java new file mode 100644 index 0000000..d02b817 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/xml/generator/model/TestVfModule.java @@ -0,0 +1,121 @@ +/** + * ============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.babel.xml.generator.model; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.babel.xml.generator.data.WidgetConfigurationUtil; +import org.onap.aai.babel.xml.generator.model.Widget.Type; + +/** + * Direct tests of the Model class VfModule so as to improve code coverage + */ +public class TestVfModule { + + static { + if (System.getProperty("AJSC_HOME") == null) { + System.setProperty("AJSC_HOME", "."); + } + } + + @Before + public void setup() throws FileNotFoundException, IOException { + InputStream in = TestVfModule.class.getClassLoader().getResourceAsStream("artifact-generator.properties"); + Properties properties = new Properties(); + properties.load(in); + in.close(); + WidgetConfigurationUtil.setConfig(properties); + } + + @Test + public void testCreateVfModule() { + VfModule vf = new VfModule(); + Map<String, String> modelIdentInfo = new HashMap<>(); + modelIdentInfo.put("UUID", "dummy_uuid"); + vf.populateModelIdentificationInformation(modelIdentInfo); + assertThat(vf.hashCode(), is(notNullValue())); + assertThat(vf.equals(vf), is(true)); + // Tests that the overridden equals() method correctly returns false for a different type of Object + // This is necessary to achieve complete code coverage + assertThat(vf.equals("string"), is(false)); // NOSONAR + } + + @Test + public void testNonMemberWidgetToVF() { + VfModule vf = new VfModule(); + Widget widget = Widget.getWidget(Type.SERVICE); + vf.setMembers(Collections.singletonList(widget.getId())); + vf.addWidget(widget); + } + + @Test + public void testAddServiceWidgetToVF() { + VfModule vf = new VfModule(); + addWidgetToModule(vf, Type.SERVICE); + } + + @Test + public void testAddVServerWidgetToVF() { + VfModule vf = new VfModule(); + addWidgetToModule(vf, Type.VSERVER); + } + + @Test + public void testAddLIntfWidgetToVF() { + VfModule vf = new VfModule(); + addWidgetToModule(vf, Type.LINT); + addWidgetToModule(vf, Type.VSERVER); + addWidgetToModule(vf, Type.LINT); + } + + @Test + public void testAddVolumeWidgetToVF() { + VfModule vf = new VfModule(); + addWidgetToModule(vf, Type.VOLUME); + addWidgetToModule(vf, Type.VSERVER); + addWidgetToModule(vf, Type.VOLUME); + } + + @Test + public void testAddOAMNetworkWidgetToVF() { + VfModule vf = new VfModule(); + addWidgetToModule(vf, Type.OAM_NETWORK); + } + + private void addWidgetToModule(VfModule vfModule, Type widgeType) { + Widget widget = Widget.getWidget(widgeType); + String id = widget.getId(); + widget.addKey(id); + vfModule.setMembers(Collections.singletonList(id)); + vfModule.addWidget(widget); + } +} diff --git a/src/test/java/org/onap/aai/babel/xml/generator/model/TestWidget.java b/src/test/java/org/onap/aai/babel/xml/generator/model/TestWidget.java new file mode 100644 index 0000000..e33de67 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/xml/generator/model/TestWidget.java @@ -0,0 +1,55 @@ +/** + * ============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.babel.xml.generator.model; + +import org.junit.Test; +import org.onap.aai.babel.xml.generator.model.Widget.Type; + +/** + * Direct tests of the Model so as to improve code coverage + */ +public class TestWidget { + + static { + if (System.getProperty("AJSC_HOME") == null) { + System.setProperty("AJSC_HOME", "."); + } + } + + @Test + public void testGetWidgets() { + Widget.getWidget(Type.VFC); + Widget.getWidget(Type.FLAVOR); + Widget.getWidget(Type.TENANT); + Widget.getWidget(Type.VOLUME_GROUP); + Widget.getWidget(Type.L3_NET); + Widget.getWidget(Type.IMAGE); + Widget.getWidget(Type.TUNNEL_XCONNECT); + } + + @Test + public void testMethods() { + new ServiceWidget().addWidget(new TenantWidget()); + new VolumeGroupWidget().getWidgetType(); + } + + +} |