KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > regexp > internal > RETest


1 package com.sun.org.apache.regexp.internal;
2
3 /*
4  * ====================================================================
5  *
6  * The Apache Software License, Version 1.1
7  *
8  * Copyright (c) 1999 The Apache Software Foundation. All rights
9  * reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  *
15  * 1. Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  *
18  * 2. Redistributions in binary form must reproduce the above copyright
19  * notice, this list of conditions and the following disclaimer in
20  * the documentation and/or other materials provided with the
21  * distribution.
22  *
23  * 3. The end-user documentation included with the redistribution, if
24  * any, must include the following acknowlegement:
25  * "This product includes software developed by the
26  * Apache Software Foundation (http://www.apache.org/)."
27  * Alternately, this acknowlegement may appear in the software itself,
28  * if and wherever such third-party acknowlegements normally appear.
29  *
30  * 4. The names "The Jakarta Project", "Jakarta-Regexp", and "Apache Software
31  * Foundation" must not be used to endorse or promote products derived
32  * from this software without prior written permission. For written
33  * permission, please contact apache@apache.org.
34  *
35  * 5. Products derived from this software may not be called "Apache"
36  * nor may "Apache" appear in their names without prior written
37  * permission of the Apache Group.
38  *
39  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
40  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
41  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
42  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
45  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
46  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
47  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
48  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
49  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This software consists of voluntary contributions made by many
54  * individuals on behalf of the Apache Software Foundation. For more
55  * information on the Apache Software Foundation, please see
56  * <http://www.apache.org/>.
57  *
58  */

59
60 import java.io.*;
61
62 /**
63  * Data driven (and optionally interactive) testing harness to exercise regular
64  * expression compiler and matching engine.
65  *
66  * @author <a HREF="mailto:jonl@muppetlabs.com">Jonathan Locke</a>
67  * @author <a HREF="mailto:jon@latchkey.com">Jon S. Stevens</a>
68  * @version $Id: RETest.java,v 1.2 2000/04/30 20:42:35 jon Exp $
69  */

