Fix for radio buttons
[sdc.git] / asdc-tests / 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(),
212                                         (failuresPerClass * 1.0) / runsPerClass * 100);
213                         logger.debug("class {} Ignored tests {} %",testClass.getName(),
214                                         (ignoredPerClass * 1.0) / runsPerClass * 100);
215
216                         // List<Failure> failures = result.getFailures();
217                         // if (failures != null) {
218                         // for (Failure failure : failures) {
219                         // System.err.println("9999999999" + failure.getTestHeader());
220                         // }
221                         // }
222
223                         addUnitTestResult(results, testClass, result);
224                         success &= result.wasSuccessful();
225
226                         if (numOfFailureClasses > 0) {
227                                 // if (exitOnFailure) {
228                                 if (exitOnFailure) {
229                                         break;
230                                 }
231                         }
232                 }
233
234                 results.append("</table>");
235                 results.append("<br/><h2> Tests Summary: </h2><br/>");
236                 results.append("Total Runs  : " + totalRunTests + "<br/>");
237                 results.append("Total Failure  : " + totalFailureTests + "<br/>");
238                 results.append("Total: " + totalFailureTests + "/" + totalRunTests + "<br/>");
239                 results.append("</html>");
240
241                 FileUtils.writeToFile(Config.instance().getOutputFolder() + File.separator + Config.instance().getReportName(),
242                                 results.toString());
243
244                 if (!success) {
245                         System.out.println("FAILURE");
246                         logger.error("Failure tests : {} %",((totalFailureTests + totalIgnoreTests) * 1.0) / (totalRunTests + totalIgnoreTests));
247                         logger.error("Ignored tests : {} %",(totalIgnoreTests * 1.0) / (totalRunTests + totalIgnoreTests));
248                         System.exit(1);
249                 }
250
251                 System.out.println("SUCCESS");
252         }
253
254         private List<Class> getClassesForPackage(String pkgname) {
255
256                 List<Class> classes = new ArrayList<Class>();
257
258                 // Get a File object for the package
259                 File directory = null;
260                 String fullPath;
261                 String relPath = pkgname.replace('.', '/');
262
263                 // System.out.println("ClassDiscovery: Package: " + pkgname +
264                 // " becomes Path:" + relPath);
265
266                 URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
267
268                 // System.out.println("ClassDiscovery: Resource = " + resource);
269                 if (resource == null) {
270                         throw new RuntimeException("No resource for " + relPath);
271                 }
272                 fullPath = resource.getFile();
273                 // System.out.println("ClassDiscovery: FullPath = " + resource);
274
275                 if (debug) {
276                         System.out.println("fullPath is " + fullPath);
277                 }
278
279                 try {
280                         directory = new File(resource.toURI());
281                 } catch (URISyntaxException e) {
282                         throw new RuntimeException(
283                                         pkgname + " (" + resource
284                                                         + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...",
285                                         e);
286                 } catch (IllegalArgumentException e) {
287                         directory = null;
288                 }
289                 // System.out.println("ClassDiscovery: Directory = " + directory);
290
291                 if (directory != null && directory.exists()) {
292
293                         // Get the list of the files contained in the package
294                         String[] files = directory.list();
295                         for (int i = 0; i < files.length; i++) {
296
297                                 // we are only interested in .class files
298                                 if (files[i].endsWith(".class") && false == files[i].contains("$")) {
299
300                                         // removes the .class extension
301                                         String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);
302
303                                         // System.out.println("ClassDiscovery: className = " +
304                                         // className);
305
306                                         if (debug) {
307                                                 System.out.println("ClassDiscovery: className = " + className);
308                                         }
309
310                                         try {
311                                                 Class clas = Class.forName(className);
312                                                 boolean isAddToRun = false;
313                                                 Method[] methods = clas.getMethods();
314                                                 for (Method method : methods) {
315                                                         Annotation[] anns = method.getAnnotations();
316                                                         for (Annotation an : anns) {
317                                                                 if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
318                                                                         isAddToRun = true;
319                                                                         break;
320                                                                 }
321                                                         }
322                                                 }
323                                                 if (isAddToRun)
324                                                         classes.add(clas);
325                                         } catch (ClassNotFoundException e) {
326                                                 throw new RuntimeException("ClassNotFoundException loading " + className);
327                                         }
328                                 }
329                         }
330                 } else {
331                         try {
332                                 String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
333
334                                 if (debug) {
335                                         System.out.println("jarPath is " + jarPath);
336                                 }
337
338                                 JarFile jarFile = new JarFile(jarPath);
339                                 Enumeration<JarEntry> entries = jarFile.entries();
340                                 while (entries.hasMoreElements()) {
341                                         JarEntry entry = entries.nextElement();
342                                         String entryName = entry.getName();
343                                         if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {
344
345                                                 // System.out.println("ClassDiscovery: JarEntry: " +
346                                                 // entryName);
347                                                 String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
348
349                                                 // System.out.println("ClassDiscovery: className = " +
350                                                 // className);
351
352                                                 if (false == className.contains("$")) {
353
354                                                         if (debug) {
355                                                                 System.out.println("ClassDiscovery: className = " + className);
356                                                         }
357
358                                                         try {
359                                                                 Class clas = Class.forName(className);
360                                                                 boolean isAddToRun = false;
361                                                                 Method[] methods = clas.getMethods();
362                                                                 for (Method method : methods) {
363                                                                         Annotation[] anns = method.getAnnotations();
364                                                                         for (Annotation an : anns) {
365                                                                                 if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
366                                                                                         isAddToRun = true;
367                                                                                         break;
368                                                                                 }
369                                                                         }
370                                                                 }
371                                                                 if (isAddToRun)
372                                                                         classes.add(clas);
373                                                         } catch (ClassNotFoundException e) {
374                                                                 throw new RuntimeException("ClassNotFoundException loading " + className);
375                                                         }
376                                                 }
377                                         }
378                                 }
379                                 jarFile.close();
380
381                         } catch (IOException e) {
382                                 throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e);
383                         }
384                 }
385                 return classes;
386         }
387
388         private void addTableHead(StringBuilder results) {
389                 results.append("<tr>");
390                 results.append("<th>").append("Unit Test").append("</th>");
391                 results.append("<th>").append("Result").append("</th>");
392                 results.append("</tr>");
393         }
394
395         private void addUnitTestResult(StringBuilder results, Class<? extends AttSdcTest> testClass,
396                         Result unitTestResult) {
397
398                 boolean isSuccess = unitTestResult.wasSuccessful();
399
400                 String result = (isSuccess) ? "success" : "fail";
401                 String fileName = FileUtils.getFileName(testClass.getName());
402                 results.append("<tr>");
403                 // results.append("<td>").append(FileUtils.getFileName(testClass.getName())).append("</td>");
404                 results.append("<td class=\"name\">")
405                                 .append("<a href=\"" + fileName + timeOfTest + ".html\">" + fileName + "</a>").append("</td>");
406                 results.append("<td class=\"" + result + "\">").append(result).append("</td>");
407                 results.append("</tr>");
408         }
409
410 }