[SDC-29] rebase continue work to align source
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / ci / tests / run / StartTest.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.util.ArrayList;
31 import java.util.Enumeration;
32 import java.util.List;
33 import java.util.concurrent.atomic.AtomicBoolean;
34 import java.util.jar.JarEntry;
35 import java.util.jar.JarFile;
36
37 import org.apache.log4j.Logger;
38 import org.apache.log4j.PropertyConfigurator;
39 import org.openecomp.sdc.ci.tests.config.Config;
40 import org.openecomp.sdc.ci.tests.utils.Utils;
41 //import org.junit.runner.JUnitCore;
42 //import org.junit.runner.Result;
43 //import org.junit.runner.notification.Failure;
44 import org.testng.TestListenerAdapter;
45 import org.testng.TestNG;
46 import org.testng.reporters.TestHTMLReporter;
47 import org.testng.xml.XmlSuite;
48
49 public class StartTest {
50
51         // private List<Class<? extends AttSdcTest>> testClasses = new
52         // 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                 TestNG testng = new TestNG();
85
86                 List<String> suites = new ArrayList<String>();
87                 suites.add("testSuites/" + args[0]);
88                 testng.setTestSuites(suites);
89                 testng.setUseDefaultListeners(true);
90                 testng.setOutputDirectory("target/");
91
92                 testng.run();
93
94         }
95
96         public StartTest() {
97                 logger = Logger.getLogger(StartTest.class.getName());
98         }
99
100         public static void enableLogger() {
101
102                 if (false == loggerInitialized.get()) {
103
104                         loggerInitialized.set(true);
105
106                         String log4jPropsFile = System.getProperty("log4j.configuration");
107                         if (System.getProperty("os.name").contains("Windows")) {
108                                 String logProps = "src/main/resources/ci/conf/log4j.properties";
109                                 if (log4jPropsFile == null) {
110                                         System.setProperty("targetlog", "target/");
111                                         log4jPropsFile = logProps;
112                                 }
113
114                         }
115                         PropertyConfigurator.configureAndWatch(log4jPropsFile);
116
117                 }
118         }
119
120         private List<Class> getClassesForPackage(String pkgname) {
121
122                 List<Class> classes = new ArrayList<Class>();
123
124                 // Get a File object for the package
125                 File directory = null;
126                 String fullPath;
127                 String relPath = pkgname.replace('.', '/');
128
129                 // System.out.println("ClassDiscovery: Package: " + pkgname +
130                 // " becomes Path:" + relPath);
131
132                 URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
133
134                 // System.out.println("ClassDiscovery: Resource = " + resource);
135                 if (resource == null) {
136                         throw new RuntimeException("No resource for " + relPath);
137                 }
138                 fullPath = resource.getFile();
139                 // System.out.println("ClassDiscovery: FullPath = " + resource);
140
141                 if (debug) {
142                         System.out.println("fullPath is " + fullPath);
143                 }
144
145                 try {
146                         directory = new File(resource.toURI());
147                 } catch (URISyntaxException e) {
148                         throw new RuntimeException(
149                                         pkgname + " (" + resource
150                                                         + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...",
151                                         e);
152                 } catch (IllegalArgumentException e) {
153                         directory = null;
154                 }
155                 // System.out.println("ClassDiscovery: Directory = " + directory);
156
157                 if (directory != null && directory.exists()) {
158
159                         // Get the list of the files contained in the package
160                         String[] files = directory.list();
161                         for (int i = 0; i < files.length; i++) {
162
163                                 // we are only interested in .class files
164                                 if (files[i].endsWith(".class") && false == files[i].contains("$")) {
165
166                                         // removes the .class extension
167                                         String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);
168
169                                         // System.out.println("ClassDiscovery: className = " +
170                                         // className);
171
172                                         if (debug) {
173                                                 System.out.println("ClassDiscovery: className = " + className);
174                                         }
175
176                                         try {
177                                                 Class clas = Class.forName(className);
178                                                 boolean isAddToRun = false;
179                                                 Method[] methods = clas.getMethods();
180                                                 for (Method method : methods) {
181                                                         Annotation[] anns = method.getAnnotations();
182                                                         for (Annotation an : anns) {
183                                                                 if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
184                                                                         isAddToRun = true;
185                                                                         break;
186                                                                 }
187                                                         }
188                                                 }
189                                                 if (isAddToRun)
190                                                         classes.add(clas);
191                                         } catch (ClassNotFoundException e) {
192                                                 throw new RuntimeException("ClassNotFoundException loading " + className);
193                                         }
194                                 }
195                         }
196                 } else {
197                         try {
198                                 String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
199
200                                 if (debug) {
201                                         System.out.println("jarPath is " + jarPath);
202                                 }
203
204                                 JarFile jarFile = new JarFile(jarPath);
205                                 Enumeration<JarEntry> entries = jarFile.entries();
206                                 while (entries.hasMoreElements()) {
207                                         JarEntry entry = entries.nextElement();
208                                         String entryName = entry.getName();
209                                         if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {
210
211                                                 // System.out.println("ClassDiscovery: JarEntry: " +
212                                                 // entryName);
213                                                 String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
214
215                                                 // System.out.println("ClassDiscovery: className = " +
216                                                 // className);
217
218                                                 if (false == className.contains("$")) {
219
220                                                         if (debug) {
221                                                                 System.out.println("ClassDiscovery: className = " + className);
222                                                         }
223
224                                                         try {
225                                                                 Class clas = Class.forName(className);
226                                                                 boolean isAddToRun = false;
227                                                                 Method[] methods = clas.getMethods();
228                                                                 for (Method method : methods) {
229                                                                         Annotation[] anns = method.getAnnotations();
230                                                                         for (Annotation an : anns) {
231                                                                                 if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
232                                                                                         isAddToRun = true;
233                                                                                         break;
234                                                                                 }
235                                                                         }
236                                                                 }
237                                                                 if (isAddToRun)
238                                                                         classes.add(clas);
239                                                         } catch (ClassNotFoundException e) {
240                                                                 throw new RuntimeException("ClassNotFoundException loading " + className);
241                                                         }
242                                                 }
243                                         }
244                                 }
245                                 jarFile.close();
246
247                         } catch (IOException e) {
248                                 throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e);
249                         }
250                 }
251                 return classes;
252         }
253
254         private void addTableHead(StringBuilder results) {
255                 results.append("<tr>");
256                 results.append("<th>").append("Unit Test").append("</th>");
257                 results.append("<th>").append("Result").append("</th>");
258                 results.append("</tr>");
259         }
260
261         // private void addUnitTestResult(StringBuilder results,
262         // Class<? extends AttSdcTest> testClass, Result unitTestResult) {
263         //
264         // boolean isSuccess = unitTestResult.wasSuccessful();
265         //
266         // String result = (isSuccess) ? "success" : "fail";
267         // String fileName = FileUtils.getFileName(testClass.getName());
268         // results.append("<tr>");
269         // //
270         // results.append("<td>").append(FileUtils.getFileName(testClass.getName())).append("</td>");
271         // results.append("<td class=\"name\">")
272         // .append("<a href=\"" + fileName + timeOfTest + ".html\">"
273         // + fileName + "</a>").append("</td>");
274         // results.append("<td class=\"" + result + "\">").append(result)
275         // .append("</td>");
276         // results.append("</tr>");
277         // }
278
279 }