70 public class RETest
71 {
72     // Construct a matcher and a debug compiler
73
RE r = new RE();
74     REDebugCompiler compiler = new REDebugCompiler();
75
76     // True if we want to see output from success cases
77
static final boolean showSuccesses = false;
78
79     /**
80      * Main program entrypoint. If an argument is given, it will be compiled
81      * and interactive matching will ensue. If no argument is given, the
82      * file RETest.txt will be used as automated testing input.
83      * @param arg Command line arguments (optional regular expression)
84     */

85     public static void _main(String JavaDoc[] arg)
86     {
87         try
88         {
89             //new RETest(arg);
90
test();
91         }
92         catch (Exception JavaDoc e)
93         {
94             e.printStackTrace();
95         }
96     }
97
98     /**
99      * Testing entrypoint.
100      * @param arg Command line arguments
101      * @exception Exception thrown in case of error
102     */

103     public static boolean test() throws Exception JavaDoc
104     {
105         RETest test = new RETest();
106         test.runAutomatedTests("docs/RETest.txt");
107         return test.failures == 0;
108     }
109
110     /**
111      * Constructor
112     */

113     public RETest()
114     {
115     }
116
117     /**
118      * Constructor for test
119      * @param arg Command line arguments
120     */

121     public RETest(String JavaDoc[] arg)
122     {
123         try
124         {
125             // Run interactive tests against a single regexp
126
if (arg.length == 2)
127             {
128                 runInteractiveTests(arg[1]);
129             }
130             else if (arg.length == 1)
131             {
132                 // Run automated tests
133
runAutomatedTests(arg[0]);
134             }
135             else
136             {
137                 System.out.println ( "Usage: RETest ([-i] [regex]) ([/path/to/testfile.txt])" );
138             }
139         }
140         catch (Exception JavaDoc e)
141         {
142             e.printStackTrace();
143         }
144     }
145
146     /**
147      * Compile and test matching against a single expression
148      * @param expr Expression to compile and test
149     */

150     void runInteractiveTests(String JavaDoc expr)
151     {
152         try
153         {
154             // Compile expression
155
r.setProgram(compiler.compile(expr));
156
157             // Show expression
158
say("\n" + expr + "\n");
159
160             // Show program for compiled expression
161
compiler.dumpProgram(new PrintWriter(System.out));
162             
163             // Test matching against compiled expression
164
while (true)
165             {
166                 // Read from keyboard
167
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
168                 System.out.print("> ");
169                 System.out.flush();
170                 String JavaDoc match = br.readLine();
171
172                 // Try a match against the keyboard input
173
if (r.match(match))
174                 {
175                     say("Match successful.");
176                 }
177                 else
178                 {
179                     say("Match failed.");
180                 }
181
182                 // Show subparen registers
183
showParens(r);
184             }
185         }
186         catch (Exception JavaDoc e)
187         {
188             say("Error: " + e.toString());
189             e.printStackTrace();
190         }
191     }
192
193     /**
194      * Exit with a fatal error.
195      * @param s Last famous words before exiting
196     */

197     void die(String JavaDoc s)
198     {
199         say("FATAL ERROR: " + s);
200         System.exit(0);
201     }
202
203     /**
204      * Fail with an error
205      * @param s Failure description
206     */

207     void fail(String JavaDoc s)
208     {
209         failures++;
210         say("\n");
211         say("*******************************************************");
212         say("********************* FAILURE! **********************");
213         say("*******************************************************");
214         say("\n");
215         say(s);
216         say("");
217         compiler.dumpProgram(new PrintWriter(System.out));
218         say("\n");
219     }
220
221     /**
222      * Show a success
223      * @param s Success story
224     */

225     void success(String JavaDoc s)
226     {
227         if (showSuccesses)
228         {
229             show();
230             say("Success: " + s);
231         }
232     }
233
234     /**
235      * Say something to standard out
236      * @param s What to say
237     */

238     void say(String JavaDoc s)
239     {
240         System.out.println (s);
241     }
242
243     /**
244      * Show an expression
245     */

246     void show()
247     {
248         say("\n-----------------------\n");
249         say("Expression #" + (n) + " \"" + expr + "\" ");
250     }
251
252     /**
253      * Dump parenthesized subexpressions found by a regular expression matcher object
254      * @param r Matcher object with results to show
255     */

256     void showParens(RE r)
257     {
258         // Loop through each paren
259
for (int i = 0; i < r.getParenCount(); i++)
260         {
261             // Show paren register
262
say("$" + i + " = " + r.getParen(i));
263         }
264     }
265
266     // Pre-compiled regular expression "a*b"
267
char[] re1Instructions =
268     {
269         0x007c, 0x0000, 0x001a, 0x007c, 0x0000, 0x000d, 0x0041,
270         0x0001, 0x0004, 0x0061, 0x007c, 0x0000, 0x0003, 0x0047,
271         0x0000, 0xfff6, 0x007c, 0x0000, 0x0003, 0x004e, 0x0000,
272         0x0003, 0x0041, 0x0001, 0x0004, 0x0062, 0x0045, 0x0000,
273         0x0000,
274     };
275
276     REProgram re1 = new REProgram(re1Instructions);
277
278     /*
279      * Current expression and number in automated test
280     */

281     String JavaDoc expr;
282     int n = 0;
283
284     /*
285      * Count of failures in automated test
286      */

287     int failures = 0;
288
289     /**
290      * Run automated tests in RETest.txt file (from Perl 4.0 test battery)
291     * @exception Exception thrown in case of error
292     */

293     void runAutomatedTests(String JavaDoc testDocument) throws Exception JavaDoc
294     {
295         long ms = System.currentTimeMillis();
296
297         // Simple test of pre-compiled regular expressions
298
RE r = new RE(re1);
299         say("a*b");
300         say("aaaab = " + r.match("aaab"));
301         showParens(r);
302         say("b = " + r.match("b"));
303         showParens(r);
304         say("c = " + r.match("c"));
305         showParens(r);
306         say("ccccaaaaab = " + r.match("ccccaaaaab"));
307         showParens(r);
308
309         r = new RE("a*b");
310         String JavaDoc[] s = r.split("xxxxaabxxxxbyyyyaaabzzz");
311         r = new RE("x+");
312         s = r.grep(s);
313         for (int i = 0; i < s.length; i++)
314         {
315             System.out.println ("s[" + i + "] = " + s[i]);
316         }
317
318         r = new RE("a*b");
319         String JavaDoc s1 = r.subst("aaaabfooaaabgarplyaaabwackyb", "-");
320         System.out.println ("s = " + s1);
321
322         // Test from script file
323
File testInput = new File(testDocument);
324         if (! testInput.exists())
325             throw new Exception JavaDoc ("Could not find: " + testDocument);
326         BufferedReader br = new BufferedReader(new FileReader(testInput));
327         try
328         {
329             // While input is available, parse lines
330
while (br.ready())
331             {
332                 // Find next re test case
333
String JavaDoc number = "";
334                 String JavaDoc yesno;
335                 while (br.ready())
336                 {
337                     number = br.readLine();
338                     if (number == null)
339                     {
340                         break;
341                     }
342                     number = number.trim();
343                     if (number.startsWith("#"))
344                     {
345                         break;
346                     }
347                     if (!number.equals(""))
348                     {
349                         System.out.println ("Script error. Line = " + number);
350                         System.exit(0);
351                     }
352                 }
353
354                 // Are we done?
355
if (!br.ready())
356                 {
357                     break;
358                 }
359
360                 // Get expression
361
expr = br.readLine();
362                 n++;
363                 say("");
364                 say(n + ". " + expr);
365                 say("");
366
367                 // Compile it
368
try
369                 {
370                     r.setProgram(compiler.compile(expr));
371                 }
372
373                 // Some expressions *should* cause exceptions to be thrown
374
catch (Exception JavaDoc e)
375                 {
376                     // Get expected result
377
yesno = br.readLine().trim();
378
379                     // If it was supposed to be an error, report success and continue
380
if (yesno.equals("ERR"))
381                     {
382                         say(" Match: ERR");
383                         success("Produces an error (" + e.toString() + "), as expected.");
384                         continue;
385                     }
386
387                     // Wasn't supposed to be an error
388
fail("Produces the unexpected error \"" + e.getMessage() + "\"");
389                 }
390                 catch (Error JavaDoc e)
391                 {
392                     // Internal error happened
393
fail("Compiler threw fatal error \"" + e.getMessage() + "\"");
394                     e.printStackTrace();
395                 }
396
397                 // Get string to match against
398
String JavaDoc matchAgainst = br.readLine().trim();
399                 say(" Match against: '" + matchAgainst + "'");
400
401                 // Expression didn't cause an expected error
402
if (matchAgainst.equals("ERR"))
403                 {
404                     fail("Was expected to be an error, but wasn't.");
405                     continue;
406                 }
407
408                 // Try matching
409
try
410                 {
411                     // Match against the string
412
boolean b = r.match(matchAgainst);
413
414                     // Get expected result
415
yesno = br.readLine().trim();
416
417                     // If match succeeded
418
if (b)
419                     {
420                         // Status
421
say(" Match: YES");
422
423                         // Match wasn't supposed to succeed
424
if (yesno.equals("NO"))
425                         {
426                             fail("Matched \"" + matchAgainst + "\", when not expected to.");
427                         }
428                         else
429                         if (yesno.equals("YES"))
430                         {
431                             // Match succeeded as expected
432
success("Matched \"" + matchAgainst + "\", as expected:");
433
434                             // Show subexpression registers
435
if (showSuccesses)
436                             {
437                                 showParens(r);
438                             }
439
440                             say(" Paren count: " + r.getParenCount());
441
442                             // Check registers against expected contents
443
for (int p = 0; p < r.getParenCount(); p++)
444                             {
445                                 // Get next register
446
String JavaDoc register = br.readLine().trim();
447                                 say(" Paren " + p + " : " + r.getParen(p));
448
449                                 // Compare expected result with actual
450
if (!register.equals(r.getParen(p)))
451                                 {
452                                     // Register isn't what it was supposed to be
453
fail("Register " + p + " should be = \"" + register + "\", but is \"" + r.getParen(p) + "\" instead.");
454                                 }
455                             }
456                         }
457                         else
458                         {
459                             // Bad test script
460
die("Test script error!");
461                         }
462                     }
463                     else
464                     {
465                         // Status
466
say(" Match: NO");
467
468                         // Match failed
469
if (yesno.equals("YES"))
470                         {
471                             // Should have failed
472
fail("Did not match \"" + matchAgainst + "\", when expected to.");
473                         }
474                         else
475                         if (yesno.equals("NO"))
476                         {
477                             // Should have failed
478
success("Did not match \"" + matchAgainst + "\", as expected.");
479                         }
480                         else
481                         {
482                             // Bad test script
483
die("Test script error!");
484                         }
485                     }
486                 }
487
488                 // Matcher blew it
489
catch (Exception JavaDoc e)
490                 {
491                     fail("Matcher threw exception: " + e.toString());
492                     e.printStackTrace();
493                 }
494
495                 // Internal error
496
catch (Error JavaDoc e)
497                 {
498                     fail("Matcher threw fatal error \"" + e.getMessage() + "\"");
499                     e.printStackTrace();
500                 }
501             }
502         }
503         finally
504         {
505             br.close();
506         }
507
508         // Show match time
509
System.out.println ("\n\nMatch time = " + (System.currentTimeMillis() - ms) + " ms.");
510
511         // Print final results
512
System.out.println ("\nTests complete. " + n + " tests, " + failures + " failure(s).");
513     }
514 }
515
Popular Tags