Improved test for ReportManger, ArtifactValidationUtils and Sonar fixes. 17/90817/7
authork.kedron <k.kedron@partner.samsung.com>
Wed, 3 Jul 2019 06:27:48 +0000 (08:27 +0200)
committerOfir Sonsino <ofir.sonsino@intl.att.com>
Mon, 22 Jul 2019 12:12:22 +0000 (12:12 +0000)
Add new ReportManagerHelper to read files with reports.
Fixed log.info to print the types of exception in the messages.
Removed redundant new lines in the report files.

Issue-ID: SDC-2327
Signed-off-by: Krystian Kedron <k.kedron@partner.samsung.com>
Change-Id: If0135f01a05b0936dad681d16e846a6c6560cc80

asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManager.java
asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactValidationUtilsTest.java
asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManagerHelper.java [new file with mode: 0644]
asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManagerTest.java

index 64e3ba0..2be8f92 100644 (file)
@@ -3,13 +3,14 @@
  * SDC
  * ================================================================================
  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
  * 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.
 
 package org.openecomp.sdc.asdctool.impl.validator.utils;
 
-import org.apache.commons.lang.text.StrBuilder;
-import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
-import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
-
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.nio.file.StandardOpenOption;
 import java.util.*;
+
+import org.apache.commons.lang.text.StrBuilder;
+import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -48,7 +50,7 @@ public class ReportManager {
             initCsvFile();
             initReportFile();
         } catch (IOException e) {
-            log.info("Init file failed - {}" , e);
+            log.info("Init file failed - {}", e.getClass().getSimpleName(), e);
         }
     }
 
