KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > cruisecontrol > builders > NantBuilderTest


1 /*******************************************************************************
2  * CruiseControl, a Continuous Integration Toolkit Copyright (c) 2001,
3  * ThoughtWorks, Inc. 651 W Washington Ave. Suite 600 Chicago, IL 60661 USA All
4  * rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  * + Redistributions of source code must retain the above copyright notice,
9  * this list of conditions and the following disclaimer.
10  * + Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  * + Neither the name of ThoughtWorks, Inc., CruiseControl, nor the names of
14  * its contributors may be used to endorse or promote products derived from this
15  * software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  ******************************************************************************/

28 package net.sourceforge.cruisecontrol.builders;
29
30 import java.io.BufferedWriter JavaDoc;
31 import java.io.ByteArrayInputStream JavaDoc;
32 import java.io.File JavaDoc;
33 import java.io.FileWriter JavaDoc;
34 import java.io.IOException JavaDoc;
35 import java.io.InputStream JavaDoc;
36 import java.io.PipedInputStream JavaDoc;
37 import java.io.PipedOutputStream JavaDoc;
38 import java.net.URL JavaDoc;
39 import java.util.ArrayList JavaDoc;
40 import java.util.HashMap JavaDoc;
41 import java.util.Hashtable JavaDoc;
42 import java.util.Iterator JavaDoc;
43 import java.util.List JavaDoc;
44
45 import junit.framework.TestCase;
46 import net.sourceforge.cruisecontrol.CruiseControlException;
47 import net.sourceforge.cruisecontrol.util.Commandline;
48 import net.sourceforge.cruisecontrol.util.MockCommandline;
49 import net.sourceforge.cruisecontrol.util.MockProcess;
50 import net.sourceforge.cruisecontrol.util.Util;
51
52 import org.jdom.Attribute;
53 import org.jdom.CDATA;
54 import org.jdom.DataConversionException;
55 import org.jdom.Element;
56
57 public class NantBuilderTest extends TestCase {
58     
59     private final List JavaDoc filesToClear = new ArrayList JavaDoc();
60     private NantBuilder builder;
61     private Hashtable JavaDoc properties;
62     private File JavaDoc rootTempDir = null;
63     
64     static class InputBasedMockCommandLineBuilder {
65         Commandline buildCommandline(final InputStream JavaDoc inputStream) {
66             final MockCommandline mockCommandline = getMockCommandline();
67             mockCommandline.setAssertCorrectCommandline(false);
68             mockCommandline.setProcessErrorStream(new PipedInputStream JavaDoc());
69             mockCommandline.setProcessInputStream(inputStream);
70             mockCommandline.setProcessOutputStream(new PipedOutputStream JavaDoc());
71             return mockCommandline;
72         }
73
74         MockCommandline getMockCommandline() {
75             return new MockCommandline();
76         }
77     }
78
79     // process that times out...
80
static class TimeoutProcess extends MockProcess {
81         private long timeoutMillis;
82         TimeoutProcess(long timeoutMillis) {
83             this.timeoutMillis = timeoutMillis;
84         }
85         public synchronized void destroy() {
86             notifyAll();
87         }
88         public int waitFor() throws InterruptedException JavaDoc {
89             synchronized (this) {
90                 try {
91                     this.wait(timeoutMillis);
92                 } catch (InterruptedException JavaDoc e) {
93                 }
94             }
95             return super.waitFor();
96         }
97     }
98
99
100     protected void setUp() throws Exception JavaDoc {
101         builder = new NantBuilder();
102         builder.setTarget("target");
103         builder.setBuildFile("buildfile");
104
105         // Must be a cleaner way to do this...
106
// builder.setNantWorkingDir(new File(
107
// new URI(ClassLoader.getSystemResource("test.build").toString())).getParent());
108
properties = new Hashtable JavaDoc();
109         properties.put("label", "200.1.23");
110
111         File JavaDoc tempDir = new File JavaDoc(System.getProperty("java.io.tmpdir"));
112         rootTempDir = new File JavaDoc(tempDir, "testRoot");
113         rootTempDir.mkdir();
114     }
115
116     public void tearDown() {
117         for (Iterator JavaDoc iterator = filesToClear.iterator(); iterator.hasNext();) {
118             File JavaDoc file = (File JavaDoc) iterator.next();
119             if (file.exists()) {
120                 file.delete();
121             }
122         }
123
124         builder = null;
125         properties = null;
126
127         Util.deleteFile(rootTempDir);
128     }
129
130     public void testValidate() {
131         builder = new NantBuilder();
132
133         try {
134             builder.validate();
135         } catch (CruiseControlException e) {
136             fail("nantbuilder is missing required attributes");
137         }
138
139         builder.setTime("0100");
140         builder.setBuildFile("buildfile");
141         builder.setTarget("target");
142
143         try {
144             builder.validate();
145         } catch (CruiseControlException e) {
146             fail("validate should not throw exceptions when options are set.");
147         }
148
149         builder.setSaveLogDir("I/hope/this/dir/does/not/exist/");
150         try {
151             builder.validate();
152             fail("validate should throw exceptions when saveLogDir doesn't exist");
153         } catch (CruiseControlException e) {
154         }
155
156         builder.setSaveLogDir(null);
157         builder.setMultiple(2);
158
159         try {
160             builder.validate();
161             fail("validate should throw exceptions when multiple and time are both set.");
162         } catch (CruiseControlException e) {
163         }
164     }
165     
166     public void testTranslateNantErrorElementsWithBuildResultsErrorAttribute()
167         throws CruiseControlException, DataConversionException {
168         Element buildLogElement = new Element("buildresults");
169         Attribute errorAttribute = new Attribute("error", "true");
170         buildLogElement.setAttribute(errorAttribute);
171         buildLogElement = builder.translateNantErrorElements(buildLogElement);
172         assertEquals("build", buildLogElement.getName());
173         assertTrue(buildLogElement.getAttribute("error").getBooleanValue());
174
175     }
176
177     public void testTranslateNantErrorElementsWithFailureElements()
178         throws CruiseControlException, DataConversionException {
179         Element buildLogElement = new Element("buildresults");
180         Element failureElement = new Element("failure");
181         buildLogElement.addContent(failureElement);
182         
183         try {
184             buildLogElement = builder.translateNantErrorElements(buildLogElement);
185             fail("Expected a CruiseControlException for invalid nant log output format");
186         } catch (CruiseControlException e) { /** expected **/ }
187
188         Element buildErrorElement = new Element("builderror");
189         failureElement.addContent(buildErrorElement);
190
191         try {
192             buildLogElement = builder.translateNantErrorElements(buildLogElement);
193             fail("Expected a CruiseControlException for invalid nant log output format");
194         } catch (CruiseControlException e) { /** expected **/ }
195
196         Element messageElement = new Element("message");
197         buildErrorElement.addContent(messageElement);
198
199         try {
200             buildLogElement = builder.translateNantErrorElements(buildLogElement);
201             fail("Expected a CruiseControlException for invalid nant log output format");
202         } catch (CruiseControlException e) { /** expected **/ }
203
204         messageElement.setContent(new CDATA("test failure"));
205
206         buildLogElement = builder.translateNantErrorElements(buildLogElement);
207         assertEquals("build", buildLogElement.getName());
208         Attribute errorAttribute = buildLogElement.getAttribute("error");
209         assertTrue(errorAttribute != null);
210         assertEquals(Attribute.UNDECLARED_TYPE, errorAttribute.getAttributeType());
211         assertEquals("test failure", errorAttribute.getValue());
212     }
213
214     public void testBuild() throws Exception JavaDoc {
215
216         final String JavaDoc logName = "nantbuilder-build1.txt";
217         final InputStream JavaDoc emptyInputStream = new ByteArrayInputStream JavaDoc("".getBytes());
218
219         final NantBuilder mybuilder = new NantBuilder() {
220             protected NantScript getNantScript() {
221                 return new NantScript() {
222                     public Commandline getCommandLine() {
223                         return new InputBasedMockCommandLineBuilder().buildCommandline(emptyInputStream);
224                     }
225                 };
226             }
227             protected Element getNantLogAsElement(File JavaDoc file) throws CruiseControlException {
228                 assertEquals("notLog.xml", file.getPath());
229                 final URL JavaDoc resource = getClass().getResource(logName);
230                 assertNotNull("missing test case resource: " + logName, resource);
231                 String JavaDoc path = resource.getPath();
232                 File JavaDoc simulatedFile = new File JavaDoc(path);
233                 return super.getNantLogAsElement(simulatedFile);
234             }
235         };
236         mybuilder.setTarget("target");
237         mybuilder.setBuildFile("buildfile");
238
239         mybuilder.setBuildFile("test.build");
240         mybuilder.setTempFile("notLog.xml");
241         mybuilder.setTarget("init");
242         HashMap JavaDoc buildProperties = new HashMap JavaDoc();
243         Element buildElement = mybuilder.build(buildProperties);
244         int initCount = getInitCount(buildElement);
245         assertEquals(1, initCount);
246
247         // TODO: Don't know if this is a valid test with NAnt's file format. Need to verify or convert to Ant format.
248
// builder.setTarget("init init");
249
// buildElement = builder.build(buildProperties);
250
// initCount = getInitCount(buildElement);
251
// assertEquals(2, initCount);
252
}
253     
254     public void testGetCommandLineArgs_DebugAndQuiet() throws CruiseControlException {
255         builder.setUseDebug(true);
256         builder.setUseQuiet(true);
257         try {
258             builder.validate();
259             fail("validate() should throw CruiseControlException when both useDebug and useQuiet are true");
260         } catch (CruiseControlException expected) {
261         }
262     }
263
264     public int getInitCount(Element buildElement) {
265         int initFoundCount = 0;
266         Iterator JavaDoc targetIterator = buildElement.getChildren("target").iterator();
267         String JavaDoc name;
268         while (targetIterator.hasNext()) {
269             name = ((Element) targetIterator.next()).getAttributeValue("name");
270             if (name.equals("init")) {
271                 initFoundCount++;
272             }
273         }
274         return initFoundCount;
275     }
276
277     public void testBuildTimeout() throws Exception JavaDoc {
278
279         final MockProcess timeoutProcess = new TimeoutProcess(20000);
280         final MockCommandline timeoutCommandline = new MockCommandline() {
281             public MockProcess getMockProcess() {
282                 return timeoutProcess;
283             }
284         };
285         final InputStream JavaDoc emptyInputStream = new ByteArrayInputStream JavaDoc("".getBytes());
286         timeoutCommandline.setAssertCorrectCommandline(false);
287         timeoutCommandline.setProcessErrorStream(emptyInputStream);
288         timeoutCommandline.setProcessInputStream(emptyInputStream);
289         timeoutCommandline.setProcessOutputStream(System.out);
290
291         final NantBuilder mybuilder = new NantBuilder() {
292             protected NantScript getNantScript() {
293                 return new NantScript() {
294                     public Commandline getCommandLine() {
295                         return timeoutCommandline;
296                     }
297                 };
298             }
299             protected Element getNantLogAsElement(File JavaDoc file) throws CruiseControlException {
300                 fail("We should time out... we have nothing to read anyway");
301                 return super.getNantLogAsElement(file); // please compiler
302
}
303         };
304
305         mybuilder.setBuildFile("test.build");
306         mybuilder.setTarget("timeout-test-target");
307         mybuilder.setTimeout(5);
308         mybuilder.setUseDebug(true);
309         mybuilder.setUseLogger(true);
310
311         HashMap JavaDoc buildProperties = new HashMap JavaDoc();
312         long startTime = System.currentTimeMillis();
313         Element buildElement = mybuilder.build(buildProperties);
314         assertTrue((System.currentTimeMillis() - startTime) < 9 * 1000L);
315         assertTrue(buildElement.getAttributeValue("error").indexOf("timeout") >= 0);
316
317         // test we don't fail when there is no NAnt log file
318
mybuilder.setTimeout(1);
319         mybuilder.setUseDebug(false);
320         mybuilder.setUseLogger(false);
321         mybuilder.setTempFile("shouldNot.xml");
322         buildElement = mybuilder.build(buildProperties);
323         assertTrue(buildElement.getAttributeValue("error").indexOf("timeout") >= 0);
324     }
325
326     public void testSaveNantLog() throws IOException JavaDoc {
327         String JavaDoc originalDirName = "target";
328         String JavaDoc logName = "log.xml";
329         String JavaDoc saveDirName = "target/reports/nant";
330
331         builder.setSaveLogDir(saveDirName);
332         builder.setTempFile(logName);
333
334         File JavaDoc originalDir = new File JavaDoc(originalDirName);
335         File JavaDoc originalLog = new File JavaDoc(originalDir, logName);
336         originalDir.mkdirs();
337         originalLog.createNewFile();
338
339         File JavaDoc saveDir = new File JavaDoc(saveDirName);
340         File JavaDoc savedLog = new File JavaDoc(saveDir, logName);
341         saveDir.mkdirs();
342         savedLog.delete();
343
344         builder.saveNantLog(originalLog);
345         assertTrue(savedLog.exists());
346
347         savedLog.delete();
348
349         builder.setSaveLogDir("");
350         builder.saveNantLog(originalLog);
351         assertFalse(savedLog.exists());
352
353         builder.setSaveLogDir(null);
354         builder.saveNantLog(originalLog);
355         assertFalse(savedLog.exists());
356     }
357     
358     public void testGetNantLogAsElement() throws IOException JavaDoc, CruiseControlException {
359         Element buildLogElement = new Element("build");
360         File JavaDoc logFile = new File JavaDoc("_tempNantLog.xml");
361         filesToClear.add(logFile);
362         BufferedWriter JavaDoc bw2 = new BufferedWriter JavaDoc(new FileWriter JavaDoc(logFile));
363         bw2.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<?xml-stylesheet "
364                 + "type=\"text/xsl\" HREF=\"log.xsl\"?>\n<build></build>");
365         bw2.flush();
366         bw2.close();
367
368         assertEquals(buildLogElement.toString(), builder.getNantLogAsElement(logFile).toString());
369     }
370
371     public void testGetNantLogAsElement_NoLogFile() throws IOException JavaDoc {
372         File JavaDoc doesNotExist = new File JavaDoc("blah blah blah does not exist");
373         try {
374             builder.getNantLogAsElement(doesNotExist);
375             fail();
376         } catch (CruiseControlException expected) {
377             assertEquals("NAnt logfile " + doesNotExist.getAbsolutePath() + " does not exist.", expected.getMessage());
378         }
379     }
380
381 }
382
Popular Tags