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.log4j;
18  
19  
20  import java.io.InputStream;
21  import java.util.Enumeration;
22  import java.util.Iterator;
23  import java.util.Properties;
24  
25  import junit.framework.Test;
26  import junit.framework.TestSuite;
27  
28  import org.apache.log4j.Level;
29  import org.apache.log4j.Logger;
30  import org.apache.log4j.PropertyConfigurator;
31  import org.apache.log4j.spi.LoggingEvent;
32  
33  
34  /***
35   * <p>TestCase for Log4J logging when running on a system with Log4J present,
36   * so that Log4J should be selected and an appropriate
37   * logger configured per the configuration properties.</p>
38   *
39   * @author Craig R. McClanahan
40   * @version $Revision: 1.9 $ $Date: 2004/05/19 20:59:56 $
41   */
42  
43  public class CustomConfigTestCase extends DefaultConfigTestCase {
44  
45  
46      // ----------------------------------------------------------- Constructors
47  
48  
49      /***
50       * <p>Construct a new instance of this test case.</p>
51       *
52       * @param name Name of the test case
53       */
54      public CustomConfigTestCase(String name) {
55          super(name);
56      }
57  
58  
59      // ----------------------------------------------------- Instance Variables
60  
61  
62      /***
63       * <p>The <code>Appender</code> we are utilizing.</p>
64       */
65      protected TestAppender appender = null;
66  
67  
68      /***
69       * <p>The <code>Logger</code> we are utilizing.</p>
70       */
71      protected Logger logger = null;
72  
73  
74      /***
75       * <p>The message levels that should have been logged.</p>
76       */
77      protected Level testLevels[] =
78      { Level.INFO, Level.WARN, Level.ERROR, Level.FATAL };
79  
80  
81      /***
82       * <p>The message strings that should have been logged.</p>
83       */
84      protected String testMessages[] =
85      { "info", "warn", "error", "fatal" };
86  
87  
88      // ------------------------------------------- JUnit Infrastructure Methods
89  
90  
91      /***
92       * Set up instance variables required by this test case.
93       */
94      public void setUp() throws Exception {
95          setUpAppender
96              ("org/apache/commons/logging/log4j/CustomConfig.properties");
97          setUpLogger("TestLogger");
98          setUpFactory();
99          setUpLog("TestLogger");
100     }
101 
102 
103     /***
104      * Return the tests included in this test suite.
105      */
106     public static Test suite() {
107         return (new TestSuite(CustomConfigTestCase.class));
108     }
109 
110     /***
111      * Tear down instance variables required by this test case.
112      */
113     public void tearDown() {
114         super.tearDown();
115         Logger.getRootLogger().removeAppender(appender);
116         appender = null;
117         logger = null;
118     }
119 
120 
121     // ----------------------------------------------------------- Test Methods
122 
123 
124     // Test logging message strings with exceptions
125     public void testExceptionMessages() throws Exception {
126 
127         logExceptionMessages();
128         checkLoggingEvents(true);
129 
130     }
131 
132 
133     // Test logging plain message strings
134     public void testPlainMessages() throws Exception {
135 
136         logPlainMessages();
137         checkLoggingEvents(false);
138 
139     }
140 
141 
142     // Test pristine Appender instance
143     public void testPristineAppender() {
144 
145         assertNotNull("Appender exists", appender);
146 
147     }
148 
149 
150     // Test pristine Log instance
151     public void testPristineLog() {
152 
153         super.testPristineLog();
154 
155     }
156 
157 
158     // Test pristine Logger instance
159     public void testPristineLogger() {
160 
161         assertNotNull("Logger exists", logger);
162         assertEquals("Logger level", Level.INFO, logger.getEffectiveLevel());
163         assertEquals("Logger name", "TestLogger", logger.getName());
164 
165     }
166 
167 
168     // Test Serializability of Log instance
169     public void testSerializable() throws Exception {
170 
171         super.testSerializable();
172         testExceptionMessages();
173 
174     }
175 
176 
177     // -------------------------------------------------------- Support Methods
178 
179 
180     // Check the log instance
181     protected void checkLog() {
182 
183         assertNotNull("Log exists", log);
184         assertEquals("Log class",
185                      "org.apache.commons.logging.impl.Log4JLogger",
186                      log.getClass().getName());
187 
188         // Assert which logging levels have been enabled
189         assertTrue(log.isErrorEnabled());
190         assertTrue(log.isWarnEnabled());
191         assertTrue(log.isInfoEnabled());
192         assertTrue(!log.isDebugEnabled());
193         assertTrue(!log.isTraceEnabled());
194 
195     }
196 
197 
198     // Check the recorded messages
199     protected void checkLoggingEvents(boolean thrown) {
200         Iterator events = appender.events();
201         for (int i = 0; i < testMessages.length; i++) {
202             assertTrue("Logged event " + i + " exists",events.hasNext());
203             LoggingEvent event = (LoggingEvent) events.next();
204             assertEquals("LoggingEvent level",
205                          testLevels[i], event.getLevel());
206             assertEquals("LoggingEvent message",
207                          testMessages[i], event.getMessage());
208             /* Does not appear to be logged correctly?
209             assertEquals("LoggingEvent class",
210                          this.getClass().getName(),
211                          event.getLocationInformation().getClassName());
212             */
213             /* Does not appear to be logged correctly?
214             if (thrown) {
215                 assertEquals("LoggingEvent method",
216                              "logExceptionMessages",
217                              event.getLocationInformation().getMethodName());
218             } else {
219                 assertEquals("LoggingEvent method",
220                              "logPlainMessages",
221                              event.getLocationInformation().getMethodName());
222             }
223             */
224             if (thrown) {
225                 assertNotNull("LoggingEvent thrown",
226                               event.getThrowableInformation().getThrowableStrRep());
227                 assertTrue("LoggingEvent thrown type",
228                            event.getThrowableInformation()
229                                 .getThrowableStrRep()[0]
230                                     .indexOf("IndexOutOfBoundsException")>0);
231             } else {
232                 assertNull("LoggingEvent thrown",
233                            event.getThrowableInformation());
234             }
235         }
236         assertTrue(!events.hasNext());
237         appender.flush();
238     }
239 
240 
241     // Log the messages with exceptions
242     protected void logExceptionMessages() {
243         Throwable t = new IndexOutOfBoundsException();
244         log.trace("trace", t); // Should not actually get logged
245         log.debug("debug", t); // Should not actually get logged
246         log.info("info", t);
247         log.warn("warn", t);
248         log.error("error", t);
249         log.fatal("fatal", t);
250     }
251 
252 
253     // Log the plain messages
254     protected void logPlainMessages() {
255         log.trace("trace"); // Should not actually get logged
256         log.debug("debug"); // Should not actually get logged
257         log.info("info");
258         log.warn("warn");
259         log.error("error");
260         log.fatal("fatal");
261     }
262 
263 
264     // Set up our custom Appender
265     protected void setUpAppender(String config) throws Exception {
266         Properties props = new Properties();
267         InputStream is =
268             this.getClass().getClassLoader().getResourceAsStream(config);
269         props.load(is);
270         is.close();
271         PropertyConfigurator.configure(props);
272         Enumeration appenders = Logger.getRootLogger().getAllAppenders();
273         appender = (TestAppender) appenders.nextElement();
274     }
275 
276 
277     // Set up our custom Logger
278     protected void setUpLogger(String name) throws Exception {
279         logger = Logger.getLogger(name);
280     }
281 
282 
283 }