]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.testing/src/org/simantics/db/testing/common/TestBase.java
06fc784a29a30b68fa335fec2e25efbb7f9ad5ec
[simantics/platform.git] / bundles / org.simantics.db.testing / src / org / simantics / db / testing / common / TestBase.java
1 package org.simantics.db.testing.common;
2 /*******************************************************************************
3  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4  * in Industry THTH ry.
5  * All rights reserved. This program and the accompanying materials
6  * are made available under the terms of the Eclipse Public License v1.0
7  * which accompanies this distribution, and is available at
8  * http://www.eclipse.org/legal/epl-v10.html
9  *
10  * Contributors:
11  *     VTT Technical Research Centre of Finland - initial API and implementation
12  *******************************************************************************/
13
14
15 import java.security.Permission;
16 import java.util.ArrayList;
17 import java.util.UUID;
18
19 import org.eclipse.core.runtime.Platform;
20 import org.junit.After;
21 import org.junit.Before;
22 import org.simantics.SimanticsPlatform;
23 import org.simantics.db.AsyncReadGraph;
24 import org.simantics.db.ReadGraph;
25 import org.simantics.db.Resource;
26 import org.simantics.db.Session;
27 import org.simantics.db.WriteGraph;
28 import org.simantics.db.WriteOnlyGraph;
29 import org.simantics.db.common.request.WriteOnlyRequest;
30 import org.simantics.db.exception.DatabaseException;
31 import org.simantics.db.exception.ServiceNotFoundException;
32 import org.simantics.db.management.SessionContext;
33 import org.simantics.db.procedure.AsyncProcedure;
34 import org.simantics.db.request.AsyncRead;
35 import org.simantics.db.request.Read;
36 import org.simantics.db.service.LifecycleSupport;
37 import org.simantics.db.testing.impl.Configuration;
38 import org.simantics.layer0.Layer0;
39 import org.simantics.utils.FileUtils;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Base class for Simantics Test Cases.
45  * Assumes that the Simantics database is already running.
46  *
47  * @author Marko Luukkainen <marko.luukkainen@vtt.fi>
48  */
49 public abstract class TestBase /*extends TestCase*/ {
50     private static final Logger LOGGER = LoggerFactory.getLogger(TestBase.class);
51     public static final boolean DEBUG = Configuration.get().debug;
52     public static final String ROOT_LIBRARY_URI = "http:/";
53     private NoExitSecurityManager noExitSecurityManager;
54     private SecurityManager securityManager;
55     protected DatabaseState state;
56     public Throwable exception2;
57     protected Layer0 L0;
58     static boolean printStart = true;
59     public static final ArrayList<String> initialWorkspaceFiles = FileUtils.createFileFilter(Platform.getLocation().toFile(), null);
60     public static void printStart(Object t) {
61         if(printStart) LOGGER.info("Test is {}", t.getClass().getName());
62     }
63     protected static void setPrintStart(boolean value) {
64         printStart = value;
65     }
66
67     public Resource getProjectResource() {
68         return SimanticsPlatform.INSTANCE.projectResource;
69     }
70
71     @Before
72     public void setUp() throws Exception {
73         printStart(this);
74         securityManager = System.getSecurityManager();
75         noExitSecurityManager = new NoExitSecurityManager(state.getSession());
76         System.setSecurityManager(noExitSecurityManager);
77         Session session = state.getSession();
78         L0 = Layer0.getInstance(session);
79     }
80     @After
81     public void tearDown() throws Exception {
82         if (noExitSecurityManager != null) {
83             System.setSecurityManager(securityManager);
84             noExitSecurityManager.dispose();
85             noExitSecurityManager = null;
86         }
87         L0 = null;
88         state = null;
89         exception2 = null;
90         securityManager = null;
91         commonTearDown();
92     }
93     public static void commonTearDown() {
94         Runtime rt = Runtime.getRuntime();
95         rt.gc();
96         rt.gc();
97         rt.gc();
98         if (DEBUG) {
99             System.out.println("Max=" + rt.maxMemory()
100                 + " tot=" + rt.totalMemory()
101                 + " fre=" + rt.freeMemory());
102         }
103     }
104
105     public static String getRandomString() {
106         return UUID.randomUUID().toString();
107     }
108
109     protected Session getSession() throws DatabaseException {
110         return state.getSession();
111     }
112     protected SessionContext getSessionContext() {
113         return state.getSessionContext();
114     }
115
116 //    protected Resource getRootLibrary() throws DatabaseException {
117 //        return getRootLibrary(getSession());
118 //    }
119 //
120 //    protected Resource getRootLibrary(Session session) throws DatabaseException {
121 //        return session.syncRequest(new ReadQuery<Resource>() {
122 //            @Override
123 //            public void run(ReadGraph g) throws DatabaseException {
124 //                result = g.getResource(ROOT_LIBRARY_URI);
125 //                assertTrue(result.getResourceId() != SessionManagerSource.NullSubjectId);
126 //            }
127 //        });
128 //    }
129
130     protected abstract class ReadQuery<Result> implements Read<Result> {
131         protected Result result = null;
132
133         public abstract void run(ReadGraph graph) throws Throwable;
134
135         @Override
136         public Result perform(ReadGraph graph) {
137             try {
138                 run(graph);
139                 return result;
140             } catch(Throwable t) {
141                 if (DEBUG) {
142                     new Exception().printStackTrace();
143                     t.printStackTrace();
144                 }
145                 if (null == exception2)
146                     exception2 = t;
147                 return null;
148             }
149         }
150
151     }
152
153     protected abstract class AsyncReadQuery<Result> implements AsyncRead<Result> {
154         protected Result result = null;
155
156         public abstract void run(AsyncReadGraph graph) throws Throwable;
157
158         @Override
159         public void perform(AsyncReadGraph graph, AsyncProcedure<Result> procedure) {
160             try {
161                 run(graph);
162             } catch(Throwable t) {
163                 if (DEBUG) {
164                     new Exception().printStackTrace();
165                     t.printStackTrace();
166                 }
167                 if (null == exception2)
168                     exception2 = t;
169             }
170         }
171
172     }
173
174     protected abstract class TestReadRequest extends ReadQuery<Object> {
175     }
176
177     protected abstract class TestAsyncReadRequest extends AsyncReadQuery<Object> {
178
179                 @Override
180                 public int getFlags() {
181                         // TODO Auto-generated method stub
182                         return 0;
183                 }
184
185                 @Override
186                 public int threadHash() {
187                         // TODO Auto-generated method stub
188                         return 0;
189                 }
190
191     }
192
193     protected abstract class WriteOnlyQuery
194     extends WriteOnlyRequest
195     {
196
197         public abstract void run(WriteOnlyGraph g) throws Throwable;
198
199         /**
200          * Since some SimpleGraphRequest can only handle Exceptions, we need to wrap other Throwables inside Exceptions
201          */
202         @Override
203         public final void perform(WriteOnlyGraph g) {
204             try {
205                 run(g);
206             } catch(Throwable t) {
207                 new Exception().printStackTrace();
208                 t.printStackTrace();
209                 if (null == exception2)
210                     exception2 = t;
211                 throw new RuntimeException("Wrapping thrown non exception to exception.", t);
212             }
213         }
214         public void run(WriteGraph g) throws Throwable {
215             run((WriteOnlyGraph)g);
216         }
217
218     }
219
220     protected void checkException() throws DatabaseException {
221         if (exception2 != null)
222             if (exception2 instanceof DatabaseException)
223                 throw (DatabaseException)exception2;
224             else
225                 throw new DatabaseException(exception2);
226     }
227
228     protected boolean hasException() {
229         return null != exception2;
230     }
231
232     protected Throwable getException() {
233         return exception2;
234     }
235
236     protected static class ExitException extends SecurityException {
237         private static final long serialVersionUID = -1982617086752946683L;
238         public final int status;
239
240         public ExitException(int status) {
241             super("There is no escape!");
242             this.status = status;
243         }
244     }
245
246     private static class NoExitSecurityManager extends SecurityManager {
247         Session session;
248 //        Thread thread;
249         NoExitSecurityManager(Session session) {
250             this.session = session;
251 //            this.thread = Thread.currentThread();
252         }
253
254         public void dispose() {
255             session = null;
256         }
257
258         @Override
259         public void checkPermission(Permission perm) {
260             // allow anything.
261         }
262
263         @Override
264         public void checkPermission(Permission perm, Object context) {
265             // allow anything.
266         }
267
268         @Override
269         public void checkExit(int status) {
270             super.checkExit(status);
271             if(session != null) {
272                 try {
273                     session.getService(LifecycleSupport.class).close(0, true);
274                 } catch (ServiceNotFoundException e) {
275                     LOGGER.error("Failed to find LifecycleSupport service", e);
276                 } catch (DatabaseException e) {
277                     LOGGER.error("Failed to close database", e);
278                 }
279             }
280 //            if (!Thread.currentThread().equals(thread)) {
281 //                ThreadUtil.interruptThreadGroup("Query Thread Group");
282 //                ThreadUtil.interruptThreadGroup("Session Thread Group");
283 //                ThreadUtil.interruptThreadGroup("Connection Thread Group");
284 //                thread.interrupt();
285 //                throw new ExitException(status);
286 //            }
287         }
288     }
289
290     protected String getName() {
291         return getClass().getSimpleName();
292     }
293
294     protected static void fail() {
295         throw new AssertionError();
296     }
297
298     protected void fail(String cause) {
299         throw new AssertionError(cause);
300     }
301
302     protected void fail(String cause, Object a) {
303         if (a instanceof Throwable) {
304             Throwable t = (Throwable)a;
305             Throwable c = t.getCause();
306             if (null != c)
307                 throw new AssertionError(new Error(t.getMessage(), c));
308         }
309         throw new AssertionError(cause + " " + a);
310     }
311
312     protected void assertEquals(Object a, Object b) {
313         if(!a.equals(b))
314             throw new AssertionError();
315     }
316
317     protected void assertEquals(int a, int b) {
318         if(a != b)
319             throw new AssertionError();
320     }
321
322     protected void assertEquals(double a, double b, double tolerance) {
323         if(Math.abs(a - b) > tolerance)
324             throw new AssertionError();
325     }
326
327     protected void assertLess(double a, double b) {
328         if(a >= b)
329             throw new AssertionError(a + " is not less than " + b);
330     }
331
332     protected void assertLess(double a, double b, String info) {
333         if(a >= b) {
334             System.err.println("assertion info:\n" + info + "\n");
335             throw new AssertionError(a + " is not less than " + b);
336         }
337     }
338
339     protected void assertEquals(String a, String b) {
340         if(!a.equals(b))
341             throw new AssertionError();
342     }
343
344     protected void assertEquals(String message, int a, int b) {
345         if(a != b)
346             throw new AssertionError(message);
347     }
348
349     protected void assertEquals(String message, boolean a, boolean b) {
350         if(a != b)
351             throw new AssertionError(message);
352     }
353
354     protected void assertNotNull(Object a) {
355         if(a == null)
356             throw new AssertionError();
357     }
358
359     protected void assertNotNull(String message, Object a) {
360         if(a == null)
361             throw new AssertionError(message);
362     }
363
364     protected void assertTrue(String message, boolean a) {
365         if(!a)
366             throw new AssertionError(message);
367     }
368
369     protected void assertTrue(boolean a) {
370         if(!a)
371             throw new AssertionError();
372     }
373
374     protected void assertFalse(boolean a) {
375         if(a)
376             throw new AssertionError();
377     }
378
379     protected void assertFalse(String message, boolean a) {
380         if(a)
381             throw new AssertionError(message);
382     }
383 }