]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.testing/src/org/simantics/db/testing/base/SCLScriptTestBase.java
459be8d4a62228c70c52430c143c0459242706db
[simantics/platform.git] / bundles / org.simantics.db.testing / src / org / simantics / db / testing / base / SCLScriptTestBase.java
1 package org.simantics.db.testing.base;
2
3 import java.io.IOException;
4 import java.lang.management.ManagementFactory;
5 import java.util.ArrayList;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.Timer;
9 import java.util.TimerTask;
10
11 import org.junit.Rule;
12 import org.junit.rules.TestName;
13 import org.osgi.framework.BundleContext;
14 import org.simantics.db.testing.cases.FreshDatabaseTest;
15 import org.simantics.scl.compiler.module.repository.ModuleRepository;
16 import org.simantics.scl.compiler.testing.TestRunnable;
17 import org.simantics.scl.compiler.testing.repository.TestRepository;
18 import org.simantics.scl.osgi.SCLOsgi;
19 import org.simantics.scl.osgi.internal.Activator;
20 import org.simantics.scl.osgi.internal.ServiceBasedModuleSourceRepository;
21 import org.simantics.scl.osgi.internal.ServiceBasedTestRepository;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 import gnu.trove.map.hash.THashMap;
26
27 /**
28  * Utilizies {@link TestRepository} for collecting SCL tests from bundles
29  * 
30  * @author Jani Simomaa
31  */
32 public class SCLScriptTestBase extends FreshDatabaseTest {
33
34     private static final Logger LOGGER = LoggerFactory.getLogger(SCLScriptTestBase.class);
35
36     private Map<String, TestRunnable> testRunnables = new THashMap<String, TestRunnable>();
37
38     @Rule public TestName testName = new TestName();
39
40     /**
41      * Constructor that initially searches for all SCL test scripts and stores
42      * them into a Map for later access
43      */
44     public SCLScriptTestBase() {
45         super();
46         BundleContext context = Activator.getContext();
47         List<TestRunnable> runnables = new ArrayList<TestRunnable>();
48         context.getService(context.getServiceReference(TestRepository.class)).collectTests(runnables);
49         for (TestRunnable runnable : runnables) {
50             testRunnables.put(runnable.getName(), runnable);
51         }
52     }
53
54     /**
55      * Simplest method for running a SCL test
56      */
57     protected void test() {
58         test(-1);
59     }
60
61     /**
62      * Executes a test case with given timeout as seconds. When time runs out one
63      * can assume a deadlock has happened. The process is killed after the timeout
64      * in order to keep the possible multiple tests running.
65      * 
66      * @param timeout allowed execution time given in seconds
67      */
68     protected void test(int timeout) {
69         testImpl(timeout);
70     }
71
72     /**
73      * Executes a test case with given timeout as seconds
74      * 
75      * @param timeout allowed execution time given in seconds
76      */
77     private void testImpl(int timeout) {
78         SCLOsgi.SOURCE_REPOSITORY = new ServiceBasedModuleSourceRepository(Activator.getContext());
79         SCLOsgi.MODULE_REPOSITORY = new ModuleRepository(SCLOsgi.SOURCE_REPOSITORY);
80         SCLOsgi.TEST_REPOSITORY = new ServiceBasedTestRepository(Activator.getContext());
81
82         String testName = resolveTestName();
83         TestRunnable runnable = testRunnables.get(testName);
84         long start = System.nanoTime(); 
85
86         if (timeout > -1) {
87             LOGGER.info("Running test {} with a timeout of {} seconds", testName, timeout); //$NON-NLS-1$
88             Timer timer = new Timer();
89             timer.schedule(new TimerTask() {
90
91                 @Override
92                 public void run() {
93                     LOGGER.info("Watchdog will kill this test process because it has been executing for over {} seconds", timeout); //$NON-NLS-1$
94                     String processName = ManagementFactory.getRuntimeMXBean().getName();
95                     LOGGER.info("Test Process Name: {}", processName); //$NON-NLS-1$
96                     String PID = processName.split("@")[0];
97                     String command = "taskkill /F /PID " + PID;
98                     LOGGER.info("Running command to kill test process: {}", command); //$NON-NLS-1$
99                     try {
100                         Runtime.getRuntime().exec(command);
101                     } catch (IOException e) {
102                         LOGGER.error("Failed to kill process that ran over its execution time limit of {} seconds", timeout, e);
103                     }
104                 }
105                 
106             }, timeout*1000);
107             try {
108                 runnable.run();
109                 long end = System.nanoTime();
110                 LOGGER.info("Completed test {} execution in {} seconds", testName, String.format("%.3f", (end-start)*1e-9)); //$NON-NLS-1$
111             } catch (Exception e) {
112                 LOGGER.error("Failed to run test {} runnable {}", testName, runnable, e);
113             } finally {
114                 timer.cancel();
115             }
116         } else {
117             LOGGER.info("Running test {} without timeout", testName); //$NON-NLS-1$
118             try {
119                 runnable.run();
120                 long end = System.nanoTime();
121                 LOGGER.info("Completed test {} execution in {} seconds", testName, String.format("%.3f", (end-start)*1e-9)); //$NON-NLS-1$
122             } catch (Exception e) {
123                 LOGGER.error("Failed to run test {} runnable {}", testName, runnable, e);
124             }
125         }
126     }
127
128     /**
129      * Resolves the full test name based on the names of classes that extends this
130      * SCLScriptTestBase class.<br><br>
131      * 
132      * For example if our tests locate in <code>sclTests/Simantics/Regression/FirstTest.sts</code>
133      * the class hierarchy would be:
134      * 
135      * <ul>
136      *   <li><code>SCLScriptTestBase</code>
137      *     <ul>
138      *       <li><code>Simantics</code>
139      *         <ul>
140      *           <li><code>Regression</code></li>
141      *         </ul>
142      *       </li>
143      *     </ul>
144      *   </li>
145      * </ul>
146      * And the script file name is the same than JUnit method name.
147      * 
148      * @return full testName
149      */
150     private String resolveTestName() {
151         StringBuilder sb = new StringBuilder();
152         Class<?> clazz = this.getClass();
153         while (true) {
154             if (!(clazz.getName() == SCLScriptTestBase.class.getName())) {
155                 String[] classNameParts = clazz.getName().split("\\.");
156                 sb.insert(0, "/");
157                 sb.insert(0, classNameParts[classNameParts.length - 1]);
158                 clazz = clazz.getSuperclass();
159             } else {
160                 sb.append(testName.getMethodName());
161                 break;
162             }
163         }
164         return sb.toString();
165     }
166
167 }