KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > BuildFileTest


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */

17
18 package org.apache.tools.ant;
19
20 import junit.framework.TestCase;
21 import org.apache.tools.ant.Project;
22 import java.io.File JavaDoc;
23 import java.io.PrintStream JavaDoc;
24 import java.net.URL JavaDoc;
25
26 /**
27  * A BuildFileTest is a TestCase which executes targets from an Ant buildfile
28  * for testing.
29  *
30  * This class provides a number of utility methods for particular build file
31  * tests which extend this class.
32  *
33  */

34 public abstract class BuildFileTest extends TestCase {
35
36     protected Project project;
37
38     private StringBuffer JavaDoc logBuffer;
39     private StringBuffer JavaDoc fullLogBuffer;
40     private StringBuffer JavaDoc outBuffer;
41     private StringBuffer JavaDoc errBuffer;
42     private BuildException buildException;
43
44     /**
45      * Constructor for the BuildFileTest object
46      *
47      *@param name string to pass up to TestCase constructor
48      */

49     public BuildFileTest(String JavaDoc name) {
50         super(name);
51     }
52
53     /**
54      * run a target, expect for any build exception
55      *
56      *@param target target to run
57      *@param cause information string to reader of report
58      */

59     protected void expectBuildException(String JavaDoc target, String JavaDoc cause) {
60         expectSpecificBuildException(target, cause, null);
61     }
62
63     /**
64      * Assert that only the given message has been logged with a
65      * priority >= INFO when running the given target.
66      */

67     protected void expectLog(String JavaDoc target, String JavaDoc log) {
68         executeTarget(target);
69         String JavaDoc realLog = getLog();
70         assertEquals(log, realLog);
71     }
72
73     /**
74      * Assert that the given substring is in the log messages
75      */

76
77     protected void assertLogContaining(String JavaDoc substring) {
78         String JavaDoc realLog = getLog();
79         assertTrue("expecting log to contain \"" + substring + "\" log was \""
80                    + realLog + "\"",
81                    realLog.indexOf(substring) >= 0);
82     }
83
84     /**
85      * Assert that the given message has been logged with a priority
86      * >= INFO when running the given target.
87      */

88     protected void expectLogContaining(String JavaDoc target, String JavaDoc log) {
89         executeTarget(target);
90         assertLogContaining(log);
91     }
92
93     /**
94      * Gets the log the BuildFileTest object.
95      * only valid if configureProject() has
96      * been called.
97      * @pre logBuffer!=null
98      * @return The log value
99      */

100     protected String JavaDoc getLog() {
101         return logBuffer.toString();
102     }
103
104     /**
105      * Assert that the given message has been logged with a priority
106      * >= DEBUG when running the given target.
107      */

108     protected void expectDebuglog(String JavaDoc target, String JavaDoc log) {
109         executeTarget(target);
110         String JavaDoc realLog = getFullLog();
111         assertEquals(log, realLog);
112     }
113
114     /**
115      * Gets the log the BuildFileTest object.
116      * only valid if configureProject() has
117      * been called.
118      * @pre fullLogBuffer!=null
119      * @return The log value
120      */

121     protected String JavaDoc getFullLog() {
122         return fullLogBuffer.toString();
123     }
124
125     /**
126      * execute the target, verify output matches expectations
127      *
128      *@param target target to execute
129      *@param output output to look for
130      */

131
132     protected void expectOutput(String JavaDoc target, String JavaDoc output) {
133         executeTarget(target);
134         String JavaDoc realOutput = getOutput();
135         assertEquals(output, realOutput.trim());
136     }
137
138     /**
139      * execute the target, verify output matches expectations
140      * and that we got the named error at the end
141      *@param target target to execute
142      *@param output output to look for
143      *@param error Description of Parameter
144      */

145
146     protected void expectOutputAndError(String JavaDoc target, String JavaDoc output, String JavaDoc error) {
147         executeTarget(target);
148         String JavaDoc realOutput = getOutput();
149         assertEquals(output, realOutput);
150         String JavaDoc realError = getError();
151         assertEquals(error, realError);
152     }
153
154     protected String JavaDoc getOutput() {
155         return cleanBuffer(outBuffer);
156     }
157
158     protected String JavaDoc getError() {
159         return cleanBuffer(errBuffer);
160     }
161
162     protected BuildException getBuildException() {
163         return buildException;
164     }
165
166     private String JavaDoc cleanBuffer(StringBuffer JavaDoc buffer) {
167         StringBuffer JavaDoc cleanedBuffer = new StringBuffer JavaDoc();
168         boolean cr = false;
169         for (int i = 0; i < buffer.length(); i++) {
170             char ch = buffer.charAt(i);
171             if (ch == '\r') {
172                 cr = true;
173                 continue;
174             }
175
176             if (!cr) {
177                 cleanedBuffer.append(ch);
178             } else {
179                 cleanedBuffer.append(ch);
180             }
181         }
182         return cleanedBuffer.toString();
183     }
184
185     /**
186      * set up to run the named project
187      *
188      * @param filename name of project file to run
189      */

190     protected void configureProject(String JavaDoc filename) throws BuildException {
191         configureProject(filename, Project.MSG_DEBUG);
192     }
193
194     /**
195      * set up to run the named project
196      *
197      * @param filename name of project file to run
198      */

199     protected void configureProject(String JavaDoc filename, int logLevel)
200         throws BuildException {
201         logBuffer = new StringBuffer JavaDoc();
202         fullLogBuffer = new StringBuffer JavaDoc();
203         project = new Project();
204         project.init();
205         project.setUserProperty( "ant.file" , new File JavaDoc(filename).getAbsolutePath() );
206         project.addBuildListener(new AntTestListener(logLevel));
207         ProjectHelper.configureProject(project, new File JavaDoc(filename));
208     }
209
210     /**
211      * execute a target we have set up
212      * @pre configureProject has been called
213      * @param targetName target to run
214      */

215     protected void executeTarget(String JavaDoc targetName) {
216         PrintStream JavaDoc sysOut = System.out;
217         PrintStream JavaDoc sysErr = System.err;
218         try {
219             sysOut.flush();
220             sysErr.flush();
221             outBuffer = new StringBuffer JavaDoc();
222             PrintStream JavaDoc out = new PrintStream JavaDoc(new AntOutputStream(outBuffer));
223             System.setOut(out);
224             errBuffer = new StringBuffer JavaDoc();
225             PrintStream JavaDoc err = new PrintStream JavaDoc(new AntOutputStream(errBuffer));
226             System.setErr(err);
227             logBuffer = new StringBuffer JavaDoc();
228             fullLogBuffer = new StringBuffer JavaDoc();
229             buildException = null;
230             project.executeTarget(targetName);
231         } finally {
232             System.setOut(sysOut);
233             System.setErr(sysErr);
234         }
235
236     }
237
238     /**
239      * Get the project which has been configured for a test.
240      *
241      * @return the Project instance for this test.
242      */

243     protected Project getProject() {
244         return project;
245     }
246
247     /**
248      * get the directory of the project
249      * @return the base dir of the project
250      */

251     protected File JavaDoc getProjectDir() {
252         return project.getBaseDir();
253     }
254
255     /**
256      * run a target, wait for a build exception
257      *
258      *@param target target to run
259      *@param cause information string to reader of report
260      *@param msg the message value of the build exception we are waiting for
261               set to null for any build exception to be valid
262      */

263     protected void expectSpecificBuildException(String JavaDoc target, String JavaDoc cause, String JavaDoc msg) {
264         try {
265             executeTarget(target);
266         } catch (org.apache.tools.ant.BuildException ex) {
267             buildException = ex;
268             if ((null != msg) && (!ex.getMessage().equals(msg))) {
269                 fail("Should throw BuildException because '" + cause
270                         + "' with message '" + msg
271                         + "' (actual message '" + ex.getMessage() + "' instead)");
272             }
273             return;
274         }
275         fail("Should throw BuildException because: " + cause);
276     }
277
278     /**
279      * run a target, expect an exception string
280      * containing the substring we look for (case sensitive match)
281      *
282      *@param target target to run
283      *@param cause information string to reader of report
284      *@param contains substring of the build exception to look for
285      */

286     protected void expectBuildExceptionContaining(String JavaDoc target, String JavaDoc cause, String JavaDoc contains) {
287         try {
288             executeTarget(target);
289         } catch (org.apache.tools.ant.BuildException ex) {
290             buildException = ex;
291             if ((null != contains) && (ex.getMessage().indexOf(contains) == -1)) {
292                 fail("Should throw BuildException because '" + cause + "' with message containing '" + contains + "' (actual message '" + ex.getMessage() + "' instead)");
293             }
294             return;
295         }
296         fail("Should throw BuildException because: " + cause);
297     }
298
299
300     /**
301      * call a target, verify property is as expected
302      *
303      * @param target build file target
304      * @param property property name
305      * @param value expected value
306      */

307
308     protected void expectPropertySet(String JavaDoc target, String JavaDoc property, String JavaDoc value) {
309         executeTarget(target);
310         assertPropertyEquals(property, value);
311     }
312
313     /**
314      * assert that a property equals a value; comparison is case sensitive.
315      * @param property property name
316      * @param value expected value
317      */

318     protected void assertPropertyEquals(String JavaDoc property, String JavaDoc value) {
319         String JavaDoc result = project.getProperty(property);
320         assertEquals("property " + property,value,result);
321     }
322
323     /**
324      * assert that a property equals &quot;true&quot;
325      * @param property property name
326      */

327     protected void assertPropertySet(String JavaDoc property) {
328         assertPropertyEquals(property, "true");
329     }
330
331     /**
332      * assert that a property is null
333      * @param property property name
334      */

335     protected void assertPropertyUnset(String JavaDoc property) {
336         assertPropertyEquals(property, null);
337     }
338
339
340     /**
341      * call a target, verify named property is "true".
342      *
343      * @param target build file target
344      * @param property property name
345      */

346     protected void expectPropertySet(String JavaDoc target, String JavaDoc property) {
347         expectPropertySet(target, property, "true");
348     }
349
350
351     /**
352      * call a target, verify property is null
353      * @param target build file target
354      * @param property property name
355      */

356     protected void expectPropertyUnset(String JavaDoc target, String JavaDoc property) {
357         expectPropertySet(target, property, null);
358     }
359
360     /**
361      * Retrieve a resource from the caller classloader to avoid
362      * assuming a vm working directory. The resource path must be
363      * relative to the package name or absolute from the root path.
364      * @param resource the resource to retrieve its url.
365      * @throws AssertionFailureException if resource is not found.
366      */

367     protected URL JavaDoc getResource(String JavaDoc resource){
368         URL JavaDoc url = getClass().getResource(resource);
369         assertNotNull("Could not find resource :" + resource, url);
370         return url;
371     }
372
373     /**
374      * an output stream which saves stuff to our buffer.
375      */

376     private static class AntOutputStream extends java.io.OutputStream JavaDoc {
377         private StringBuffer JavaDoc buffer;
378
379         public AntOutputStream( StringBuffer JavaDoc buffer ) {
380             this.buffer = buffer;
381         }
382
383         public void write(int b) {
384             buffer.append((char)b);
385         }
386     }
387
388     /**
389      * our own personal build listener
390      */

391     private class AntTestListener implements BuildListener {
392         private int logLevel;
393
394         /**
395          * Constructs a test listener which will ignore log events
396          * above the given level
397          */

398         public AntTestListener(int logLevel) {
399             this.logLevel = logLevel;
400         }
401
402         /**
403          * Fired before any targets are started.
404          */

405         public void buildStarted(BuildEvent event) {
406         }
407
408         /**
409          * Fired after the last target has finished. This event
410          * will still be thrown if an error occured during the build.
411          *
412          * @see BuildEvent#getException()
413          */

414         public void buildFinished(BuildEvent event) {
415         }
416
417         /**
418          * Fired when a target is started.
419          *
420          * @see BuildEvent#getTarget()
421          */

422         public void targetStarted(BuildEvent event) {
423             //System.out.println("targetStarted " + event.getTarget().getName());
424
}
425
426         /**
427          * Fired when a target has finished. This event will
428          * still be thrown if an error occured during the build.
429          *
430          * @see BuildEvent#getException()
431          */

432         public void targetFinished(BuildEvent event) {
433             //System.out.println("targetFinished " + event.getTarget().getName());
434
}
435
436         /**
437          * Fired when a task is started.
438          *
439          * @see BuildEvent#getTask()
440          */

441         public void taskStarted(BuildEvent event) {
442             //System.out.println("taskStarted " + event.getTask().getTaskName());
443
}
444
445         /**
446          * Fired when a task has finished. This event will still
447          * be throw if an error occured during the build.
448          *
449          * @see BuildEvent#getException()
450          */

451         public void taskFinished(BuildEvent event) {
452             //System.out.println("taskFinished " + event.getTask().getTaskName());
453
}
454
455         /**
456          * Fired whenever a message is logged.
457          *
458          * @see BuildEvent#getMessage()
459          * @see BuildEvent#getPriority()
460          */

461         public void messageLogged(BuildEvent event) {
462             if (event.getPriority() > logLevel) {
463                 // ignore event
464
return;
465             }
466
467             if (event.getPriority() == Project.MSG_INFO ||
468                 event.getPriority() == Project.MSG_WARN ||
469                 event.getPriority() == Project.MSG_ERR) {
470                 logBuffer.append(event.getMessage());
471             }
472             fullLogBuffer.append(event.getMessage());
473
474         }
475     }
476
477
478 }
479
Popular Tags