[SDC-29] rebase continue work to align source
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / ci / tests / run / StartTest2backup.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.ci.tests.run;
22
23 import java.io.File;
24 import java.io.FileNotFoundException;
25 import java.io.IOException;
26 import java.lang.annotation.Annotation;
27 import java.lang.reflect.Method;
28 import java.net.URISyntaxException;
29 import java.net.URL;
30 import java.text.SimpleDateFormat;
31 import java.util.ArrayList;
32 import java.util.Calendar;
33 import java.util.Enumeration;
34 import java.util.List;
35 import java.util.concurrent.atomic.AtomicBoolean;
36 import java.util.jar.JarEntry;
37 import java.util.jar.JarFile;
38
39 import org.apache.log4j.PropertyConfigurator;
40 import org.junit.runner.JUnitCore;
41 import org.junit.runner.Result;
42 import org.junit.runner.notification.Failure;
43 import org.openecomp.sdc.ci.tests.api.AttSdcTest;
44 import org.openecomp.sdc.ci.tests.config.Config;
45 import org.openecomp.sdc.ci.tests.utils.Utils;
46 import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 public class StartTest2backup {
51
52         private List<Class<? extends AttSdcTest>> testClasses = new ArrayList<Class<? extends AttSdcTest>>();
53         public static long timeOfTest = 0;
54
55         public static boolean debug = false;
56
57         public static AtomicBoolean loggerInitialized = new AtomicBoolean(false);
58
59         protected static Logger logger = null;
60
61         public static void main(String[] args) {
62
63                 String debugEnabled = System.getProperty("debug");
64                 if (debugEnabled != null && debugEnabled.equalsIgnoreCase("true")) {
65                         debug = true;
66                 }
67                 System.out.println("Debug mode is " + (debug ? "enabled" : "disabled"));
68
69                 enableLogger();
70
71                 Config config = null;
72                 try {
73                         config = Utils.getConfig();
74                 } catch (FileNotFoundException e) {
75                         // TODO Auto-generated catch block
76                         e.printStackTrace();
77                 }
78
79                 if (config == null) {
80                         logger.error("Failed to configuration file of ci tests.");
81                         System.exit(1);
82                 }
83
84                 List<String> packagesToRun = config.getPackages();
85                 if (packagesToRun == null || true == packagesToRun.isEmpty()) {
86                         logger.error("No package was configured to be executed.");
87                         System.exit(2);
88                 }
89                 StartTest2backup tests = new StartTest2backup();
90
91                 boolean stopOnClassFailure = false;
92                 String stopOnClassFailureStr = System.getProperty("stopOnClassFailure");
93                 if (stopOnClassFailureStr != null && stopOnClassFailureStr.equalsIgnoreCase("true")) {
94                         stopOnClassFailure = true;
95                 } else {
96                         Boolean stopOnClassFailureObj = config.isStopOnClassFailure();
97                         if (stopOnClassFailureObj != null) {
98                                 stopOnClassFailure = stopOnClassFailureObj.booleanValue();
99                         }
100                 }
101
102                 tests.start(packagesToRun, stopOnClassFailure);
103         }
104
105         public StartTest2backup() {
106                 logger = LoggerFactory.getLogger(StartTest2backup.class.getName());
107         }
108
109         public static void enableLogger() {
110
111                 if (false == loggerInitialized.get()) {
112
113                         loggerInitialized.set(true);
114
115                         String log4jPropsFile = System.getProperty("log4j.configuration");
116                         if (System.getProperty("os.name").contains("Windows")) {
117                                 String logProps = "src/main/resources/ci/conf/log4j.properties";
118                                 if (log4jPropsFile == null) {
119                                         System.setProperty("targetlog", "target/");
120                                         log4jPropsFile = logProps;
121                                 }
122
123                         }
124                         PropertyConfigurator.configureAndWatch(log4jPropsFile);
125
126                 }
127         }
128
129         public void start(List<String> packages, boolean exitOnFailure) {
130
131                 boolean success = true;
132                 StringBuilder results = new StringBuilder();
133                 Result result;
134
135                 if (packages == null) {
136                         return;
137                 }
138
139                 for (String packageName : packages) {
140                         // List<Class> classesForPackage =
141                         // getClassesForPackage("org.openecomp.sdc.ci.tests.execute");
142                         List<Class> classesForPackage = getClassesForPackage(packageName);
143                         if (classesForPackage != null && false == classesForPackage.isEmpty()) {
144                                 for (Class testUnit : classesForPackage) {
145                                         testClasses.add(testUnit);
146                                 }
147                         }
148                 }
149
150                 System.out.println(testClasses);
151
152                 // tsetClasses.add(LogValidatorTest.class);
153                 // tsetClasses.add(AttNorthboundTest.class);
154
155                 results.append(
156                                 "<Html><head><style>th{background-color: gray;color: white;height: 30px;}td {color: black;height: 30px;}.fail {background-color: #FF5555;width: 100px;text-align: center;}.success {background-color: #00FF00;width: 100px;text-align: center;}.name {width: 200px;background-color: #F0F0F0;}.message {width: 300px;background-color: #F0F0F0;}</style></head><body>");
157
158                 Calendar calendar = Calendar.getInstance();
159                 timeOfTest = calendar.getTimeInMillis();
160                 SimpleDateFormat date_format = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");
161                 results.append("<br/><h2> This report generated on " + date_format.format(calendar.getTime()) + "</h2><br/>");
162
163                 results.append("<table>");
164                 addTableHead(results);
165
166                 int size = testClasses.size();
167                 int index = 0;
168
169                 int totalRunTests = 0;
170                 int totalFailureTests = 0;
171                 int totalIgnoreTests = 0;
172                 int numOfFailureClasses = 0;
173                 for (Class<? extends AttSdcTest> testClass : testClasses) {
174
175                         index++;
176
177                         StringBuilder builder = new StringBuilder();
178                         String str = "***************************************************************************";
179                         builder.append(str + "\n");
180                         String current = "class " + index + "/" + size + " failure(" + numOfFailureClasses + ") + RUNS("
181                                         + totalRunTests + ")" + " FAILURES(" + totalFailureTests + ") IGNORED(" + totalIgnoreTests + ")";
182                         int interval = ((str.length() - current.length() - 2) / 2);
183                         String substring = str.substring(0, interval);
184                         builder.append(substring + " " + current + " " + substring + "\n");
185                         builder.append(str + "\n");
186
187                         System.out.println(builder.toString());
188
189                         logger.debug(builder.toString());
190                         logger.debug("Going to run test class {}", testClass.getName());
191
192                         result = JUnitCore.runClasses(testClass);
193                         if (result.wasSuccessful() == false) {
194                                 numOfFailureClasses++;
195                         }
196                         logger.debug("Test class {} finished {}",testClass.getName(),(result.wasSuccessful() ? "OK." : " WITH ERROR."));
197                         List<Failure> failures = result.getFailures();
198                         if (failures != null) {
199                                 for (Failure failure : failures) {
200                                         logger.error("Test class {} failure test {}-{}",testClass.getName(),failure.getTestHeader(),failure.getTrace());
201                                 }
202                         }
203                         int runsPerClass = result.getRunCount();
204                         int failuresPerClass = result.getFailureCount();
205                         int ignoredPerClass = result.getIgnoreCount();
206
207                         totalRunTests += runsPerClass;
208                         totalFailureTests += failuresPerClass;
209                         totalIgnoreTests += ignoredPerClass;
210
211                         logger.debug("class {} Failed tests {} %",testClass.getName(),(failuresPerClass * 1.0) / runsPerClass * 100);
212                         logger.debug("class {} Ignored tests {} %",testClass.getName(),(ignoredPerClass * 1.0) / runsPerClass * 100);
213
214                         // List<Failure> failures = result.getFailures();
215                         // if (failures != null) {
216                         // for (Failure failure : failures) {
217                         // System.err.println("9999999999" + failure.getTestHeader());
218                         // }
219                         // }
220
221                         addUnitTestResult(results, testClass, result);
222                         success &= result.wasSuccessful();
223
224                         if (numOfFailureClasses > 0) {
225                                 // if (exitOnFailure) {
226                                 if (exitOnFailure) {
227                                         break;
228                                 }
229                         }
230                 }
231
232                 results.append("</table>");
233                 results.append("<br/><h2> Tests Summary: </h2><br/>");
234                 results.append("Total Runs  : " + totalRunTests + "<br/>");
235                 results.append("Total Failure  : " + totalFailureTests + "<br/>");
236                 results.append("Total: " + totalFailureTests + "/" + totalRunTests + "<br/>");
237                 results.append("</html>");
238
239                 FileUtils.writeToFile(Config.instance().getOutputFolder() + File.separator + Config.instance().getReportName(),
240                                 results.toString());
241
242                 if (!success) {
243                         System.out.println("FAILURE");
244                         logger.error("Failure tests : {} %",((totalFailureTests + totalIgnoreTests) * 1.0) / (totalRunTests + totalIgnoreTests));
245                         logger.error("Ignored tests : {} %",(totalIgnoreTests * 1.0) / (totalRunTests + totalIgnoreTests));
246                         System.exit(1);
247                 }
248
249                 System.out.println("SUCCESS");
250         }
251
252         private List<Class> getClassesForPackage(String pkgname) {
253
254                 List<Class> classes = new ArrayList<Class>();
255
256                 // Get a File object for the package
257                 File directory = null;
258                 String fullPath;
259                 String relPath = pkgname.replace('.', '/');
260
261                 // System.out.println("ClassDiscovery: Package: " + pkgname +
262                 // " becomes Path:" + relPath);
263
264                 URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
265
266                 // System.out.println("ClassDiscovery: Resource = " + resource);
267                 if (resource == null) {
268                         throw new RuntimeException("No resource for " + relPath);
269                 }
270                 fullPath = resource.getFile();
271                 // System.out.println("ClassDiscovery: FullPath = " + resource);
272
273                 if (debug) {
274                         System.out.println("fullPath is " + fullPath);
275                 }
276
277                 try {
278                         directory = new File(resource.toURI());
279                 } catch (URISyntaxException e) {
280                         throw new RuntimeException(
281                                         pkgname + " (" + resource
282                                                         + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...",
283                                         e);
284                 } catch (IllegalArgumentException e) {
285                         directory = null;
286                 }
287                 // System.out.println("ClassDiscovery: Directory = " + directory);
288
289                 if (directory != null && directory.exists()) {
290
291                         // Get the list of the files contained in the package
292                         String[] files = directory.list();
293                         for (int i = 0; i < files.length; i++) {
294
295                                 // we are only interested in .class files
296                                 if (files[i].endsWith(".class") && false == files[i].contains("$")) {
297
298                                         // removes the .class extension
299                                         String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);
300
301                                         // System.out.println("ClassDiscovery: className = " +
302                                         // className);
303
304                                         if (debug) {
305                                                 System.out.println("ClassDiscovery: className = " + className);
306                                         }
307
308                                         try {
309                                                 Class clas = Class.forName(className);
310                                                 boolean isAddToRun = false;
311                                                 Method[] methods = clas.getMethods();
312                                                 for (Method method : methods) {
313                                                         Annotation[] anns = method.getAnnotations();
314                                                         for (Annotation an : anns) {
315                                                                 if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
316                                                                         isAddToRun = true;
317                                                                         break;
318                                                                 }
319                                                         }
320                                                 }
321                                                 if (isAddToRun)
322                                                         classes.add(clas);
323                                         } catch (ClassNotFoundException e) {
324                                                 throw new RuntimeException("ClassNotFoundException loading " + className);
325                                         }
326                                 }
327                         }
328                 } else {
329                         try {
330                                 String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
331
332                                 if (debug) {
333                                         System.out.println("jarPath is " + jarPath);
334                                 }
335
336                                 JarFile jarFile = new JarFile(jarPath);
337                                 Enumeration<JarEntry> entries = jarFile.entries();
338                                 while (entries.hasMoreElements()) {
339                                         JarEntry entry = entries.nextElement();
340                                         String entryName = entry.getName();
341                                         if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {
342
343                                                 // System.out.println("ClassDiscovery: JarEntry: " +
344                                                 // entryName);
345                                                 String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
346
347                                                 // System.out.println("ClassDiscovery: className = " +
348                                                 // className);
349
350                                                 if (false == className.contains("$")) {
351
352                                                         if (debug) {
353                                                                 System.out.println("ClassDiscovery: className = " + className);
354                                                         }
355
356                                                         try {
357                                                                 Class clas = Class.forName(className);
358                                                                 boolean isAddToRun = false;
359                                                                 Method[] methods = clas.getMethods();
360                                                                 for (Method method : methods) {
361                                                                         Annotation[] anns = method.getAnnotations();
362                                                                         for (Annotation an : anns) {
363                                                                                 if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
364                                                                                         isAddToRun = true;
365                                                                                         break;
366                                                                                 }
367                                                                         }
368                                                                 }
369                                                                 if (isAddToRun)
370                                                                         classes.add(clas);
371                                                         } catch (ClassNotFoundException e) {
372                                                                 throw new RuntimeException("ClassNotFoundException loading " + className);
373                                                         }
374                                                 }
375                                         }
376                                 }
377                                 jarFile.close();
378
379                         } catch (IOException e) {
380                                 throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e);
381                         }
382                 }
383                 return classes;
384         }
385
386         private void addTableHead(StringBuilder results) {
387                 results.append("<tr>");
388                 results.append("<th>").append("Unit Test").append("</th>");
389                 results.append("<th>").append("Result").append("</th>");
390                 results.append("</tr>");
391         }
392
393         private void addUnitTestResult(StringBuilder results, Class<? extends AttSdcTest> testClass,
394                         Result unitTestResult) {
395
396                 boolean isSuccess = unitTestResult.wasSuccessful();
397
398                 String result = (isSuccess) ? "success" : "fail";
399                 String fileName = FileUtils.getFileName(testClass.getName());
400                 results.append("<tr>");
401                 // results.append("<td>").append(FileUtils.getFileName(testClass.getName())).append("</td>");
402                 results.append("<td class=\"name\">")
403                                 .append("<a href=\"" + fileName + timeOfTest + ".html\">" + fileName + "</a>").append("</td>");
404                 results.append("<td class=\"" + result + "\">").append(result).append("</td>");
405                 results.append("</tr>");
406         }
407
408 }