Remove csvReportFilePath from ValidationConfigManager 00/106300/6
authorFrancis Toth <francis.toth@yoppworks.com>
Mon, 20 Apr 2020 00:16:33 +0000 (20:16 -0400)
committerOfir Sonsino <ofir.sonsino@intl.att.com>
Tue, 28 Apr 2020 08:21:37 +0000 (08:21 +0000)
This commit aims to extract the csvReportFilePath field from ValidationConfigManager in order to improve testability. This commit contains multiple minor modifications resulting from bubbling up the csvReportFilePath static field to where it is actually set. Put differently, most of the modifications result from changing the signature of the functions which formerly relied on ValidationConfigManager.getCSVReportFilePath.

Change-Id: I82c3b0fca8a0f407319e40ecfff45e89ec1d4323
Signed-off-by: Francis Toth <francis.toth@yoppworks.com>
Issue-ID: SDC-2499

asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationConfigManager.java
asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java
asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManager.java
asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactValidatorTool.java
asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ValidationTool.java
asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationConfigManagerTest.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
asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManagerTest.java

index ea0bbf3..3c09a54 100644 (file)
 
 package org.openecomp.sdc.asdctool.impl.validator.config;
 
+import java.util.function.Supplier;
+
 public class ValidationConfigManager {
 
+    private static final String CSV_FILE_PREFIX = "/csvSummary_";
+    private static final String CSV_EXT = ".csv";
+    public static final String DEFAULT_CSV_PATH = "summary.csv";
+
     private static String outputFullFilePath;
     private static String outputFilePath;
 
     private ValidationConfigManager() {
     }
 
+    public static String csvReportFilePath(String outputPath, Supplier<Long> getTime) {
+        return outputPath + CSV_FILE_PREFIX + getTime.get() + CSV_EXT;
+    }
+
     public static String getOutputFullFilePath() {
         return outputFullFilePath;
     }
@@ -44,15 +54,4 @@ public class ValidationConfigManager {
         ValidationConfigManager.outputFilePath = outputPath;
         ValidationConfigManager.outputFullFilePath = outputPath + "/reportOutput.txt";
     }
-
-    public static String getCsvReportFilePath() {
-        return csvReportFilePath;
-    }
-
-    public static void setCsvReportFilePath(String outputPath) {
-        ValidationConfigManager.csvReportFilePath =
-            outputPath + "/csvSummary_" + System.currentTimeMillis() + ".csv";
-    }
-
-    private static String csvReportFilePath = "summary.csv";
 }
index b83417c..7afb4ed 100644 (file)
@@ -131,9 +131,6 @@ public class ValidationToolConfiguration {
         return new VfValidatorExecuter(tasks, janusGraphDao);
     }
 
