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