KickJava   Java API By Example, From Geeks To Geeks.

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


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 java.io.File JavaDoc;
21 import java.io.PrintStream JavaDoc;
22 import java.net.URL JavaDoc;
23
24 import junit.framework.TestCase;
25
26 /**
27  * (note: name changed from BuildFileTest to ensure the abstract test isn't
28  * run).
29  *
30  * A BuildFileTest is a TestCase which executes targets from an Ant buildfile
31  * for testing.
32  *
33  * This class provides a number of utility methods for particular build file
34  * tests which extend this class.
35  *
36  * @author Nico Seessle <nico@seessle.de>
37  * @author Conor MacNeill
38  */

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

54     public BuildFileTestA(String JavaDoc name) {
55         super(name);
56     }
57
58     /**
59      * run a target, expect for any build exception
60      *
61      *@param target target to run
62      *@param cause information string to reader of report
63      */

64     protected void expectBuildException(String JavaDoc target, String JavaDoc cause) {
65         expectSpecificBuildException(target, cause, null);
66     }
67
68     /**
69      * Assert that only the given message has been logged with a
70      * priority &gt;= INFO when running the given target.
71      */

72     protected void expectLog(String JavaDoc target, String JavaDoc log) {
73         executeTarget(target);
74         String JavaDoc realLog = getLog();
75         assertEquals(log, realLog);
76     }
77
78     /**
79      * Assert that the given substring is in the log messages
80      */

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

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

105     protected String JavaDoc getLog() {
106         return logBuffer.toString();
107     }
108
109     /**
110      * Assert that the given message has been logged with a priority
111      * &gt;= DEBUG when running the given target.
112      */

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

126     protected String JavaDoc getFullLog() {
127         return fullLogBuffer.toString();
128     }
129
130     /**
131      * execute the target, verify output matches expectations
132      *
133      *@param target target to execute
134      *@param output output to look for
135      */

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

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

195     protected void configureProject(String JavaDoc filename) throws BuildException {
196         configureProject(filename, Project.MSG_DEBUG);
197     }
198
199     /**
200      * set up to run the named project
201      *
202      * @param filename name of project file to run
203      */

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

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

248     protected Project getProject() {
249         return project;
250     }
251
252     /**
253      * get the directory of the project
254      * @return the base dir of the project
255      */

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

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

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

312
313     protected void expectPropertySet(String JavaDoc target, String JavaDoc property, String JavaDoc value) {
314         executeTarget(target);
315         assertPropertyEquals(property, value);
316     }
317
318     /**
319      * assert that a property equals a value; comparison is case sensitive.
320      * @param property property name
321      * @param value expected value
322      */

323     protected void assertPropertyEquals(String JavaDoc property, String JavaDoc value) {
324         String JavaDoc result = project.getProperty(property);
325         assertEquals("property " + property,value,result);
326     }
327
328     /**
329      * assert that a property equals &quot;true&quot;
330      * @param property property name
331      */

332     protected void assertPropertySet(String JavaDoc property) {
333         assertPropertyEquals(property, "true");
334     }
335
336     /**
337      * assert that a property is null
338      * @param property property name
339      */

340     protected void assertPropertyUnset(String JavaDoc property) {
341         assertPropertyEquals(property, null);
342     }
343
344
345     /**
346      * call a target, verify named property is "true".
347      *
348      * @param target build file target
349      * @param property property name
350      */

351     protected void expectPropertySet(String JavaDoc target, String JavaDoc property) {
352         expectPropertySet(target, property, "true");
353     }
354
355
356     /**
357      * call a target, verify property is null
358      * @param target build file target
359      * @param property property name
360      */

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

372     protected URL JavaDoc getResource(String JavaDoc resource){
373         URL JavaDoc url = getClass().getResource(resource);
374         assertNotNull("Could not find resource :" + resource, url);
375         return url;
376     }
377
378     /**
379      * an output stream which saves stuff to our buffer.
380      */

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

396     private class AntTestListener implements BuildListener {
397         private int logLevel;
398
399         /**
400          * Constructs a test listener which will ignore log events
401          * above the given level
402          */

403         public AntTestListener(int logLevel) {
404             this.logLevel = logLevel;
405         }
406
407         /**
408          * Fired before any targets are started.
409          */

410         public void buildStarted(BuildEvent event) {
411         }
412
413         /**
414          * Fired after the last target has finished. This event
415          * will still be thrown if an error occured during the build.
416          *
417          * @see BuildEvent#getException()
418          */

419         public void buildFinished(BuildEvent event) {
420         }
421
422         /**
423          * Fired when a target is started.
424          *
425          * @see BuildEvent#getTarget()
426          */

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

437         public void targetFinished(BuildEvent event) {
438             //System.out.println("targetFinished " + event.getTarget().getName());
439
}
440
441         /**
442          * Fired when a task is started.
443          *
444          * @see BuildEvent#getTask()
445          */

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

456         public void taskFinished(BuildEvent event) {
457             //System.out.println("taskFinished " + event.getTask().getTaskName());
458
}
459
460         /**
461          * Fired whenever a message is logged.
462          *
463          * @see BuildEvent#getMessage()
464          * @see BuildEvent#getPriority()
465          */

466         public void messageLogged(BuildEvent event) {
467             if (event.getPriority() > logLevel) {
468                 // ignore event
469
return;
470             }
471
472             if (event.getPriority() == Project.MSG_INFO ||
473                 event.getPriority() == Project.MSG_WARN ||
474                 event.getPriority() == Project.MSG_ERR) {
475                 logBuffer.append(event.getMessage());
476                 logBuffer.append( "\n" );
477             }
478             fullLogBuffer.append(event.getMessage());
479             fullLogBuffer.append( "\n" );
480         }
481     }
482
483
484 }
485
Popular Tags