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