KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > rdql > test > QueryTestScripts


1 /*
2  * (c) Copyright 2001, 2002, 2003, 2004 2004, 2005 Hewlett-Packard Development Company, LP
3  * [See end of file]
4  * $Id: QueryTestScripts.java,v 1.21 2005/02/21 12:16:07 andy_seaborne Exp $
5  */

6
7
8 package com.hp.hpl.jena.rdql.test;
9
10 import java.io.* ;
11 //import java.util.* ;
12

13 import com.hp.hpl.jena.rdql.* ;
14 import com.hp.hpl.jena.util.FileManager;
15 import com.hp.hpl.jena.util.FileUtils;
16 import com.hp.hpl.jena.rdf.model.*;
17 import com.hp.hpl.jena.shared.*;
18
19 import junit.framework.*;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22
23 /** Test scripts for RDQL - loads, executes and checks (with JUnit) a collection of
24  * queries. New tests added as new featues appera and bugs are reported by
25  * adding new script files. This class need not change.
26  *
27  * @author Andy Seaborne
28  * @version $Id: QueryTestScripts.java,v 1.21 2005/02/21 12:16:07 andy_seaborne Exp $
29  */

30
31
32 public class QueryTestScripts extends TestSuite
33 {
34     static final String JavaDoc testSetName = "RDQL - Query - Scripts" ;
35     static final String JavaDoc directory = "testing/RDQL/" ;
36     FileManager fm = null ;
37     
38     public String JavaDoc basename = null ;
39     static public boolean printDetails = false ;
40     static public boolean displayTime = false ;
41
42     static protected Log log = LogFactory.getLog( QueryTestScripts.class );
43
44     static PrintWriter out = FileUtils.asPrintWriterUTF8(System.out) ;
45
46     public static TestSuite suite()
47     {
48         return new QueryTestScripts(testSetName) ;
49     }
50
51     
52     // Use to explicitly create tests.
53
public QueryTestScripts(String JavaDoc name)
54     {
55         super(name) ;
56         FileManager fm = new FileManager() ;
57         fm.addLocatorFile(directory) ;
58     }
59
60
61     static int testCounter = 0 ;
62     
63     public void addTest(TestItem item)
64     {
65         testCounter++ ;
66         addTest("BRQL-test-"+testCounter, item) ;
67     }
68
69     public void addTest(String JavaDoc testName, TestItem item)
70     {
71         addTest(testName, null, item) ;
72     }
73
74     
75     public void addTest(String JavaDoc testName, String JavaDoc directory,
76                         TestItem item)
77     {
78         addTest(null, testName, directory, item) ;
79     }
80
81     public void addTest(Model model, String JavaDoc testName, String JavaDoc directory,
82                         TestItem item)
83     {
84         TestCase test = new RDQLTest(model, testName, fm, item) ;
85         addTest(test) ;
86     }
87     
88     // One test. State and execution.
89

90     private static class RDQLTest extends TestCase
91     {
92         static int testCounter = 1 ;
93         static boolean printModelsOnFailure = false ;
94         
95         Model model ;
96         int testNumber = testCounter++ ;
97         TestItem testItem ;
98         FileManager fileManager ;
99
100         // If supplied with a model, the test will load that model with data from the source
101
// If no model is supplied one is created or attached (e.g. a database)
102

103         RDQLTest(Model m, String JavaDoc testName, FileManager fm, TestItem t)
104         {
105             super(testName) ;
106             model = m ;
107             fileManager = fm ;
108             testItem = t ;
109         }
110         
111         protected void runTest() throws Throwable JavaDoc
112         {
113             Query query = null ;
114             try {
115                 if ( printDetails )
116                 {
117                     if ( testNumber != 1 )
118                     {
119                         out.println() ;
120                         out.println("------------------------------------------------------------------------") ;
121                         out.println() ;
122                     }
123                     out.println("Test "+testNumber+" :: QueryFile="+testItem.getQueryFile()+", DataFile="+testItem.getDataFile()+", ResultsFile="+testItem.getResultFile()) ;
124                 }
125
126                 String JavaDoc queryString = fileManager.readWholeFileAsUTF8(testItem.getQueryFile()) ;
127
128                 if ( printDetails ) {
129                     out.println("Query:") ;
130                     out.println(queryString);
131                     if ( ! queryString.endsWith("\n") )
132                         out.println() ;
133                     out.flush() ;
134                 }
135
136                 long startTime = System.currentTimeMillis();
137                 
138                 try {
139                     query = new Query(queryString) ;
140                 }
141                 catch (QueryException qEx)
142                 {
143                     query = null ;
144                     out.flush() ;
145                     assertFalse("Parse failure: "+qEx.getMessage(), true) ;
146                     // Test failure.
147
throw qEx ;
148                 }
149                 
150                 if ( printDetails ) {
151                     out.println("Parsed query:") ;
152                     out.println(query.toString()) ;
153                     out.flush() ;
154                 }
155
156                 if ( model == null )
157                 {
158                     if ( testItem.getDataFile() != null && ! testItem.getDataFile().equals("") ) {
159                         long startLoadTime = System.currentTimeMillis();
160                         Model m = fileManager.loadModel(testItem.getDataFile()) ;
161                         query.setSource(m) ;
162                         query.loadTime = System.currentTimeMillis() - startLoadTime ;
163                     }
164                 } else
165                 {
166                     // Model supplied : ensure empty then load it.
167
emptyModel(model) ;
168                     
169                     String JavaDoc data = null ;
170                     if ( testItem.getDataFile() != null && ! testItem.getDataFile().equals("") )
171                         data = testItem.getDataFile() ;
172                     if ( data == null )
173                         data = query.getSourceURL() ;
174
175                     try {
176                         long startLoadTime = System.currentTimeMillis();
177                         query.setSource(fileManager.readModel(model, data)) ;
178                         query.loadTime = System.currentTimeMillis() - startLoadTime ;
179                     } catch (JenaException ex)
180                     {
181                         log.warn("Problems loading data for: "+data) ;
182                     }
183                 }
184
185                 QueryExecution qe = new QueryEngine(query) ;
186                 qe.init() ;
187                 runTestSelect(query, qe, startTime) ;
188             }
189             catch (IOException ioEx){ out.println("IOException: "+ioEx) ; ioEx.printStackTrace(out) ; out.flush() ; }
190             //catch (JenaException rdfEx) { out.println("JenaException: "+rdfEx) ; rdfEx.printStackTrace(out) ; out.flush() ; }
191
catch (Exception JavaDoc ex)
192             {
193                 out.println("Exception: "+ex) ;
194                 ex.printStackTrace(out) ;
195                 out.flush() ;
196                 Assert.assertTrue("Exception: "+testItem.getQueryFile(),false) ;
197             }
198             finally
199             {
200                 if ( model == null && query != null && query.getSource() != null )
201                     query.getSource().close() ;
202                 out.flush() ;
203             }
204         }
205         
206         void runTestSelect(Query query, QueryExecution qe, long startTime) throws Exception JavaDoc
207         {
208             // Do the query!
209
QueryResults resultsActual = qe.exec() ;
210             
211             long finishTime = System.currentTimeMillis();
212             long totalTime = finishTime-startTime ;
213             
214             // Turn into a resettable version
215
QueryResultsRewindable results = new QueryResultsMem(resultsActual) ;
216             resultsActual.close() ;
217             resultsActual = null ;
218             
219             boolean testingResults = ( testItem.getResultFile() != null && !testItem.getResultFile().equals("") ) ;
220             
221             if ( printDetails )
222             {
223                 QueryResultsFormatter fmt = new QueryResultsFormatter(results) ;
224                 fmt.printAll(out) ;
225                 // Must be after the results have been processed
226
out.println() ;
227                 fmt.close() ;
228             }
229             
230             if ( printDetails && displayTime )
231             {
232                 out.println() ;
233                 out.println("Query parse: "+formatlong(query.parseTime) +" ms") ;
234                 out.println("Query build: "+formatlong(query.buildTime) +" ms") ;
235                 out.println("Data load time: "+formatlong(query.loadTime) +" ms") ;
236                 out.println("Query execute: "+formatlong(query.executeTime) +" ms") ;
237                 out.println("Query misc: "+formatlong(totalTime-query.parseTime-query.buildTime-query.loadTime-query.executeTime)+" ms") ;
238                 out.println("Query total: "+formatlong(totalTime) +" ms") ;
239                 out.flush() ;
240             }
241             
242             
243             if ( testingResults )
244             {
245                 try {
246                     Model tmp = fileManager.loadModel(testItem.getResultFile()) ;
247                     
248                     QueryResultsMem qr1 = new QueryResultsMem(results) ;
249                     QueryResultsMem qr2 = new QueryResultsMem(tmp) ;
250
251                     if ( !resultSetEquivalent(qr1, qr2) )
252                     {
253                         out.println() ;
254                         out.println("=======================================") ;
255                         out.println("Failure: "+testItem.getQueryFile()) ;
256                         out.println("Got: "+qr1.size()+" ----------------------------------") ;
257                         qr1.reset() ;
258                         
259                         QueryResultsFormatter qrFmt1 = new QueryResultsFormatter(qr1) ;
260                         qrFmt1.dump(out, false) ;
261                         qr1.reset() ;
262                         
263                         if ( printModelsOnFailure )
264                         {
265                             out.println("---------------------------------------") ;
266                             qrFmt1.toModel().write(out, "N3") ;
267                             qr1.reset() ;
268                         }
269                         out.flush() ;
270                         
271                         QueryResultsFormatter qrFmt2 = new QueryResultsFormatter(qr2) ;
272                         
273                         out.println("Expected: "+qr2.size()+" -----------------------------") ;
274                         qr2.reset() ;
275                         qrFmt2.dump(out, false) ;
276                         qr2.reset() ;
277                         
278                         if ( printModelsOnFailure )
279                         {
280                             out.println("---------------------------------------") ;
281                             qrFmt2.toModel().write(out, "N3") ;
282                             qr2.reset() ;
283                         }
284                         out.println() ;
285                         out.flush() ;
286     
287                         qrFmt1.close() ;
288                         qrFmt2.close() ;
289                         qr1.close() ;
290                         qr2.close() ;
291                                 
292                         Assert.assertTrue("Results do not match: "+testItem.getQueryFile(),false) ;
293                     }
294                     //else
295
// passed
296
} catch (Exception JavaDoc ex)
297                 {
298                     log.warn("Exception in result testing", ex) ;
299                     Assert.fail("Exception in result testing: "+ex) ;
300                 }
301             }
302             results.close() ;
303         }
304         
305         /** Are two result sets the same (isomorphic)?
306         *
307         * @param irs1
308         * @param irs2
309         * @return boolean
310         */

311
312        static public boolean resultSetEquivalent(
313            QueryResults rs1,
314            QueryResults rs2)
315        {
316            QueryResultsFormatter fmt1 = new QueryResultsFormatter(rs1) ;
317            Model model1 = fmt1.toModel() ;
318
319            QueryResultsFormatter fmt2 = new QueryResultsFormatter(rs2) ;
320            Model model2 = fmt2.toModel() ;
321
322            return model1.isIsomorphicWith(model2) ;
323        }
324
325
326         
327         void runTestConstruct(Query query, QueryExecution qe, long startTime) throws Exception JavaDoc
328         {
329         }
330         
331         void runTestDescribe(Query query, QueryExecution qe, long startTime) throws Exception JavaDoc
332         {
333         }
334         
335         void runTestAsk(Query query, QueryExecution qe, long startTime) throws Exception JavaDoc
336         {
337         }
338         
339
340     }
341
342     public static void emptyModel(Model model)
343     {
344         if ( model == null )
345             return ;
346         try {
347             StmtIterator sIter = model.listStatements();
348             while (sIter.hasNext()) {
349                 sIter.nextStatement();
350                 sIter.remove();
351             }
352             sIter.close() ;
353         } catch ( JenaException rdfEx)
354         { log.error( "Failed to empty model (com.hp.hpl.jena.rdf.query.Test.QueryTest.emptyModel)", rdfEx) ; }
355     }
356
357     static String JavaDoc convertFilename(String JavaDoc filename, String JavaDoc directory)
358     {
359         if ( filename == null )
360             return null;
361         if ( filename.startsWith("file:"))
362             filename = filename.substring("file:".length()) ;
363         if ( directory != null && ! filename.startsWith("/"))
364             filename = directory+"/"+filename ;
365         return filename ;
366     }
367
368     // Copied from rdfquery. Share it!
369
static String JavaDoc formatlong(long x) {
370         StringBuffer JavaDoc sbuff = new StringBuffer JavaDoc() ;
371         sbuff.append(Long.toString(x)) ;
372         for ( int i = sbuff.length() ; i < 4 ; i++ ) sbuff.append(" ") ;
373         return sbuff.toString() ;
374     }
375
376 }
377
378 /*
379  * (c) Copyright 2001, 2002, 2003, 2004 2004, 2005 Hewlett-Packard Development Company, LP
380  * All rights reserved.
381  *
382  * Redistribution and use in source and binary forms, with or without
383  * modification, are permitted provided that the following conditions
384  * are met:
385  * 1. Redistributions of source code must retain the above copyright
386  * notice, this list of conditions and the following disclaimer.
387  * 2. Redistributions in binary form must reproduce the above copyright
388  * notice, this list of conditions and the following disclaimer in the
389  * documentation and/or other materials provided with the distribution.
390  * 3. The name of the author may not be used to endorse or promote products
391  * derived from this software without specific prior written permission.
392  *
393  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
394  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
395  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
396  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
397  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
398  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
399  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
400  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
401  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
402  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
403  */

404
Popular Tags