@@ -62,7 +64,7 @@ public class ReportManager {
     private void initCsvFile() throws IOException {
         csvReportFilePath = ValidationConfigManager.getCsvReportFilePath();
         StrBuilder sb = new StrBuilder();
-        sb.append("Vertex ID,"+"Task Name,"+"Success,"+"Result Details"+","+"Result Description");
+        sb.append("Vertex ID,Task Name,Success,Result Details,Result Description");
         sb.appendNewLine();
         Files.write(Paths.get(csvReportFilePath), sb.toString().getBytes());
     }
@@ -87,9 +89,7 @@ public class ReportManager {
         String successStatus = success ? "success" : "failed";
         String line = "-----------------------Vertex: "+vertexScanned.getUniqueId()+", Task " + taskName + " " +successStatus+"-----------------------";
         StrBuilder sb = new StrBuilder();
-        writeReportLineToFile(sb.appendNewLine().toString());
         sb.appendln(line);
-        sb.appendNewLine();
         writeReportLineToFile(line);
     }
 
@@ -98,13 +98,12 @@ public class ReportManager {
             Files.write(Paths.get(reportOutputFilePath), new StrBuilder().appendNewLine().toString().getBytes(), StandardOpenOption.APPEND);
             Files.write(Paths.get(reportOutputFilePath), message.getBytes(), StandardOpenOption.APPEND);
         } catch (IOException e) {
-            log.info("write to file failed - {}" , e);
+            log.info("write to file failed - {}", e.getClass().getSimpleName(), e);
         }
     }
 
     public static void reportValidatorTypeSummary(String validatorName, Set<String> failedTasksNames, Set<String> successTasksNames){
         StrBuilder sb = new StrBuilder();
-        sb.appendNewLine().appendNewLine();
         sb.appendln("-----------------------ValidatorExecuter " + validatorName + " Validation Summary-----------------------");
         sb.appendln("Failed tasks: "+ failedTasksNames);
         sb.appendln("Success tasks: "+ successTasksNames);
@@ -113,21 +112,18 @@ public class ReportManager {
 
     public static void reportStartValidatorRun(String validatorName, int componenentsNum) {
         StrBuilder sb = new StrBuilder();
-        sb.appendNewLine().appendNewLine();
         sb.appendln("------ValidatorExecuter " + validatorName + " Validation Started, on "+componenentsNum+" components---------");
         writeReportLineToFile(sb.toString());
     }
 
     public static void reportStartTaskRun(GraphVertex vertex, String taskName){
         StrBuilder sb = new StrBuilder();
-        sb.appendNewLine().appendNewLine();
         sb.appendln("-----------------------Vertex: "+vertex.getUniqueId()+", Task " + taskName + " Started-----------------------");
         writeReportLineToFile(sb.toString());
     }
 
     public static void reportEndOfToolRun() {
         StrBuilder sb = new StrBuilder();
-        sb.appendNewLine().appendNewLine();
         sb.appendln("-----------------------------------Validator Tool Summary-----------------------------------");
         failedVerticesPerTask.forEach((taskName, failedVertices) -> {
             sb.append("Task: " + taskName);
@@ -140,16 +136,17 @@ public class ReportManager {
     }
 
     public static void printAllResults() {
-        resultsPerVertex.forEach((vertex, tasksResults)->{
-            tasksResults.forEach((task, result) -> {
-                try {
-                    String resultLine = vertex +","+task+","+result.getStatus()+","+result.getResult();
-                    Files.write(Paths.get(csvReportFilePath), resultLine.getBytes(), StandardOpenOption.APPEND);
-                    Files.write(Paths.get(csvReportFilePath), new StrBuilder().appendNewLine().toString().getBytes(), StandardOpenOption.APPEND);
-                } catch (IOException e) {
-                    log.info("write to file failed - {}" , e);
-                }
-            });
-        });
+        resultsPerVertex.forEach((vertex, tasksResults) -> tasksResults.forEach((task, result) -> {
+            try {
+                String resultLine = vertex + "," + task + "," + result.getStatus() + "," + result.getResult();
+                Files.write(Paths.get(csvReportFilePath), resultLine.getBytes(),
+                    StandardOpenOption.APPEND);
+                Files.write(Paths.get(csvReportFilePath),
+                    new StrBuilder().appendNewLine().toString().getBytes(),
+                    StandardOpenOption.APPEND);
+            } catch (IOException e) {
+                log.info("write to file failed - {}", e.getClass().getSimpleName(), e);
+            }
+        }));
     }
 }
index 2dca89f..50e5f87 100644 (file)
@@ -35,7 +35,9 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.stream.IntStream;
 
+import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
@@ -46,6 +48,7 @@ import org.mockito.Mock;
 import org.mockito.junit.MockitoJUnitRunner;
 import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
 import org.openecomp.sdc.asdctool.impl.validator.utils.ReportManager;
+import org.openecomp.sdc.asdctool.impl.validator.utils.ReportManagerHelper;
 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
 
@@ -114,6 +117,11 @@ public class ArtifactValidationUtilsTest {
         when(vertex.getUniqueId()).thenReturn(UNIQUE_ID_VERTEX);
     }
 
+    @After
+    public void clean() {
+        ReportManagerHelper.cleanReports();
+    }
+
     @Test
     public void testValidateArtifactsAreInCassandra() {
         // given
@@ -124,9 +132,12 @@ public class ArtifactValidationUtilsTest {
         ArtifactsVertexResult result =
             testSubject.validateArtifactsAreInCassandra(vertex, TASK_NAME, artifacts);
 
+        List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
+
         // then
         assertTrue(result.getStatus());
         assertEquals(0, result.notFoundArtifacts.size());
+        assertEquals("Artifact " + ES_ID + " is in Cassandra", reportOutputFile.get(2));
     }
 
     @Test
@@ -139,11 +150,20 @@ public class ArtifactValidationUtilsTest {
         // when
         ArtifactsVertexResult result =
             testSubject.validateArtifactsAreInCassandra(vertex, TASK_NAME, artifacts);
+        ReportManager.reportEndOfToolRun();
+
+        List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
 
         // then
         assertFalse(result.getStatus());
         assertEquals(1, result.notFoundArtifacts.size());
         assertEquals(UNIQUE_ID, result.notFoundArtifacts.iterator().next());
+
+        assertEquals("Artifact " + ES_ID + " is in Cassandra", reportOutputFile.get(2));
+        assertEquals("Artifact " + ES_ID_NOT_IN_CASS + " doesn't exist in Cassandra",
+            reportOutputFile.get(3));
+        assertEquals("Task: " + TASK_NAME, reportOutputFile.get(5));
+        assertEquals("FailedVertices: [" + UNIQUE_ID_VERTEX + "]", reportOutputFile.get(6));
     }
 
     @Test
@@ -208,9 +228,14 @@ public class ArtifactValidationUtilsTest {
         ArtifactsVertexResult result =
             testSubject.validateTopologyTemplateArtifacts(vertex, TASK_NAME);
 
+        List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
+
         // then
-               assertTrue(result.getStatus());
-               assertEquals(0, result.notFoundArtifacts.size());
+        assertTrue(result.getStatus());
+        assertEquals(0, result.notFoundArtifacts.size());
+
+        IntStream.range(2, reportOutputFile.size()).forEach(
+            i -> assertEquals("Artifact " + ES_ID + " is in Cassandra", reportOutputFile.get(i)));
     }
 
     @Test
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManagerHelper.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManagerHelper.java
new file mode 100644 (file)
index 0000000..9bcffbb
--- /dev/null
@@ -0,0 +1,65 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.asdctool.impl.validator.utils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
+
+public class ReportManagerHelper {
+
+    private ReportManagerHelper() {
+    }
+
+    public static List<String> getReportOutputFileAsList() {
+        return readFileAsList(ValidationConfigManager.getOutputFullFilePath());
+    }
+
+    public static List<String> getReportCsvFileAsList() {
+        return readFileAsList(ValidationConfigManager.getCsvReportFilePath());
+    }
+
+    public static void cleanReports() {
+        cleanFile(ValidationConfigManager.getCsvReportFilePath());
+        cleanFile(ValidationConfigManager.getOutputFullFilePath());
+    }
+
+    private static List<String> readFileAsList(String filePath) {
+        try (BufferedReader br = Files.newBufferedReader(Paths.get(filePath))) {
+            return br.lines().collect(Collectors.toList());
+        } catch (IOException e) {
+            return null;
+        }
+    }
+
+    private static void cleanFile(String filePath) {
+        try {
+            Files.delete(Paths.get(filePath));
+        } catch (IOException ignored) {
+
+        }
+    }
+}
index 1da3d6d..c3cc306 100644 (file)
@@ -3,13 +3,14 @@
  * SDC
  * ================================================================================
  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
  * 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.
 
 package org.openecomp.sdc.asdctool.impl.validator.utils;
 
-import java.util.Set;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.when;
 
+import java.io.File;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import org.junit.After;
+import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
 import org.powermock.core.classloader.annotations.PrepareForTest;
 import org.powermock.modules.junit4.PowerMockRunner;
+import org.powermock.modules.junit4.PowerMockRunnerDelegate;
 
 @RunWith(PowerMockRunner.class)
+@PowerMockRunnerDelegate(MockitoJUnitRunner.class)
 @PrepareForTest({ReportManager.class})
 public class ReportManagerTest {
 
-       @Test
-       public void testReportTaskEnd() throws Exception {
-               String vertexId = "";
-               String taskName = "";
-               VertexResult result = null;
-
-               // default test
-               ReportManager.reportTaskEnd(vertexId, taskName, result);
-       }
+    private static final String VERTEX_1_ID = "testID1";
+    private static final String TASK_1_FAILED_NAME = "testFailedTask1";
+    private static final String TASK_1_NAME = "testTask1";
+    private static final String VERTEX_2_ID = "testID2";
+    private static final String TASK_2_NAME = "testTask2";
+    private static final String TASK_2_FAILED_NAME = "testFailedTask2";
+    private static final String UNIQUE_ID = "uniqueID";
+    private static final String DUMMY_MESSAGE = "dummyMessage";
+    private static final String VALIDATOR_NAME = "testValidatorNamed";
+    private static final int COMPONENT_SUM = 0;
+
+    private static final String EXPECTED_CSV_HEADER =
+        "Vertex ID,Task Name,Success,Result Details,Result Description";
+    private static final String EXPECTED_OUTPUT_FILE_HEADER =
+        "-----------------------Validation Tool Results:-------------------------";
+    private static final String EXPECTED_OUTPUT_FILE_SUMMARY =
+        "-----------------------------------Validator Tool Summary-----------------------------------";
+
+    private final SortedSet<String> failedTasksNames =
+        new TreeSet<>(Arrays.asList(TASK_1_FAILED_NAME, TASK_2_FAILED_NAME));
+    private final SortedSet<String> successTasksNames =
+        new TreeSet<>(Arrays.asList(TASK_1_NAME, TASK_2_NAME));
+
+    private VertexResult successResult = new VertexResult();
+
+    @Mock
+    GraphVertex vertexScanned;
+
+       @Before
+    public void setup() {
+        String resourcePath = new File(Objects
+            .requireNonNull(ReportManagerTest.class.getClassLoader().getResource("")).getFile())
+                .getAbsolutePath();
+        ValidationConfigManager.setOutputFullFilePath(resourcePath);
+        ValidationConfigManager.setCsvReportFilePath(resourcePath);
+        new ReportManager();
+
+        successResult.setStatus(true);
+    }
+
+    @After
+    public void clean() {
+        ReportManagerHelper.cleanReports();
+    }
+
+    @Test
+    public void testReportTaskEnd() {
+        // when
+        ReportManager.reportTaskEnd(VERTEX_1_ID, TASK_1_NAME, successResult);
+        ReportManager.reportTaskEnd(VERTEX_2_ID, TASK_2_NAME, successResult);
+        ReportManager.printAllResults();
+
+        List reportCsvFile = ReportManagerHelper.getReportCsvFileAsList();
+
+        // then
+        assertNotNull(reportCsvFile);
+        assertEquals(EXPECTED_CSV_HEADER, reportCsvFile.get(0));
+        assertEquals(getCsvExpectedResult(VERTEX_1_ID, TASK_1_NAME), reportCsvFile.get(1));
+        assertEquals(getCsvExpectedResult(VERTEX_2_ID, TASK_2_NAME), reportCsvFile.get(2));
+    }
+
+    @Test
+    public void testAddFailedVertex() {
+        // when
+        ReportManager.addFailedVertex(TASK_1_NAME, VERTEX_1_ID);
+        ReportManager.reportEndOfToolRun();
+
+        List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
+
+        // then
+        assertNotNull(reportOutputFile);
+
+        assertEquals(EXPECTED_OUTPUT_FILE_HEADER, reportOutputFile.get(0));
+        assertEquals(EXPECTED_OUTPUT_FILE_SUMMARY, reportOutputFile.get(2));
+        assertEquals("Task: " + TASK_1_NAME, reportOutputFile.get(3));
+        assertEquals("FailedVertices: [" + VERTEX_1_ID + "]", reportOutputFile.get(4));
+    }
+
+    @Test
+    public void testPrintValidationTaskStatus() {
+        // given
+        when(vertexScanned.getUniqueId()).thenReturn(UNIQUE_ID);
+
+        // when
+        ReportManager.printValidationTaskStatus(vertexScanned, TASK_1_NAME, false);
+
+        List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
+
+        // then
+        assertNotNull(reportOutputFile);
+
+        assertEquals(EXPECTED_OUTPUT_FILE_HEADER, reportOutputFile.get(0));
+        assertEquals("-----------------------Vertex: " + UNIQUE_ID + ", Task " + TASK_1_NAME
+            + " failed-----------------------", reportOutputFile.get(2));
+    }
+
+    @Test
+    public void testWriteReportLineToFile() {
+        // when
+        ReportManager.writeReportLineToFile(DUMMY_MESSAGE);
+
+        List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
+
+        // then
+        assertNotNull(reportOutputFile);
+
+        assertEquals(EXPECTED_OUTPUT_FILE_HEADER, reportOutputFile.get(0));
+        assertEquals(DUMMY_MESSAGE, reportOutputFile.get(2));
+    }
+
+    @Test
+    public void testReportValidatorTypeSummary() {
+        // when
+        ReportManager.reportValidatorTypeSummary(VALIDATOR_NAME, failedTasksNames, successTasksNames);
+
+        List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
+
+        // then
+        assertNotNull(reportOutputFile);
+        assertEquals(EXPECTED_OUTPUT_FILE_HEADER, reportOutputFile.get(0));
+
+        assertEquals("-----------------------ValidatorExecuter " + VALIDATOR_NAME
+            + " Validation Summary-----------------------", reportOutputFile.get(2));
+        assertEquals("Failed tasks: [" + TASK_1_FAILED_NAME + ", " + TASK_2_FAILED_NAME + "]",
+            reportOutputFile.get(3));
+        assertEquals("Success tasks: [" + TASK_1_NAME + ", " + TASK_2_NAME + "]",
+            reportOutputFile.get(4));
+    }
 
        @Test
-       public void testAddFailedVertex() throws Exception {
-               String taskName = "";
-               String vertexId = "";
-
-               // default test
-               ReportManager.addFailedVertex(taskName, vertexId);
-       }
+       public void testReportStartValidatorRun() {
+               // when
+               ReportManager.reportStartValidatorRun(VALIDATOR_NAME, COMPONENT_SUM);
 
-       @Test(expected = NullPointerException.class)
-       public void testPrintValidationTaskStatus() throws Exception {
-               GraphVertex vertexScanned = null;
-               String taskName = "";
-               boolean success = false;
+               List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
 
-               // default test
-               ReportManager.printValidationTaskStatus(vertexScanned, taskName, success);
+               // then
+        assertNotNull(reportOutputFile);
+        assertEquals(EXPECTED_OUTPUT_FILE_HEADER, reportOutputFile.get(0));
+        assertEquals("------ValidatorExecuter " + VALIDATOR_NAME + " Validation Started, on "
+            + COMPONENT_SUM + " components---------", reportOutputFile.get(2));
        }
 
-       @Test(expected = NullPointerException.class)
-       public void testWriteReportLineToFile() throws Exception {
-               String message = "";
+    @Test
+    public void testReportStartTaskRun() {
+        // given
+        when(vertexScanned.getUniqueId()).thenReturn(UNIQUE_ID);
 
-               // default test
-               ReportManager.writeReportLineToFile(message);
-       }
+        // when
+        ReportManager.reportStartTaskRun(vertexScanned, TASK_1_NAME);
 
-       @Test(expected = NullPointerException.class)
-       public void testReportValidatorTypeSummary() throws Exception {
-               String validatorName = "";
-               Set<String> failedTasksNames = null;
-               Set<String> successTasksNames = null;
+        List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
 
-               // default test
-               ReportManager.reportValidatorTypeSummary(validatorName, failedTasksNames, successTasksNames);
-       }
+        // then
+        assertNotNull(reportOutputFile);
+        assertEquals(EXPECTED_OUTPUT_FILE_HEADER, reportOutputFile.get(0));
+        assertEquals("-----------------------Vertex: " + UNIQUE_ID + ", Task " + TASK_1_NAME
+                + " Started-----------------------", reportOutputFile.get(2));
+    }
 
-       @Test(expected = NullPointerException.class)
-       public void testReportStartValidatorRun() throws Exception {
-               String validatorName = "";
-               int componenentsNum = 0;
-
-               // default test
-               ReportManager.reportStartValidatorRun(validatorName, componenentsNum);
-       }
-
-       @Test(expected = NullPointerException.class)
-       public void testReportStartTaskRun() throws Exception {
-               GraphVertex vertex = null;
-               String taskName = "";
-
-               // default test
-               ReportManager.reportStartTaskRun(vertex, taskName);
-       }
-
-       @Test(expected = NullPointerException.class)
-       public void testReportEndOfToolRun() throws Exception {
-
-               // default test
-               ReportManager.reportEndOfToolRun();
-       }
-
-       @Test(expected = NullPointerException.class)
-       public void testPrintAllResults() throws Exception {
-
-               // default test
-               ReportManager.printAllResults();
-       }
-}
+    private String getCsvExpectedResult(String vertexID, String taskID) {
+        return String.join(",", new String[] {vertexID, taskID,
+            String.valueOf(successResult.getStatus()), successResult.getResult()});
+    }
+}
\ No newline at end of file