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  package org.apache.commons.logging.jdk14;
18  
19  
20  import java.io.InputStream;
21  import java.util.Iterator;
22  import java.util.logging.Handler;
23  import java.util.logging.Level;
24  import java.util.logging.LogManager;
25  import java.util.logging.LogRecord;
26  import java.util.logging.Logger;
27  
28  import junit.framework.Test;
29  import junit.framework.TestSuite;
30  
31  
32  /***
33   * <p>TestCase for JDK 1.4 logging when running on a JDK 1.4 system with
34   * custom configuration, so that JDK 1.4 should be selected and an appropriate
35   * logger configured per the configuration properties.</p>
36   *
37   * @author Craig R. McClanahan
38   * @version $Revision: 370012 $ $Date: 2006-01-18 02:34:05 +0000 (Wed, 18 Jan 2006) $
39   */
40  
41  public class CustomConfigTestCase extends DefaultConfigTestCase {
42  
43  
44      // ----------------------------------------------------------- Constructors
45  
46  
47      /***
48       * <p>Construct a new instance of this test case.</p>
49       *
50       * @param name Name of the test case
51       */
52      public CustomConfigTestCase(String name) {
53          super(name);
54      }
55  
56  
57      // ----------------------------------------------------- Instance Variables
58  
59  
60      /***
61       * <p>The customized <code>Handler</code> we will be using.</p>
62       */
63      protected TestHandler handler = null;
64  
65  
66      /***
67       * <p>The underlying <code>Handler</code>s we will be using.</p>
68       */
69      protected Handler handlers[] = null;
70  
71  
72      /***
73       * <p>The underlying <code>Logger</code> we will be using.</p>
74       */
75      protected Logger logger = null;
76  
77  
78      /***
79       * <p>The underlying <code>LogManager</code> we will be using.</p>
80       */
81      protected LogManager manager = null;
82  
83  
84      /***
85       * <p>The message levels that should have been logged.</p>
86       */
87      protected Level testLevels[] =
88      { Level.FINE, Level.INFO, Level.WARNING, Level.SEVERE, Level.SEVERE };
89  
90  
91      /***
92       * <p>The message strings that should have been logged.</p>
93       */
94      protected String testMessages[] =
95      { "debug", "info", "warn", "error", "fatal" };
96  
97  
98      // ------------------------------------------- JUnit Infrastructure Methods
99  
100 
101     /***
102      * Set up instance variables required by this test case.
103      */
104     public void setUp() throws Exception {
105         setUpManager
106             ("org/apache/commons/logging/jdk14/CustomConfig.properties");
107         setUpLogger("TestLogger");
108         setUpHandlers();
109         setUpFactory();
110         setUpLog("TestLogger");
111     }
112 
113 
114     /***
115      * Return the tests included in this test suite.
116      */
117     public static Test suite() throws Exception {
118         /*
119         PathableClassLoader loader = new PathableClassLoader(null);
120         loader.useSystemLoader("junit.");
121 
122         PathableClassLoader child = new PathableClassLoader(parent);
123         child.addLogicalLib("testclasses");
124         child.addLogicalLib("commons-logging");
125         
126         Class testClass = child.loadClass(CustomConfigTestCase.class.getName());
127         return new PathableTestSuite(testClass, child);
128         */
129         return new TestSuite(CustomConfigTestCase.class);
130     }
131 
132     /***
133      * Tear down instance variables required by this test case.
134      */
135     public void tearDown() {
136         super.tearDown();
137         handlers = null;
138         logger = null;
139         manager = null;
140     }
141 
142 
143     // ----------------------------------------------------------- Test Methods
144 
145 
146     // Test logging message strings with exceptions
147     public void testExceptionMessages() throws Exception {
148 
149         logExceptionMessages();
150         checkLogRecords(true);
151 
152     }
153 
154 
155     // Test logging plain message strings
156     public void testPlainMessages() throws Exception {
157 
158         logPlainMessages();
159         checkLogRecords(false);
160 
161     }
162 
163 
164     // Test pristine Handlers instances
165     public void testPristineHandlers() {
166 
167         assertNotNull(handlers);
168         assertEquals(1, handlers.length);
169         assertTrue(handlers[0] instanceof TestHandler);
170         assertNotNull(handler);
171 
172     }
173 
174 
175     // Test pristine Logger instance
176     public void testPristineLogger() {
177 
178         assertNotNull("Logger exists", logger);
179         assertEquals("Logger name", "TestLogger", logger.getName());
180 
181         // Assert which logging levels have been enabled
182         assertTrue(logger.isLoggable(Level.SEVERE));
183         assertTrue(logger.isLoggable(Level.WARNING));
184         assertTrue(logger.isLoggable(Level.INFO));
185         assertTrue(logger.isLoggable(Level.CONFIG));
186         assertTrue(logger.isLoggable(Level.FINE));
187         assertTrue(!logger.isLoggable(Level.FINER));
188         assertTrue(!logger.isLoggable(Level.FINEST));
189 
190     }
191 
192 
193     // Test Serializability of Log instance
194     public void testSerializable() throws Exception {
195 
196         super.testSerializable();
197         testExceptionMessages();
198 
199     }
200 
201 
202     // -------------------------------------------------------- Support Methods
203 
204 
205     // Check the log instance
206     protected void checkLog() {
207 
208         assertNotNull("Log exists", log);
209         assertEquals("Log class",
210                      "org.apache.commons.logging.impl.Jdk14Logger",
211                      log.getClass().getName());
212 
213         // Assert which logging levels have been enabled
214         assertTrue(log.isFatalEnabled());
215         assertTrue(log.isErrorEnabled());
216         assertTrue(log.isWarnEnabled());
217         assertTrue(log.isInfoEnabled());
218         assertTrue(log.isDebugEnabled());
219         assertTrue(!log.isTraceEnabled());
220 
221     }
222 
223 
224     // Check the recorded messages
225     protected void checkLogRecords(boolean thrown) {
226         Iterator records = handler.records();
227         for (int i = 0; i < testMessages.length; i++) {
228             assertTrue(records.hasNext());
229             LogRecord record = (LogRecord) records.next();
230             assertEquals("LogRecord level",
231                          testLevels[i], record.getLevel());
232             assertEquals("LogRecord message",
233                          testMessages[i], record.getMessage());
234             assertTrue("LogRecord class",
235                          record.getSourceClassName().startsWith(
236                                  "org.apache.commons.logging.jdk14.CustomConfig"));
237             if (thrown) {
238                 assertEquals("LogRecord method",
239                              "logExceptionMessages",
240                              record.getSourceMethodName());
241             } else {
242                 assertEquals("LogRecord method",
243                              "logPlainMessages",
244                              record.getSourceMethodName());
245             }
246             if (thrown) {
247                 assertNotNull("LogRecord thrown", record.getThrown());
248                 assertTrue("LogRecord thrown type",
249                            record.getThrown() instanceof IndexOutOfBoundsException);
250             } else {
251                 assertNull("LogRecord thrown",
252                            record.getThrown());
253             }
254         }
255         assertTrue(!records.hasNext());
256         handler.flush();
257     }
258 
259 
260     // Log the messages with exceptions
261     protected void logExceptionMessages() {
262         Throwable t = new IndexOutOfBoundsException();
263         log.trace("trace", t); // Should not actually get logged
264         log.debug("debug", t);
265         log.info("info", t);
266         log.warn("warn", t);
267         log.error("error", t);
268         log.fatal("fatal", t);
269     }
270 
271 
272     // Log the plain messages
273     protected void logPlainMessages() {
274         log.trace("trace"); // Should not actually get logged
275         log.debug("debug");
276         log.info("info");
277         log.warn("warn");
278         log.error("error");
279         log.fatal("fatal");
280     }
281 
282 
283     // Set up handlers instance
284     protected void setUpHandlers() throws Exception {
285         Logger parent = logger;
286         while (parent.getParent() != null) {
287             parent = parent.getParent();
288         }
289         handlers = parent.getHandlers();
290         
291         // The CustomConfig.properties file explicitly defines one handler class
292         // to be attached to the root logger, so if it isn't there then 
293         // something is badly wrong...
294         //
295         // Yes this testing is also done in testPristineHandlers but
296         // unfortunately:
297         //  * we need to set up the handlers variable here, 
298         //  * we don't want that to be set up incorrectly, as that can
299         //    produce weird error messages in other tests, and
300         //  * we can't rely on testPristineHandlers being the first
301         //    test to run.
302         // so we need to test things here too.
303         assertNotNull("No Handlers defined for JDK14 logging", handlers);
304         assertEquals("Unexpected number of handlers for JDK14 logging", 1, handlers.length);
305         assertNotNull("Handler is null", handlers[0]);
306         assertTrue("Handler not of expected type", handlers[0] instanceof TestHandler);
307         handler = (TestHandler) handlers[0];
308     }
309 
310 
311     // Set up logger instance
312     protected void setUpLogger(String name) throws Exception {
313         logger = Logger.getLogger(name);
314     }
315 
316 
317     // Set up LogManager instance
318     protected void setUpManager(String config) throws Exception {
319         manager = LogManager.getLogManager();
320         InputStream is =
321             this.getClass().getClassLoader().getResourceAsStream(config);
322         manager.readConfiguration(is);
323         is.close();
324     }
325 
326 
327 }