diff options
author | mark.j.leonard <mark.j.leonard@gmail.com> | 2018-06-26 11:37:52 +0100 |
---|---|---|
committer | mark.j.leonard <mark.j.leonard@gmail.com> | 2018-06-26 12:12:05 +0100 |
commit | f3bf5dd360b93fd7ef6cc8d871a9903de9f27e5a (patch) | |
tree | f7837fb3d8fcb57e0366682118a492eab951760a /src/test/java | |
parent | d874753af8a4f5d8db615370c607cc938659eefe (diff) |
Fix remaining Sonar code smells
Code reformatting to address Sonar code smells, excluding the cyclomatic
complexity errors which will require some heavier refactoring.
Issue-ID: AAI-1242
Change-Id: I0f2502c8038b1e70f53f3b82b9d4d0761d9137cc
Signed-off-by: mark.j.leonard <mark.j.leonard@gmail.com>
Diffstat (limited to 'src/test/java')
14 files changed, 222 insertions, 183 deletions
diff --git a/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java b/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java index e6f5aa6..a8f1f92 100644 --- a/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java +++ b/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -116,8 +116,6 @@ public class MicroServiceAuthTest { assertThat(AAIMicroServiceAuthCore.authorize(VALID_ADMIN_USER, "WRONG:action"), is(false)); } - - @Test public void testValidateRequest() throws AAIAuthException { AAIMicroServiceAuth auth = createStandardAuth(); @@ -137,7 +135,6 @@ public class MicroServiceAuthTest { * @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); @@ -145,6 +142,7 @@ public class MicroServiceAuthTest { fileWriter.flush(); fileWriter.close(); + BabelAuthConfig babelAuthConfig = new BabelAuthConfig(); babelAuthConfig.setAuthPolicyFile(file.getAbsolutePath()); return new AAIMicroServiceAuth(babelAuthConfig); } @@ -190,8 +188,6 @@ public class MicroServiceAuthTest { 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); @@ -199,8 +195,9 @@ public class MicroServiceAuthTest { JSONArray rolesArray = new JSONArray(); rolesArray.put(role); - roles.put("roles", rolesArray); + JSONObject roles = new JSONObject(); + 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 index 77517ad..b53f38d 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 @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -27,13 +27,12 @@ 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.onap.aai.babel.xml.generator.data.Artifact; /** - * Tests @see YamlExtractor + * Tests {@link YamlExtractor}. */ public class YamlExtractorTest { @@ -44,90 +43,72 @@ public class YamlExtractorTest { private static final String SUPPLY_VERSION = "The version must be supplied for processing."; @Test - public void extract_nullContentSupplied() { + public void testNullContentSupplied() { 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() { + public void testEmptyContentSupplied() { invalidArgumentsTest(new byte[0], FOO, FOO, SUPPLY_AN_ARCHIVE); } @Test - public void extract_nullNameSupplied() { + public void testNullNameSupplied() { invalidArgumentsTest(SOME_BYTES.getBytes(), null, FOO, SUPPLY_NAME); } @Test - public void extract_blankNameSupplied() { + public void testBlankNameSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), " \t ", FOO, SUPPLY_NAME); } @Test - public void extract_emptyNameSupplied() { + public void testEmptyNameSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), "", FOO, SUPPLY_NAME); } @Test - public void extract_nullVersionSupplied() { + public void testNullVersionSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), FOO, null, SUPPLY_VERSION); } @Test - public void extract_blankVersionSupplied() { + public void testBlankVersionSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), FOO, " \t ", SUPPLY_VERSION); } @Test - public void extract_emptyVersionSupplied() { + public void testEmptyVersionSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), FOO, "", SUPPLY_VERSION); } @Test - public void extract_invalidContentSupplied() { + public void testInvalidContentSupplied() { 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 { + public void testArchiveContainsNoYmlFiles() throws IOException { try { - YamlExtractor.extract(loadResource("compressedArtifacts/noYmlFilesArchive.zip"), "noYmlFilesArchive.zip", - "v1"); + extractArchive("noYmlFilesArchive.zip"); 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.", + assertEquals("Incorrect message was returned", "No valid YAML 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_archiveContainsOnlyTheExpectedYmlFilesFromSdWanService() + public void testArchiveContainsOnlyTheExpectedYmlFilesFromSdWanService() throws IOException, InvalidArchiveException { - List<Artifact> ymlFiles = - YamlExtractor.extract(loadResource("compressedArtifacts/service-SdWanServiceTest-csar.csar"), - "service-SdWanServiceTest-csar.csar", "v1"); - + final List<Artifact> ymlFiles = extractArchive("service-SdWanServiceTest-csar.csar"); List<String> payloads = new ArrayList<>(); payloads.add("ymlFiles/resource-SdWanTestVsp-template.yml"); payloads.add("ymlFiles/resource-TunnelXconntest-template.yml"); @@ -137,5 +118,30 @@ public class YamlExtractorTest { new ArtifactTestUtils().performYmlAsserts(ymlFiles, payloads); } -} + /** + * @param archive + * @param name + * @param version + * @param expectedErrorMessage + */ + private void invalidArgumentsTest(byte[] archive, String name, String version, String expectedErrorMessage) { + try { + new 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()); + } + } + + /** + * @param resourceName + * @return + * @throws InvalidArchiveException + * @throws IOException + */ + private List<Artifact> extractArchive(String resourceName) throws InvalidArchiveException, IOException { + return new YamlExtractor().extract(new ArtifactTestUtils().getCompressedArtifact(resourceName), resourceName, "v1"); + } +} 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 96f1b2d..cb70677 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 @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -33,10 +33,14 @@ public class ArtifactInfoBuilder { * Builds an implementation of IArtifactInfo for test purposes. * <p/> * - * @param type type of artifact - * @param name name of artifact - * @param description description of artifact - * @param version version of artifact + * @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, @@ -61,8 +65,9 @@ public class ArtifactInfoBuilder { * where the elements of the second dimension are the arguments to {@link #build(String, String, String, String)}. * <p/> * - * @param artifactInfoBits a two dimensional array of data used to build the artifacts - * @return List<IArtifactInfo> a list of artifacts built from the given array of info + * @param artifactInfoBits + * a two dimensional array of data used to build the artifacts + * @return List<IArtifactInfo> a list of artifacts built from the given array of info */ static List<IArtifactInfo> buildArtifacts(final String[][] artifactInfoBits) { List<IArtifactInfo> artifacts = new ArrayList<>(); 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 f686911..6c0078d 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 @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -102,19 +102,18 @@ public class TestArtifactInfoImpl implements IArtifactInfo { @Override public boolean equals(Object obj) { + if (this == obj) { + return true; + } if (!(obj instanceof TestArtifactInfoImpl)) { return false; - } else if (obj == this) { - return true; } TestArtifactInfoImpl rhs = (TestArtifactInfoImpl) obj; - // @formatter:off - return new EqualsBuilder() - .append(artifactType, rhs.artifactType) - .append(artifactDescription, rhs.artifactDescription) - .append(artifactVersion, rhs.artifactVersion) - .isEquals(); - // @formatter:on + return new EqualsBuilder() // + .append(artifactType, rhs.artifactType) // + .append(artifactDescription, rhs.artifactDescription) // + .append(artifactVersion, rhs.artifactVersion) // + .isEquals(); } @Override diff --git a/src/test/java/org/onap/aai/babel/logging/LogReader.java b/src/test/java/org/onap/aai/babel/logging/LogReader.java index 0c4de64..77b8d60 100644 --- a/src/test/java/org/onap/aai/babel/logging/LogReader.java +++ b/src/test/java/org/onap/aai/babel/logging/LogReader.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -27,6 +27,7 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -67,7 +68,7 @@ public class LogReader { 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())); + .max(Comparator.comparingLong(f -> f.toFile().lastModified())); if (latestFilePath.isPresent()) { cachedLog = latestFilePath.get(); } else { diff --git a/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java b/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java index ed9dac4..0c350c2 100644 --- a/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java +++ b/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -61,7 +61,7 @@ public class TestApplicationLogger { Logger logger = LogHelper.INSTANCE; LogReader errorReader = new LogReader(LogHelper.getLogDirectory(), "error"); LogReader debugReader = new LogReader(LogHelper.getLogDirectory(), "debug"); - String[] args = {"1", "2", "3", "4"}; + String[] args = { "1", "2", "3", "4" }; for (ApplicationMsgs msg : Arrays.asList(ApplicationMsgs.values())) { if (msg.name().endsWith("ERROR")) { logger.error(msg, args); @@ -106,8 +106,8 @@ public class TestApplicationLogger { */ @Test public void logAuditMessage() throws IOException { - LogHelper logger = LogHelper.INSTANCE; - LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit"); + final LogHelper logger = LogHelper.INSTANCE; + final LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit"); HttpHeaders headers = Mockito.mock(HttpHeaders.class); Mockito.when(headers.getHeaderString("X-ECOMP-RequestID")).thenReturn("ecomp-request-id"); @@ -115,20 +115,20 @@ public class TestApplicationLogger { // 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")); + String str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat("audit message log level", str, containsString("INFO")); + assertThat("audit message content", str, 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")); + str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat("audit message log level", str, containsString("INFO")); + assertThat("audit message content", str, containsString("foo")); + assertThat("audit message content", str, containsString("ecomp-request-id")); + assertThat("audit message content", str, containsString("app-id")); } /** @@ -142,10 +142,10 @@ public class TestApplicationLogger { 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")); + String str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat("audit message log level", str, containsString("INFO")); + assertThat("audit message content", str, containsString("foo")); } /** @@ -158,10 +158,10 @@ public class TestApplicationLogger { 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")); + String str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat("metrics message log level", str, containsString("INFO")); + assertThat("metrics message content", str, containsString("fred")); } @Test @@ -212,7 +212,7 @@ public class TestApplicationLogger { private void callUnsupportedOperationMethod(TriConsumer<Enum<?>, LogFields, String[]> logMethod, ApplicationMsgs dummyMsg) { try { - logMethod.accept(dummyMsg, new LogFields(), new String[] {""}); + 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 @@ -228,8 +228,8 @@ public class TestApplicationLogger { * @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)); + String str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat(msg.toString() + " log level", str, 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 index 14fa9f3..d27396d 100644 --- a/src/test/java/org/onap/aai/babel/parser/TestToscaParser.java +++ b/src/test/java/org/onap/aai/babel/parser/TestToscaParser.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -27,16 +27,15 @@ 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.util.ArtifactTestUtils; 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; @@ -57,9 +56,8 @@ public class TestToscaParser { @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()); - + System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, + new ArtifactTestUtils().getResourcePath("artifact-generator.properties")); InputStream in = TestToscaParser.class.getClassLoader().getResourceAsStream("artifact-generator.properties"); Properties properties = new Properties(); properties.load(in); @@ -69,20 +67,18 @@ public class TestToscaParser { @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"); + String csarResourceName = "catalog_csar.csar"; + byte[] csarBytes = new ArtifactTestUtils().getCompressedArtifact(csarResourceName); + List<Artifact> ymlFiles = new YamlExtractor().extract(csarBytes, csarResourceName, "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); + GenerationData data = generator.generateArtifact(csarBytes, 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 9310d2d..0bc7c31 100644 --- a/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java +++ b/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -22,7 +22,6 @@ package org.onap.aai.babel.service; import static org.junit.Assert.assertThat; -import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -49,29 +48,45 @@ import org.onap.aai.babel.xml.generator.data.GeneratorConstants; public class CsarToXmlConverterTest { 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("APP_HOME") == null) { System.setProperty("APP_HOME", "."); } } + private enum CsarTest { + VALID_CSAR_FILE("service-SdWanServiceTest-csar.csar"), NO_YAML_FILES("noYmlFilesArchive.zip"); + + private String filename; + private ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils(); + + CsarTest(String filename) { + this.filename = filename; + } + + public String getName() { + return filename; + } + + public byte[] getContent() throws IOException { + return artifactTestUtils.getCompressedArtifact(filename); + } + } + + // The class to be tested. + private CsarToXmlConverter converter; + @Rule public ExpectedException exception = ExpectedException.none(); - private ArtifactTestUtils artifactTestUtils; @Before public void setup() { System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, - CsarToXmlConverterTest.class.getClassLoader().getResource(ARTIFACT_GENERATOR_CONFIG).getPath()); + new ArtifactTestUtils().getResourcePath(ARTIFACT_GENERATOR_CONFIG)); converter = new CsarToXmlConverter(); - artifactTestUtils = new ArtifactTestUtils(); } @After @@ -86,12 +101,12 @@ public class CsarToXmlConverterTest { @Test(expected = NullPointerException.class) public void generateXmlFromCsar_missingName() throws CsarConverterException, IOException { - converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), null, null); + converter.generateXmlFromCsar(CsarTest.VALID_CSAR_FILE.getContent(), null, null); } @Test(expected = NullPointerException.class) public void generateXmlFromCsar_missingVersion() throws CsarConverterException, IOException { - converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), INCORRECT_CSAR_NAME, null); + converter.generateXmlFromCsar(CsarTest.VALID_CSAR_FILE.getContent(), INCORRECT_CSAR_NAME, null); } @Test(expected = CsarConverterException.class) @@ -101,25 +116,26 @@ public class CsarToXmlConverterTest { @Test(expected = CsarConverterException.class) public void generateXmlFromCsar_csarFileHasNoYmlFiles() throws CsarConverterException, IOException { - converter.generateXmlFromCsar(getCsar("noYmlFilesArchive.zip"), "noYmlFilesArchive.zip", SERVICE_VERSION); + converter.generateXmlFromCsar(CsarTest.NO_YAML_FILES.getContent(), "noYmlFilesArchive.zip", SERVICE_VERSION); } @Test - public void generateXmlFromCsar_artifactgenerator_config_systemPropertyNotSet() + public void testArtifactGeneratorConfigMissing() throws IOException, XmlArtifactGenerationException, CsarConverterException { exception.expect(CsarConverterException.class); exception.expectMessage("Cannot generate artifacts. artifactgenerator.config system property not configured"); // Unset the required system property System.clearProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE); - converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), VALID_CSAR_FILE, SERVICE_VERSION); + converter.generateXmlFromCsar(CsarTest.VALID_CSAR_FILE.getContent(), CsarTest.VALID_CSAR_FILE.getName(), + SERVICE_VERSION); } @Test public void generateXmlFromCsar() throws CsarConverterException, IOException, XmlArtifactGenerationException { Map<String, String> expectedXmlFiles = createExpectedXmlFiles(); - List<BabelArtifact> generatedArtifacts = - converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), VALID_CSAR_FILE, SERVICE_VERSION); + List<BabelArtifact> generatedArtifacts = converter.generateXmlFromCsar(CsarTest.VALID_CSAR_FILE.getContent(), + CsarTest.VALID_CSAR_FILE.getName(), SERVICE_VERSION); generatedArtifacts .forEach(ga -> assertThat("The content of " + ga.getName() + " must match the expected content", @@ -131,8 +147,8 @@ public class CsarToXmlConverterTest { protected String theExpected = expected; @Override - public boolean matches(Object o) { - return artifactTestUtils.compareXMLStrings((String) o, theExpected); + public boolean matches(Object item) { + return new ArtifactTestUtils().compareXmlStrings((String) item, theExpected); } @Override @@ -142,10 +158,6 @@ public class CsarToXmlConverterTest { }; } - 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> xmlMap = new HashMap<>(); @@ -156,7 +168,7 @@ public class CsarToXmlConverterTest { filesToLoad.add("AAI-SD-WAN-Test-VSP-resource-1.0.xml"); for (String filename : filesToLoad) { - xmlMap.put(filename, artifactTestUtils.loadResourceAsString("generatedXml" + File.separator + filename)); + xmlMap.put(filename, new ArtifactTestUtils().loadResourceAsString("generatedXml/" + filename)); } 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 5840cd7..4cc8c8c 100644 --- a/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java +++ b/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -26,14 +26,10 @@ 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; @@ -45,6 +41,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.onap.aai.auth.AAIMicroServiceAuth; +import org.onap.aai.babel.util.ArtifactTestUtils; import org.onap.aai.babel.xml.generator.data.GeneratorConstants; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.ContextConfiguration; @@ -55,7 +52,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:/babel-beans.xml"}) +@ContextConfiguration(locations = { "classpath:/babel-beans.xml" }) public class TestGenerateArtifactsServiceImpl { static { @@ -70,58 +67,55 @@ public class TestGenerateArtifactsServiceImpl { @BeforeClass public static void setup() { - URL url = TestGenerateArtifactsServiceImpl.class.getClassLoader().getResource("artifact-generator.properties"); - System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, url.getPath()); + System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, + new ArtifactTestUtils().getResourcePath("artifact-generator.properties")); } @Test public void testInvalidCsarFile() throws URISyntaxException, IOException { - String jsonRequest = readstringFromFile("jsonFiles/invalid_csar_request.json"); - Response response = processJsonRequest(jsonRequest); + Response response = processJsonRequest("invalid_csar_request.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 testInvalidJsonFile() throws URISyntaxException, IOException { - String jsonRequest = readstringFromFile("jsonFiles/invalid_json_request.json"); - Response response = processJsonRequest(jsonRequest); + Response response = processJsonRequest("invalid_json_request.json"); 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); + Response response = processJsonRequest("missing_artifact_name_request.json"); 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); + Response response = processJsonRequest("missing_artifact_version_request.json"); 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); + Response response = processJsonRequest("missing_csar_request.json"); assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); assertThat(response.getEntity(), is("No csar attribute found in the request body.")); } /** * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API - * - * @param request for the Babel Service + * + * @param resource + * path to the incoming JSON request * @return the Response from the HTTP API * @throws URISyntaxException + * @throws IOException */ - private Response processJsonRequest(String jsonRequest) throws URISyntaxException { + private Response processJsonRequest(String resource) throws URISyntaxException, IOException { 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 @@ -150,22 +144,24 @@ public class TestGenerateArtifactsServiceImpl { 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.X509Certificate", new X509Certificate[] { mockCertificate }); servletRequest.setAttribute("javax.servlet.request.cipher_suite", ""); GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth); - return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonRequest); + String jsonString = getRequestJson(resource); + return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString); } - private List<String> createSingletonList(String listItem) { - return Collections.<String>singletonList(listItem); + private String getRequestJson(String resource) throws IOException, URISyntaxException { + return new ArtifactTestUtils().getRequestJson(resource); + } + + private String getResponseJson(String jsonResponse) throws IOException, URISyntaxException { + return new ArtifactTestUtils().getResponseJson(jsonResponse); } - private String readstringFromFile(String resourceFile) throws IOException, URISyntaxException { - return Files - .lines(Paths - .get(TestGenerateArtifactsServiceImpl.class.getClassLoader().getResource(resourceFile).toURI())) - .collect(Collectors.joining()); + private List<String> createSingletonList(String listItem) { + return Collections.<String>singletonList(listItem); } } diff --git a/src/test/java/org/onap/aai/babel/service/TestInfoService.java b/src/test/java/org/onap/aai/babel/service/TestInfoService.java index 1d60839..b97aa92 100644 --- a/src/test/java/org/onap/aai/babel/service/TestInfoService.java +++ b/src/test/java/org/onap/aai/babel/service/TestInfoService.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. diff --git a/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java b/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java index 69d7819..cf96d24 100644 --- a/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java +++ b/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -24,11 +24,15 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.io.IOException; +import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.Base64; import java.util.List; import java.util.Set; +import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.custommonkey.xmlunit.Diff; @@ -40,19 +44,23 @@ import org.xml.sax.SAXException; */ public class ArtifactTestUtils { + private static final String JSON_REQUESTS_FOLDER = "jsonFiles/"; + private static final String JSON_RESPONSES_FOLDER = "response/"; + private static final String CSAR_INPUTS_FOLDER = "compressedArtifacts/"; + public void performYmlAsserts(List<Artifact> toscaFiles, List<String> ymlPayloadsToLoad) { - assertThat("An unexpected number of yml files have been extracted", toscaFiles.size(), + assertThat("An unexpected number of YAML files have been extracted", toscaFiles.size(), is(ymlPayloadsToLoad.size())); - Set<String> ymlPayloads = ymlPayloadsToLoad.stream().map(s -> { + Function<? super String, ? extends String> loadResource = s -> { try { return loadResourceAsString(s); } catch (IOException e) { throw new RuntimeException(e); } - }).collect(Collectors.toSet()); - - compareXMLPayloads(toscaFiles, ymlPayloads); + }; + Set<String> ymlPayloads = ymlPayloadsToLoad.stream().map(loadResource).collect(Collectors.toSet()); + compareXmlPayloads(toscaFiles, ymlPayloads); } /** @@ -62,7 +70,7 @@ public class ArtifactTestUtils { * @param string2 * @return true if similar */ - public boolean compareXMLStrings(String string1, String string2) { + public boolean compareXmlStrings(String string1, String string2) { boolean similar = false; try { @@ -74,7 +82,11 @@ public class ArtifactTestUtils { return similar; } - public byte[] loadResource(String resourceName) throws IOException { + public byte[] getCompressedArtifact(String resourceName) throws IOException { + return loadResourceBytes(CSAR_INPUTS_FOLDER + resourceName); + } + + public byte[] loadResourceBytes(String resourceName) throws IOException { return IOUtils.toByteArray(getResource(resourceName)); } @@ -82,26 +94,43 @@ public class ArtifactTestUtils { return IOUtils.toString(getResource(resourceName), Charset.defaultCharset()); } - private void compareXMLPayloads(List<Artifact> toscaFiles, Set<String> ymlPayloads) { + public String getRequestJson(String resource) throws IOException { + return loadResourceAsString(JSON_REQUESTS_FOLDER + resource); + } + + public String getResponseJson(String jsonResponse) throws IOException, URISyntaxException { + return readstringFromFile(JSON_RESPONSES_FOLDER + jsonResponse); + } + + public String readstringFromFile(String resourceFile) throws IOException, URISyntaxException { + return Files.lines(Paths.get(getResource(resourceFile).toURI())).collect(Collectors.joining()); + } + + public String getResourcePath(String resourceName) { + return getResource(resourceName).getPath(); + } + + private URL getResource(String resourceName) { + return ArtifactTestUtils.class.getClassLoader().getResource(resourceName); + } + + private void compareXmlPayloads(List<Artifact> toscaFiles, Set<String> ymlPayloads) { for (Artifact artifact : toscaFiles) { boolean payloadFound = false; for (String ymlPayload : ymlPayloads) { - if (compareXMLStrings(convertToString(artifact.getPayload()), ymlPayload)) { + 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 (" + assertThat("The content of each YAML file must match the actual content of the file extracted (" + artifact.getName() + ")", payloadFound, is(true)); } } - private URL getResource(String resourceName) { - return ArtifactTestUtils.class.getClassLoader().getResource(resourceName); - } - 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 aff27cc..db7d882 100644 --- a/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java +++ b/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -39,10 +39,9 @@ public class TestRequestValidator { request.setCsar("UEsDBBQACAgIAGsrz0oAAAAAAAAAAAAAAAAJAAAAY3Nhci5tZXRhC3Z"); request.setArtifactVersion("1.0"); request.setArtifactName(null); - RequestValidator.validateRequest(request); + new RequestValidator().validateRequest(request); } - @Test public void testMissingArtifactVersionExceptionThrown() throws Exception { exception.expect(RequestValidationException.class); @@ -52,7 +51,7 @@ public class TestRequestValidator { request.setCsar("UEsDBBQACAgIAGsrz0oAAAAAAAAAAAAAAAAJAAAAY3Nhci5tZXRhC3Z"); request.setArtifactVersion(null); request.setArtifactName("hello"); - RequestValidator.validateRequest(request); + new RequestValidator().validateRequest(request); } @Test @@ -64,7 +63,7 @@ public class TestRequestValidator { request.setCsar(null); request.setArtifactVersion("1.0"); request.setArtifactName("hello"); - RequestValidator.validateRequest(request); + new 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 index b4ce96d..5572fe2 100644 --- 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 @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -70,7 +70,7 @@ public class TestVfModule { } @Test - public void testNonMemberWidgetToVF() { + public void testNonMemberWidgetToVf() { VfModule vf = new VfModule(); Widget widget = Widget.getWidget(Type.SERVICE); vf.setMembers(Collections.singletonList(widget.getId())); @@ -78,19 +78,19 @@ public class TestVfModule { } @Test - public void testAddServiceWidgetToVF() { + public void testAddServiceWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.SERVICE); } @Test - public void testAddVServerWidgetToVF() { + public void testAddVServerWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.VSERVER); } @Test - public void testAddLIntfWidgetToVF() { + public void testAddLIntfWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.LINT); addWidgetToModule(vf, Type.VSERVER); @@ -98,7 +98,7 @@ public class TestVfModule { } @Test - public void testAddVolumeWidgetToVF() { + public void testAddVolumeWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.VOLUME); addWidgetToModule(vf, Type.VSERVER); @@ -106,7 +106,7 @@ public class TestVfModule { } @Test - public void testAddOAMNetworkWidgetToVF() { + public void testAddOamNetworkWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.OAM_NETWORK); } 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 index 6f2dcca..1865968 100644 --- 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 @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -51,5 +51,4 @@ public class TestWidget { new VolumeGroupWidget().getWidgetType(); } - } |