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