KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cactus > integration > ant > AntTestCase


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

20 package org.apache.cactus.integration.ant;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileNotFoundException JavaDoc;
25 import java.io.FileOutputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.StringReader JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.HashSet JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Set JavaDoc;
32
33 import junit.framework.AssertionFailedError;
34 import junit.framework.TestCase;
35
36 import org.apache.tools.ant.BuildEvent;
37 import org.apache.tools.ant.BuildException;
38 import org.apache.tools.ant.BuildListener;
39 import org.apache.tools.ant.Project;
40 import org.apache.tools.ant.ProjectHelper;
41 import org.apache.tools.ant.Target;
42
43 /**
44  * An AntTestCase is a TestCase specialization for unit testing Ant tasks.
45  *
46  * @version $Id: AntTestCase.java,v 1.13 2004/05/31 20:05:23 vmassol Exp $
47  */

48 public abstract class AntTestCase extends TestCase implements BuildListener
49 {
50     // Instance Variables ------------------------------------------------------
51

52     /**
53      * The Ant project.
54      */

55     private Project project;
56
57     /**
58      * The name of the test build file.
59      */

60     private String JavaDoc buildFile;
61
62     /**
63      * Buffer containing all messages logged by Ant. Keys correspond to the
64      * message priority as <code>java.lang.Integer</code>, the values are are
65      * <code>java.lang.StringBuffer</code>s containing the actual log messages.
66      */

67     private Map JavaDoc log = new HashMap JavaDoc();
68
69     /**
70      * File where to log Ant outputs for debugging. If no file location has
71      * been passed, there will be no file logging.
72      */

73     private FileOutputStream JavaDoc outputStream;
74     
75     /**
76      * The targets the have been executed.
77      */

78     private Set JavaDoc executedTargets = new HashSet JavaDoc();
79
80     // Constructors ------------------------------------------------------------
81

82     /**
83      * @param theBuildFile The Ant build file corresponding to the test fixture
84      */

85     public AntTestCase(String JavaDoc theBuildFile)
86     {
87         this.buildFile = theBuildFile;
88         
89         String JavaDoc outputString = System.getProperty("logfile");
90         if (outputString != null)
91         {
92             try
93             {
94                 this.outputStream = new FileOutputStream JavaDoc(outputString);
95             }
96             catch (FileNotFoundException JavaDoc e)
97             {
98                 // Silently ignore error when creating output stream
99
}
100         }
101     }
102
103     // BuildListener Implementation --------------------------------------------
104

105     /**
106      * @see BuildListener#buildStarted
107      */

108     public final void buildStarted(BuildEvent theEvent)
109     {
110     }
111
112     /**
113      * @see BuildListener#buildFinished
114      */

115     public final void buildFinished(BuildEvent theEvent)
116     {
117     }
118
119     /**
120      * @see BuildListener#targetStarted
121      */

122     public final void targetStarted(BuildEvent theEvent)
123     {
124     }
125
126     /**
127      * @see BuildListener#targetFinished
128      */

129     public final void targetFinished(BuildEvent theEvent)
130     {
131         this.executedTargets.add(theEvent.getTarget().getName());
132     }
133
134     /**
135      * @see BuildListener#taskStarted
136      */

137     public final void taskStarted(BuildEvent theEvent)
138     {
139     }
140
141     /**
142      * @see BuildListener#taskFinished
143      */

144     public final void taskFinished(BuildEvent theEvent)
145     {
146     }
147
148     /**
149      * @see BuildListener#messageLogged
150      */

151     public final void messageLogged(BuildEvent theEvent)
152     {
153         StringBuffer JavaDoc buffer = (StringBuffer JavaDoc)
154             log.get(new Integer JavaDoc(theEvent.getPriority()));
155         if (buffer == null)
156         {
157             buffer = new StringBuffer JavaDoc();
158             log.put(new Integer JavaDoc(theEvent.getPriority()), buffer);
159         }
160         buffer.append(theEvent.getMessage()).append("\n");
161         if (this.outputStream != null)
162         {
163             try
164             {
165                 this.outputStream.write(theEvent.getMessage().getBytes());
166                 this.outputStream.write('\n');
167             }
168             catch (IOException JavaDoc e)
169             {
170                 // Silently ignore log error
171
}
172         }
173     }
174
175     // TestCase Implementation -------------------------------------------------
176

177     /**
178      * Initializes a fresh Ant project with a target named after the name of the
179      * test case.
180      *
181      * @see junit.framework.TestCase#setUp()
182      */

183     protected void setUp() throws Exception JavaDoc
184     {
185         this.project = new Project();
186         this.project.addBuildListener(this);
187         this.project.init();
188         File JavaDoc buildFile = getBuildFile(this.buildFile);
189         this.project.setUserProperty("ant.file", buildFile.getAbsolutePath());
190         ProjectHelper helper = ProjectHelper.getProjectHelper();
191         helper.parse(this.project, buildFile);
192         if (getProject().getTargets().get("setUp") != null)
193         {
194             getProject().executeTarget("setUp");
195         }
196     }
197
198     /**
199      * @see junit.framework.TestCase#tearDown()
200      */

201     protected void tearDown() throws Exception JavaDoc
202     {
203         if (getProject().getTargets().get("tearDown") != null)
204         {
205             try
206             {
207                 getProject().executeTarget("tearDown");
208             }
209             catch (BuildException be)
210             {
211                 // exception has been logged
212
}
213         }
214     }
215
216     // Protected Methods -------------------------------------------------------
217

218     /**
219      * @return the buffer containing all Ant logs for the specified
220      * log level
221      * @param theLogLevel The log level of the message
222      */

223     protected String JavaDoc getLog(int theLogLevel)
224     {
225         String JavaDoc result = null;
226         StringBuffer JavaDoc buffer = (StringBuffer JavaDoc) this.log.get(
227             new Integer JavaDoc(theLogLevel));
228         if (buffer != null)
229         {
230             result = buffer.toString();
231         }
232         return result;
233     }
234     
235     /**
236      * Asserts that a specific message has been logged at a specific log level.
237      *
238      * @param theMessage The message to check for
239      * @param theLogLevel The log level of the message
240      * @throws IOException If an error occurred reading the log buffer
241      */

242     protected final void assertMessageLogged(String JavaDoc theMessage, int theLogLevel)
243         throws IOException JavaDoc
244     {
245         String JavaDoc buffer = getLog(theLogLevel);
246         if (buffer != null)
247         {
248             BufferedReader JavaDoc reader =
249                 new BufferedReader JavaDoc(new StringReader JavaDoc(buffer));
250             String JavaDoc line = null;
251             while ((line = reader.readLine()) != null)
252             {
253                 if (line.equals(theMessage))
254                 {
255                     return;
256                 }
257             }
258         }
259         throw new AssertionFailedError(
260             "Expected log message '" + theMessage + "'");
261     }
262
263     /**
264      * Asserts that a message containing the specified substring has been logged
265      * at a specific log level.
266      *
267      * @param theSubstring The substring to check for
268      * @param theLogLevel The log level of the message
269      * @throws IOException If an error occurred reading the log buffer
270      */

271     protected final void assertMessageLoggedContaining(String JavaDoc theSubstring,
272         int theLogLevel)
273         throws IOException JavaDoc
274     {
275         StringBuffer JavaDoc buffer = (StringBuffer JavaDoc) log.get(new Integer JavaDoc(theLogLevel));
276         if (buffer != null)
277         {
278             BufferedReader JavaDoc reader =
279                 new BufferedReader JavaDoc(new StringReader JavaDoc(buffer.toString()));
280             String JavaDoc line = null;
281             while ((line = reader.readLine()) != null)
282             {
283                 if (line.indexOf(theSubstring) >= 0)
284                 {
285                     return;
286                 }
287             }
288         }
289         throw new AssertionFailedError(
290             "Expected log message containing '" + theSubstring + "'");
291     }
292
293     /**
294      * Asserts that a named target has been executed.
295      *
296      * @param theName The name of the target
297      */

298     protected final void assertTargetExecuted(String JavaDoc theName)
299     {
300         assertTrue("Target '" + theName + "' should have been executed",
301             this.executedTargets.contains(theName));
302     }
303
304     /**
305      * Executes the target in the project that corresponds to the current test
306      * case.
307      */

308     protected final void executeTestTarget()
309     {
310         this.project.executeTarget(getName());
311     }
312
313     /**
314      * Returns the Ant project.
315      *
316      * @return The project
317      */

318     protected final Project getProject()
319     {
320         return this.project;
321     }
322
323     /**
324      * Returns the base directory of the Ant project.
325      *
326      * @return The base directory
327      */

328     protected final File JavaDoc getProjectDir()
329     {
330         return this.project.getBaseDir();
331     }
332
333     /**
334      * Returns the target in the project that corresponds to the current test
335      * case.
336      *
337      * @return The test target
338      */

339     protected final Target getTestTarget()
340     {
341         return (Target) getProject().getTargets().get(getName());
342     }
343
344     // Private Methods ---------------------------------------------------------
345

346     /**
347      * Returns a file from the test inputs directory, which is determined by the
348      * system property <code>testinput.dir</code>.
349      *
350      * @param theFileName The name of the file relative to the test input
351      * directory
352      * @return The file from the test input directory
353      */

354     private File JavaDoc getBuildFile(String JavaDoc theFileName)
355     {
356         String JavaDoc testInputDirProperty = System.getProperty("testinput.dir");
357         assertTrue("The system property 'testinput.dir' must be set",
358             testInputDirProperty != null);
359         File JavaDoc testInputDir = new File JavaDoc(testInputDirProperty);
360         assertTrue("The system property 'testinput.dir' must point to an "
361             + "existing directory", testInputDir.isDirectory());
362         File JavaDoc buildFile = new File JavaDoc(testInputDir, theFileName);
363         assertTrue("The test input " + theFileName + " does not exist",
364             buildFile.exists());
365         return buildFile;
366     }
367
368 }
369
Popular Tags