KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > module > spi > AntLoggerTest


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.apache.tools.ant.module.spi;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Arrays JavaDoc;
26 import java.util.HashSet JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Set JavaDoc;
29 import org.apache.tools.ant.module.api.AntTargetExecutor;
30 import org.apache.tools.ant.module.xml.AntProjectSupport;
31 import org.netbeans.junit.MockServices;
32 import org.netbeans.junit.NbTestCase;
33 import org.openide.filesystems.FileObject;
34 import org.openide.filesystems.FileUtil;
35 import org.openide.modules.InstalledFileLocator;
36 import org.openide.util.Lookup;
37
38 // For debugging info, add to nbproject/private/private.properties:
39
// test-unit-sys-prop.org.apache.tools.ant.module.bridge.impl.NbBuildLogger.LOG_AT_WARNING=true
40

41 /**
42  * Tests functionality of {@link AntLogger}.
43  * Specifically, NbBuildLogger.
44  * @author Jesse Glick
45  */

46 public class AntLoggerTest extends NbTestCase {
47     
48     static {
49         AntLoggerTest.class.getClassLoader().setDefaultAssertionStatus(true);
50     }
51
52     public AntLoggerTest(String JavaDoc name) {
53         super(name);
54     }
55
56     private File JavaDoc testdir;
57     private FileObject testdirFO;
58     private TestLogger LOGGER;
59
60     @Override JavaDoc
61     protected void setUp() throws Exception JavaDoc {
62         super.setUp();
63         MockServices.setServices(IFL.class, TestLogger.class);
64         LOGGER = Lookup.getDefault().lookup(TestLogger.class);
65         LOGGER.reset();
66         testdir = new File JavaDoc(this.getDataDir(), "antlogger");
67         assertTrue("have a dir " + testdir, testdir.isDirectory());
68         testdirFO = FileUtil.toFileObject(testdir);
69         assertNotNull("have testdirFO", testdirFO);
70     }
71
72     private void run(FileObject script) throws Exception JavaDoc {
73         run(script, null, AntEvent.LOG_INFO);
74     }
75     private void run(FileObject script, String JavaDoc[] targets, int verbosity) throws Exception JavaDoc {
76         AntTargetExecutor.Env env = new AntTargetExecutor.Env();
77         env.setVerbosity(verbosity);
78         int res = AntTargetExecutor.createTargetExecutor(env).execute(new AntProjectSupport(script), targets).result();
79         if (res != 0) {
80             throw new IOException JavaDoc("Nonzero exit code: " + res + "; messages: " + LOGGER.getMessages());
81         }
82     }
83
84     public void testRunningAnt() throws Exception JavaDoc {
85         File JavaDoc something = new File JavaDoc(System.getProperty("java.io.tmpdir"), "something");
86         if (something.exists()) {
87             something.delete();
88         }
89         run(testdirFO.getFileObject("trivial.xml"));
90         assertTrue("now " + something + " exists", something.isFile());
91     }
92     
93     public void testLocationOfImportedTargetsWithoutLineNumbers() throws Exception JavaDoc {
94         LOGGER.interestedInSessionFlag = true;
95         LOGGER.interestedInAllScriptsFlag = true;
96         LOGGER.interestingTargets = AntLogger.ALL_TARGETS;
97         run(testdirFO.getFileObject("importing.xml"));
98         File JavaDoc importing = new File JavaDoc(testdir, "importing.xml");
99         File JavaDoc imported = new File JavaDoc(testdir, "imported.xml");
100         assertEquals("correct 2 targets run (NOTE: you need Ant 1.6.0+)", Arrays.asList(new String JavaDoc[] {
101             imported + "#subtarget",
102             importing + "#main",
103         }), LOGGER.getTargetsStarted());
104     }
105     
106     public void testLocationOfImportedTargetsWithLineNumbers() throws Exception JavaDoc {
107         LOGGER.interestedInSessionFlag = true;
108         LOGGER.interestedInAllScriptsFlag = true;
109         LOGGER.interestingTargets = AntLogger.ALL_TARGETS;
110         LOGGER.collectLineNumbersForTargets = true;
111         run(testdirFO.getFileObject("importing.xml"));
112         File JavaDoc importing = new File JavaDoc(testdir, "importing.xml");
113         File JavaDoc imported = new File JavaDoc(testdir, "imported.xml");
114         assertEquals("correct 2 targets run (NOTE: you need Ant 1.6.3+)", Arrays.asList(new String JavaDoc[] {
115             imported + ":3#subtarget",
116             importing + ":4#main",
117         }), LOGGER.getTargetsStarted());
118     }
119     
120     public void testTaskdef() throws Exception JavaDoc {
121         LOGGER.interestedInSessionFlag = true;
122         LOGGER.interestedInAllScriptsFlag = true;
123         LOGGER.interestingTargets = AntLogger.ALL_TARGETS;
124         LOGGER.interestingTasks = AntLogger.ALL_TASKS;
125         LOGGER.interestingLogLevels = new int[] {AntEvent.LOG_INFO, AntEvent.LOG_WARN};
126         run(testdirFO.getFileObject("taskdefs.xml"));
127         //System.err.println("messages=" + LOGGER.messages);
128
assertTrue("got info message", LOGGER.getMessages().contains("mytask:" + AntEvent.LOG_INFO + ":MyTask info message"));
129         assertFalse("did not get verbose message", LOGGER.getMessages().contains("mytask:" + AntEvent.LOG_VERBOSE + ":MyTask verbose message"));
130         assertTrue("got warn message", LOGGER.getMessages().contains("mytask:" + AntEvent.LOG_WARN + ":MyTask warn message"));
131     }
132     
133     public void testCorrectTaskFromIndirectCall() throws Exception JavaDoc {
134         // #49464: if a task calls something which in turn does Project.log w/o the Task handle,
135
// you lose all useful information. But you can guess which Task it is - you know some
136
// task has been started and not yet finished. Within limits. Imports, <ant>, etc. can
137
// screw up the accounting.
138
LOGGER.interestedInSessionFlag = true;
139         LOGGER.interestedInAllScriptsFlag = true;
140         LOGGER.interestingTargets = AntLogger.ALL_TARGETS;
141         LOGGER.interestingTasks = AntLogger.ALL_TASKS;
142         LOGGER.interestingLogLevels = new int[] {AntEvent.LOG_DEBUG};
143         run(testdirFO.getFileObject("property.xml"));
144         //System.err.println("messages=" + LOGGER.messages);
145
List JavaDoc<String JavaDoc> messages = LOGGER.getMessages();
146         assertTrue("have message with task ID in " + messages, messages.contains("property:4:Setting project property: propname -> propval"));
147     }
148
149     public void testAntEventDetails() throws Exception JavaDoc {
150         LOGGER.interestedInSessionFlag = true;
151         LOGGER.interestedInAllScriptsFlag = true;
152         LOGGER.interestingTargets = AntLogger.ALL_TARGETS;
153         LOGGER.interestingTasks = new String JavaDoc[] {"echo"};
154         LOGGER.interestingLogLevels = new int[] {AntEvent.LOG_INFO};
155         run(testdirFO.getFileObject("property.xml"));
156         assertTrue(LOGGER.antEventDetailsOK);
157         LOGGER.antEventDetailsOK = false;
158         run(testdirFO.getFileObject("property.xml"), new String JavaDoc[] {"run2"}, AntEvent.LOG_INFO);
159         assertTrue("#71816: works even inside <antcall>", LOGGER.antEventDetailsOK);
160     }
161     
162     public void testSimultaneousLogging() throws Exception JavaDoc {
163         // #84704: just because one log call is locked, ought not block others
164
LOGGER.interestedInSessionFlag = true;
165         LOGGER.interestedInAllScriptsFlag = true;
166         LOGGER.interestingTargets = AntLogger.ALL_TARGETS;
167         LOGGER.interestingTasks = AntLogger.ALL_TASKS;
168         LOGGER.interestingLogLevels = new int[] {AntEvent.LOG_VERBOSE};
169         LOGGER.halt = true;
170         run(testdirFO.getFileObject("trivial.xml"), null, AntEvent.LOG_VERBOSE);
171         // see TestLogger.taskStarted for details
172
}
173     
174     /**
175      * Sample logger which collects results.
176      */

177     public static final class TestLogger extends AntLogger {
178         
179         public boolean interestedInSessionFlag;
180         public boolean interestedInAllScriptsFlag;
181         public Set JavaDoc<File JavaDoc> interestingScripts;
182         public String JavaDoc[] interestingTargets;
183         public String JavaDoc[] interestingTasks;
184         public int[] interestingLogLevels;
185         public boolean collectLineNumbersForTargets;
186         public boolean halt;
187         /** Format of each: "/path/to/file.xml:line#targetName" (line numbers only if collectLineNumbersForTargets) */
188         private List JavaDoc<String JavaDoc> targetsStarted;
189         /** Format of each: "taskname:level:message" */
190         private List JavaDoc<String JavaDoc> messages;
191         private boolean antEventDetailsOK;
192         
193         public TestLogger() {}
194         
195         /** Set everything back to default values as in AntLogger base class. */
196         public synchronized void reset() {
197             interestedInSessionFlag = false;
198             interestedInAllScriptsFlag = false;
199             interestingScripts = new HashSet JavaDoc<File JavaDoc>();
200             interestingTargets = AntLogger.NO_TARGETS;
201             interestingTasks = AntLogger.NO_TASKS;
202             interestingLogLevels = new int[0];
203             collectLineNumbersForTargets = false;
204             targetsStarted = new ArrayList JavaDoc<String JavaDoc>();
205             messages = new ArrayList JavaDoc<String JavaDoc>();
206             antEventDetailsOK = false;
207             halt = false;
208         }
209         
210         public synchronized List JavaDoc<String JavaDoc> getTargetsStarted() {
211             return new ArrayList JavaDoc<String JavaDoc>(targetsStarted);
212         }
213         
214         public synchronized List JavaDoc<String JavaDoc> getMessages() {
215             return new ArrayList JavaDoc<String JavaDoc>(messages);
216         }
217
218         @Override JavaDoc
219         public boolean interestedInAllScripts(AntSession session) {
220             return interestedInAllScriptsFlag;
221         }
222
223         @Override JavaDoc
224         public String JavaDoc[] interestedInTasks(AntSession session) {
225             return interestingTasks;
226         }
227
228         @Override JavaDoc
229         public boolean interestedInScript(File JavaDoc script, AntSession session) {
230             return interestingScripts.contains(script);
231         }
232
233         @Override JavaDoc
234         public String JavaDoc[] interestedInTargets(AntSession session) {
235             return interestingTargets;
236         }
237
238         @Override JavaDoc
239         public boolean interestedInSession(AntSession session) {
240             return interestedInSessionFlag;
241         }
242
243         @Override JavaDoc
244         public int[] interestedInLogLevels(AntSession session) {
245             return interestingLogLevels;
246         }
247
248         @Override JavaDoc
249         public synchronized void targetStarted(AntEvent event) {
250             int line = event.getLine();
251             targetsStarted.add(event.getScriptLocation() +
252                 (collectLineNumbersForTargets && line != -1 ? ":" + line : "") +
253                 '#' + event.getTargetName());
254         }
255         
256         @Override JavaDoc
257         public synchronized void messageLogged(AntEvent event) {
258             String JavaDoc toadd = "" + event.getLogLevel() + ":" + event.getMessage();
259             String JavaDoc taskname = event.getTaskName();
260             if (taskname != null) {
261                 toadd = taskname + ":" + toadd;
262             }
263             messages.add(toadd);
264         }
265
266         @Override JavaDoc
267         public synchronized void buildFinished(AntEvent event) {
268             Throwable JavaDoc t = event.getException();
269             if (t != null) {
270                 messages.add("EXC:" + t);
271             }
272         }
273
274         @Override JavaDoc
275         public synchronized void taskStarted(final AntEvent event) {
276             antEventDetailsOK |=
277                     "echo".equals(event.getTaskName()) &&
278                     "meaningless".equals(event.getTaskStructure().getText()) &&
279                     "info".equals(event.getTaskStructure().getAttribute("level")) &&
280                     event.getPropertyNames().contains("propname") &&
281                     "propval".equals(event.getProperty("propname"));
282             if (halt && event.getTaskName().equals("touch")) {
283                 try {
284                     Thread JavaDoc t = new Thread JavaDoc() {
285                         public void run() {
286                             synchronized (TestLogger.this) {
287                                 assertEquals("${foobie}", event.evaluate("${foobie}"));
288                                 TestLogger.this.notify();
289                             }
290                         }
291                     };
292                     t.start();
293                     wait(9999);
294                     t.join(9999);
295                     boolean found = false;
296                     for (String JavaDoc m : messages) {
297                         if (m.contains("foobie")) {
298                             found = true;
299                             break;
300                         }
301                     }
302                     assertTrue("message about ${foobie} exists", found);
303                 } catch (InterruptedException JavaDoc x) {
304                     fail(x.toString());
305                 }
306             }
307         }
308         
309     }
310     
311     public static final class IFL extends InstalledFileLocator {
312         public IFL() {}
313         @Override JavaDoc
314         public File JavaDoc locate(String JavaDoc relativePath, String JavaDoc codeNameBase, boolean localized) {
315             if (relativePath.equals("ant/nblib/bridge.jar")) {
316                 String JavaDoc path = System.getProperty("test.bridge.jar");
317                 assertNotNull("must set test.bridge.jar", path);
318                 return new File JavaDoc(path);
319             } else if (relativePath.equals("ant")) {
320                 String JavaDoc path = System.getProperty("test.ant.home");
321                 assertNotNull("must set test.ant.home", path);
322                 return new File JavaDoc(path);
323             } else if (relativePath.startsWith("ant/")) {
324                 String JavaDoc path = System.getProperty("test.ant.home");
325                 assertNotNull("must set test.ant.home", path);
326                 return new File JavaDoc(path, relativePath.substring(4).replace('/', File.separatorChar));
327             } else {
328                 return null;
329             }
330         }
331     }
332
333 }
334
Popular Tags