-    @Bean
-    public ReportManager reportManager() { return new ReportManager();}
-
     @Bean(name = "artifact-cassandra-dao")
     public ArtifactCassandraDao artifactCassandraDao(CassandraClient cassandraClient) {
         return new ArtifactCassandraDao(cassandraClient);
index e575ffc..feef9ea 100644 (file)
@@ -37,23 +37,22 @@ import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 
-/**
- * Created by chaya on 7/5/2017.
- */
 public class ReportManager {
 
     private static Logger log = LoggerFactory.getLogger(ReportManager.class);
     private static String reportOutputFilePath;
-    private static String csvReportFilePath;
-    private static Map<String, Set<String>> failedVerticesPerTask = new HashMap<>();
-    private static Map<String, Map<String, VertexResult>> resultsPerVertex = new HashMap<>();
+    private static final Map<String, Set<String>> failedVerticesPerTask = new HashMap<>();
+    private static final Map<String, Map<String, VertexResult>> resultsPerVertex = new HashMap<>();
+
+    public static ReportManager make(String csvReportFilePath) {
+        return new ReportManager(csvReportFilePath);
+    }
 
-    public ReportManager() {
+    private ReportManager(String csvReportFilePath) {
         try {
-            initCsvFile();
+            initCsvFile(csvReportFilePath);
             initReportFile();
         } catch (IOException e) {
-            e.printStackTrace();
             log.info("Init file failed - {}", e.getClass().getSimpleName(), e);
         }
     }
@@ -65,8 +64,7 @@ public class ReportManager {
         Files.write(Paths.get(reportOutputFilePath), sb.toString().getBytes());
     }
 
-    private void initCsvFile() throws IOException {
-        csvReportFilePath = ValidationConfigManager.getCsvReportFilePath();
+    private void initCsvFile(String csvReportFilePath) throws IOException {
         StrBuilder sb = new StrBuilder();
         sb.append("Vertex ID,Task Name,Success,Result Details,Result Description");
         sb.appendNewLine();
@@ -75,12 +73,12 @@ public class ReportManager {
 
     public static void reportTaskEnd(String vertexId, String taskName, VertexResult result) {
         Map<String, VertexResult> vertexTasksResults =
-                Optional.ofNullable(resultsPerVertex.get(vertexId)).orElse(new HashMap<>());
+            Optional.ofNullable(resultsPerVertex.get(vertexId)).orElse(new HashMap<>());
         vertexTasksResults.put(taskName, result);
         resultsPerVertex.put(vertexId, vertexTasksResults);
     }
 
-    public static void addFailedVertex (String taskName, String vertexId) {
+    public static void addFailedVertex(String taskName, String vertexId) {
         Set<String> failedVertices = failedVerticesPerTask.get(taskName);
         if (failedVertices == null) {
             failedVertices = new HashSet<>();
@@ -91,7 +89,9 @@ public class ReportManager {
 
     public static void printValidationTaskStatus(GraphVertex vertexScanned, String taskName, boolean success) {
         String successStatus = success ? "success" : "failed";
-        String line = "-----------------------Vertex: "+vertexScanned.getUniqueId()+", Task " + taskName + " " +successStatus+"-----------------------";
+        String line =
+            "-----------------------Vertex: " + vertexScanned.getUniqueId() + ", Task " + taskName + " " + successStatus
+                + "-----------------------";
         StrBuilder sb = new StrBuilder();
         sb.appendln(line);
         writeReportLineToFile(line);
@@ -99,35 +99,39 @@ public class ReportManager {
 
     public static void writeReportLineToFile(String message) {
         try {
-            Files.write(Paths.get(reportOutputFilePath), new StrBuilder().appendNewLine().toString().getBytes(), StandardOpenOption.APPEND);
+            Files.write(Paths.get(reportOutputFilePath), new StrBuilder().appendNewLine().toString().getBytes(),
+                StandardOpenOption.APPEND);
             Files.write(Paths.get(reportOutputFilePath), message.getBytes(), StandardOpenOption.APPEND);
         } catch (IOException e) {
-            e.printStackTrace();
             log.info("write to file failed - {}", e.getClass().getSimpleName(), e);
         }
     }
 
-    public static void reportValidatorTypeSummary(String validatorName, Set<String> failedTasksNames, Set<String> successTasksNames){
+    public static void reportValidatorTypeSummary(String validatorName, Set<String> failedTasksNames,
+        Set<String> successTasksNames) {
         StrBuilder sb = new StrBuilder();
-        sb.appendln("-----------------------ValidatorExecuter " + validatorName + " Validation Summary-----------------------");
-        sb.appendln("Failed tasks: "+ failedTasksNames);
-        sb.appendln("Success tasks: "+ successTasksNames);
+        sb.appendln(
+            "-----------------------ValidatorExecuter " + validatorName + " Validation Summary-----------------------");
+        sb.appendln("Failed tasks: " + failedTasksNames);
+        sb.appendln("Success tasks: " + successTasksNames);
         writeReportLineToFile(sb.toString());
     }
 
     public static void reportStartValidatorRun(String validatorName, int componenentsNum) {
         StrBuilder sb = new StrBuilder();
-        sb.appendln("------ValidatorExecuter " + validatorName + " Validation Started, on "+componenentsNum+" components---------");
+        sb.appendln("------ValidatorExecuter " + validatorName + " Validation Started, on " + componenentsNum
+            + " components---------");
         writeReportLineToFile(sb.toString());
     }
 
-    public static void reportStartTaskRun(GraphVertex vertex, String taskName){
+    public static void reportStartTaskRun(GraphVertex vertex, String taskName) {
         StrBuilder sb = new StrBuilder();
-        sb.appendln("-----------------------Vertex: "+vertex.getUniqueId()+", Task " + taskName + " Started-----------------------");
+        sb.appendln("-----------------------Vertex: " + vertex.getUniqueId() + ", Task " + taskName
+            + " Started-----------------------");
         writeReportLineToFile(sb.toString());
     }
 
-    public static void reportEndOfToolRun() {
+    public static void reportEndOfToolRun(String csvReportFilePath) {
         StrBuilder sb = new StrBuilder();
         sb.appendln("-----------------------------------Validator Tool Summary-----------------------------------");
         failedVerticesPerTask.forEach((taskName, failedVertices) -> {
@@ -137,10 +141,10 @@ public class ReportManager {
             sb.appendNewLine();
         });
         writeReportLineToFile(sb.toString());
-        printAllResults();
+        printAllResults(csvReportFilePath);
     }
 
-    public static void printAllResults() {
+    public static void printAllResults(String csvReportFilePath) {
         resultsPerVertex.forEach((vertex, tasksResults) -> tasksResults.forEach((task, result) -> {
             try {
                 String resultLine = vertex + "," + task + "," + result.getStatus() + "," + result.getResult();
@@ -150,7 +154,6 @@ public class ReportManager {
                     new StrBuilder().appendNewLine().toString().getBytes(),
                     StandardOpenOption.APPEND);
             } catch (IOException e) {
-                    e.printStackTrace();
                 log.info("write to file failed - {}", e.getClass().getSimpleName(), e);
             }
         }));
index c85385b..063f3f6 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -28,12 +28,11 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
 
 public class ArtifactValidatorTool {
 
-       public static void main(String[] args) {
+    public static void main(String[] args) {
 
         String outputPath = args[0];
         ValidationConfigManager.setOutputFullFilePath(outputPath);
-        ValidationConfigManager.setCsvReportFilePath(outputPath);
-        
+
         String appConfigDir = args[1];
         AnnotationConfigApplicationContext context = initContext(appConfigDir);
         ArtifactToolBL validationToolBL = context.getBean(ArtifactToolBL.class);
@@ -47,12 +46,13 @@ public class ArtifactValidatorTool {
             System.out.println("ArtifactValidation finished with warnings");
             System.exit(2);
         }
-       }
-       
-       private static AnnotationConfigApplicationContext initContext(String appConfigDir) {
-      ConfigurationUploader.uploadConfigurationFiles(appConfigDir);
-               AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ValidationToolConfiguration.class);
-               return context;
-       }
+    }
+
+    private static AnnotationConfigApplicationContext initContext(String appConfigDir) {
+        ConfigurationUploader.uploadConfigurationFiles(appConfigDir);
+        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
+            ValidationToolConfiguration.class);
+        return context;
+    }
 
 }
index 25efc9a..23b9c18 100644 (file)
@@ -42,15 +42,15 @@ public class ValidationTool {
 
         String outputPath = args[0];
         ValidationConfigManager.setOutputFullFilePath(outputPath);
-        ValidationConfigManager.setCsvReportFilePath(outputPath);
+        String csvReportFilePath = ValidationConfigManager.csvReportFilePath(outputPath, System::currentTimeMillis);
 
         String appConfigDir = args[1];
         AnnotationConfigApplicationContext context = initContext(appConfigDir);
         ValidationToolBL validationToolBL = context.getBean(ValidationToolBL.class);
 
         log.info("Start Validation Tool");
-        Boolean result = validationToolBL.validateAll();
-        ReportManager.reportEndOfToolRun();
+        boolean result = validationToolBL.validateAll();
+        ReportManager.reportEndOfToolRun(csvReportFilePath);
         if (result) {
             log.info("Validation finished successfully");
             System.exit(0);
index efc7dd8..570e5b2 100644 (file)
 
 package org.openecomp.sdc.asdctool.impl.validator.config;
 
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+import static org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager.csvReportFilePath;
+
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.openecomp.sdc.asdctool.impl.validator.utils.ReportManager;
@@ -33,27 +37,20 @@ import java.util.Properties;
 public class ValidationConfigManagerTest {
 
     @Test
-    public void testGetOutputFilePath() {
-        String result;
-
-        // default test
-        result = ValidationConfigManager.getOutputFilePath();
+    public void testCsvReportFilePath() {
+        String randomOutput = System.currentTimeMillis() + "";
+        long millis = System.currentTimeMillis();
+        assertThat(
+            csvReportFilePath(randomOutput, () -> millis),
+            is(randomOutput + "/csvSummary_" + millis + ".csv"));
     }
 
     @Test
-    public void testGetCsvReportFilePath() {
+    public void testGetOutputFilePath() {
         String result;
 
         // default test
-        result = ValidationConfigManager.getCsvReportFilePath();
-    }
-
-    @Test
-    public void testSetCsvReportFilePath() {
-        String outputPath = "";
-
-        // default test
-        ValidationConfigManager.setCsvReportFilePath(outputPath);
+        result = ValidationConfigManager.getOutputFilePath();
     }
 
     @Test
index b5ce1ab..1af4a13 100644 (file)
@@ -64,7 +64,7 @@ import static org.mockito.Mockito.when;
 @PowerMockRunnerDelegate(MockitoJUnitRunner.class)
 @PrepareForTest({ReportManager.class})
 public class ArtifactValidationUtilsTest {
-    
+
     @Mock
     private ArtifactCassandraDao artifactCassandraDao;
     @Mock
@@ -91,12 +91,15 @@ public class ArtifactValidationUtilsTest {
     private static final String UNIQUE_ID = "4321";
     private static final String UNIQUE_ID_VERTEX = "321";
 
+    private final static String resourcePath = new File("src/test/resources").getAbsolutePath();
+    private final static String csvReportFilePath = ValidationConfigManager.DEFAULT_CSV_PATH;
+
     public void initReportManager() {
         String resourcePath = new File(Objects
             .requireNonNull(ArtifactValidationUtilsTest.class.getClassLoader().getResource(""))
             .getFile()).getAbsolutePath();
         ValidationConfigManager.setOutputFullFilePath(resourcePath);
-        new ReportManager();
+        ReportManager.make(csvReportFilePath);
     }
 
     @Before
@@ -115,7 +118,7 @@ public class ArtifactValidationUtilsTest {
 
     @After
     public void clean() {
-        ReportManagerHelper.cleanReports();
+        ReportManagerHelper.cleanReports(csvReportFilePath);
     }
 
     @Test
@@ -146,7 +149,7 @@ public class ArtifactValidationUtilsTest {
         // when
         ArtifactsVertexResult result =
             testSubject.validateArtifactsAreInCassandra(vertex, TASK_NAME, artifacts);
-        ReportManager.reportEndOfToolRun();
+        ReportManager.reportEndOfToolRun(csvReportFilePath);
 
         List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
 
@@ -203,19 +206,19 @@ public class ArtifactValidationUtilsTest {
     @Test
     public void testValidateTopologyTemplateArtifacts() {
         // given
-               Map<String, ArtifactDataDefinition> artifacts = new HashMap<>();
-               artifacts.put(ES_ID, artifactDataDefinition);
+        Map<String, ArtifactDataDefinition> artifacts = new HashMap<>();
+        artifacts.put(ES_ID, artifactDataDefinition);
 
-               when(topologyTemplate.getDeploymentArtifacts()).thenReturn(artifacts);
-               when(topologyTemplate.getArtifacts()).thenReturn(artifacts);
-               when(topologyTemplate.getServiceApiArtifacts()).thenReturn(artifacts);
+        when(topologyTemplate.getDeploymentArtifacts()).thenReturn(artifacts);
+        when(topologyTemplate.getArtifacts()).thenReturn(artifacts);
+        when(topologyTemplate.getServiceApiArtifacts()).thenReturn(artifacts);
 
-               when(mapToscaDataDefinition.getMapToscaDataDefinition()).thenReturn(artifacts);
-               Map<String, MapArtifactDataDefinition> artifactsMap = new HashMap<>();
-               artifactsMap.put(ES_ID, mapToscaDataDefinition);
+        when(mapToscaDataDefinition.getMapToscaDataDefinition()).thenReturn(artifacts);
+        Map<String, MapArtifactDataDefinition> artifactsMap = new HashMap<>();
+        artifactsMap.put(ES_ID, mapToscaDataDefinition);
 
-               when(topologyTemplate.getInstanceArtifacts()).thenReturn(artifactsMap);
-               when(topologyTemplate.getInstDeploymentArtifacts()).thenReturn(artifactsMap);
+        when(topologyTemplate.getInstanceArtifacts()).thenReturn(artifactsMap);
+        when(topologyTemplate.getInstDeploymentArtifacts()).thenReturn(artifactsMap);
 
         when(topologyTemplateOperation.getToscaElement(eq(vertex.getUniqueId()), any()))
             .thenReturn(Either.left(topologyTemplate));
index c832c47..011039d 100644 (file)
@@ -38,12 +38,12 @@ public class ReportManagerHelper {
         return readFileAsList(ValidationConfigManager.getOutputFullFilePath());
     }
 
-    public static List<String> getReportCsvFileAsList() {
-        return readFileAsList(ValidationConfigManager.getCsvReportFilePath());
+    public static List<String> getReportCsvFileAsList(String csvReportFilePath) {
+        return readFileAsList(csvReportFilePath);
     }
 
-    public static void cleanReports() {
-        cleanFile(ValidationConfigManager.getCsvReportFilePath());
+    public static void cleanReports(String csvReportFilePath) {
+        cleanFile(csvReportFilePath);
         cleanFile(ValidationConfigManager.getOutputFullFilePath());
     }
 
index 4926c1d..22aaf6e 100644 (file)
@@ -74,24 +74,28 @@ public class ReportManagerTest {
 
     private VertexResult successResult = new VertexResult();
 
+    private final static String resourcePath = new File("src/test/resources").getAbsolutePath();
+    private final static String csvReportFilePath = ValidationConfigManager
+        .csvReportFilePath(resourcePath, System::currentTimeMillis);
+
+
     @Mock
     GraphVertex vertexScanned;
 
-       @Before
+    @Before
     public void setup() {
         String resourcePath = new File(Objects
             .requireNonNull(ReportManagerTest.class.getClassLoader().getResource("")).getFile())
-                .getAbsolutePath();
+            .getAbsolutePath();
         ValidationConfigManager.setOutputFullFilePath(resourcePath);
-        ValidationConfigManager.setCsvReportFilePath(resourcePath);
-        new ReportManager();
+        ReportManager.make(csvReportFilePath);
 
         successResult.setStatus(true);
     }
 
     @After
     public void clean() {
-        ReportManagerHelper.cleanReports();
+        ReportManagerHelper.cleanReports(csvReportFilePath);
     }
 
     @Test
@@ -99,9 +103,9 @@ public class ReportManagerTest {
         // when
         ReportManager.reportTaskEnd(VERTEX_1_ID, TASK_1_NAME, successResult);
         ReportManager.reportTaskEnd(VERTEX_2_ID, TASK_2_NAME, successResult);
-        ReportManager.printAllResults();
+        ReportManager.printAllResults(csvReportFilePath);
 
-        List reportCsvFile = ReportManagerHelper.getReportCsvFileAsList();
+        List<String> reportCsvFile = ReportManagerHelper.getReportCsvFileAsList(csvReportFilePath);
 
         // then
         assertNotNull(reportCsvFile);
@@ -114,7 +118,7 @@ public class ReportManagerTest {
     public void testAddFailedVertex() {
         // when
         ReportManager.addFailedVertex(TASK_1_NAME, VERTEX_1_ID);
-        ReportManager.reportEndOfToolRun();
+        ReportManager.reportEndOfToolRun(csvReportFilePath);
 
         List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
 
@@ -178,19 +182,19 @@ public class ReportManagerTest {
             reportOutputFile.get(4));
     }
 
-       @Test
-       public void testReportStartValidatorRun() {
-               // when
-               ReportManager.reportStartValidatorRun(VALIDATOR_NAME, COMPONENT_SUM);
+    @Test
+    public void testReportStartValidatorRun() {
+        // when
+        ReportManager.reportStartValidatorRun(VALIDATOR_NAME, COMPONENT_SUM);
 
-               List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
+        List reportOutputFile = ReportManagerHelper.getReportOutputFileAsList();
 
-               // then
+        // 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
     public void testReportStartTaskRun() {
@@ -206,11 +210,11 @@ public class ReportManagerTest {
         assertNotNull(reportOutputFile);
         assertEquals(EXPECTED_OUTPUT_FILE_HEADER, reportOutputFile.get(0));
         assertEquals("-----------------------Vertex: " + UNIQUE_ID + ", Task " + TASK_1_NAME
-                + " Started-----------------------", reportOutputFile.get(2));
+            + " Started-----------------------", reportOutputFile.get(2));
     }
 
     private String getCsvExpectedResult(String vertexID, String taskID) {
-        return String.join(",", new String[] {vertexID, taskID,
+        return String.join(",", new String[]{vertexID, taskID,
             String.valueOf(successResult.getStatus()), successResult.getResult()});
     }
 }
\ No newline at end of file