This is an automated email from the ASF dual-hosted git repository. ggregory pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-logging.git
The following commit(s) were added to refs/heads/master by this push: new 5f5affb We don't use author tag, CVS/SVN tags or lots of whitespace 5f5affb is described below commit 5f5affb46746c8ad07d7c8e42bf1df80335bf83f Author: Gary Gregory <garydgreg...@gmail.com> AuthorDate: Tue Aug 30 09:46:14 2022 -0400 We don't use author tag, CVS/SVN tags or lots of whitespace Add a space before { when missing --- .../apache/commons/logging/AbstractLogTest.java | 160 ++--- .../org/apache/commons/logging/LoadTestCase.java | 443 ++++++------ .../logging/avalon/AvalonLoggerTestCase.java | 88 ++- .../logging/jdk14/CustomConfigTestCase.java | 795 ++++++++++----------- .../logging/jdk14/DefaultConfigTestCase.java | 351 ++++----- .../apache/commons/logging/jdk14/TestHandler.java | 126 ++-- .../logging/simple/CustomConfigTestCase.java | 39 - .../logging/simple/DefaultConfigTestCase.java | 35 - 8 files changed, 932 insertions(+), 1105 deletions(-) diff --git a/src/test/java/org/apache/commons/logging/AbstractLogTest.java b/src/test/java/org/apache/commons/logging/AbstractLogTest.java index 3ae0222..10c4f70 100644 --- a/src/test/java/org/apache/commons/logging/AbstractLogTest.java +++ b/src/test/java/org/apache/commons/logging/AbstractLogTest.java @@ -1,94 +1,66 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.logging; - -import junit.framework.TestCase; - - -/** - * Generic tests that can be applied to any log adapter by - * subclassing this class and defining method getLogObject - * appropriately. - * - * @author Sean C. Sullivan - * @version $Revision$ - */ -public abstract class AbstractLogTest extends TestCase { - - public abstract Log getLogObject(); - - public void testLoggingWithNullParameters() - { - final Log log = this.getLogObject(); - - assertNotNull(log); - - - log.debug(null); - - log.debug(null, null); - - log.debug(log.getClass().getName() + ": debug statement"); - - log.debug(log.getClass().getName() + ": debug statement w/ null exception", new RuntimeException()); - - - log.error(null); - - log.error(null, null); - - log.error(log.getClass().getName() + ": error statement"); - - log.error(log.getClass().getName() + ": error statement w/ null exception", new RuntimeException()); - - - log.fatal(null); - - log.fatal(null, null); - - log.fatal(log.getClass().getName() + ": fatal statement"); - - log.fatal(log.getClass().getName() + ": fatal statement w/ null exception", new RuntimeException()); - - - log.info(null); - - log.info(null, null); - - log.info(log.getClass().getName() + ": info statement"); - - log.info(log.getClass().getName() + ": info statement w/ null exception", new RuntimeException()); - - - log.trace(null); - - log.trace(null, null); - - log.trace(log.getClass().getName() + ": trace statement"); - - log.trace(log.getClass().getName() + ": trace statement w/ null exception", new RuntimeException()); - - - log.warn(null); - - log.warn(null, null); - - log.warn(log.getClass().getName() + ": warn statement"); - - log.warn(log.getClass().getName() + ": warn statement w/ null exception", new RuntimeException()); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.logging; + +import junit.framework.TestCase; + + +/** + * Generic tests that can be applied to any log adapter by + * subclassing this class and defining method getLogObject + * appropriately. + */ +public abstract class AbstractLogTest extends TestCase { + + public abstract Log getLogObject(); + + public void testLoggingWithNullParameters() + { + final Log log = this.getLogObject(); + assertNotNull(log); + + log.debug(null); + log.debug(null, null); + log.debug(log.getClass().getName() + ": debug statement"); + log.debug(log.getClass().getName() + ": debug statement w/ null exception", new RuntimeException()); + + log.error(null); + log.error(null, null); + log.error(log.getClass().getName() + ": error statement"); + log.error(log.getClass().getName() + ": error statement w/ null exception", new RuntimeException()); + + log.fatal(null); + log.fatal(null, null); + log.fatal(log.getClass().getName() + ": fatal statement"); + log.fatal(log.getClass().getName() + ": fatal statement w/ null exception", new RuntimeException()); + + log.info(null); + log.info(null, null); + log.info(log.getClass().getName() + ": info statement"); + log.info(log.getClass().getName() + ": info statement w/ null exception", new RuntimeException()); + + log.trace(null); + log.trace(null, null); + log.trace(log.getClass().getName() + ": trace statement"); + log.trace(log.getClass().getName() + ": trace statement w/ null exception", new RuntimeException()); + + log.warn(null); + log.warn(null, null); + log.warn(log.getClass().getName() + ": warn statement"); + log.warn(log.getClass().getName() + ": warn statement w/ null exception", new RuntimeException()); + } +} diff --git a/src/test/java/org/apache/commons/logging/LoadTestCase.java b/src/test/java/org/apache/commons/logging/LoadTestCase.java index 625b6c4..abbb227 100644 --- a/src/test/java/org/apache/commons/logging/LoadTestCase.java +++ b/src/test/java/org/apache/commons/logging/LoadTestCase.java @@ -1,227 +1,216 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.logging; - -import junit.framework.TestCase; - -/** - * testcase to emulate container and application isolated from container - * @author baliuka - */ -public class LoadTestCase extends TestCase{ - //TODO: need some way to add service provider packages - static private String LOG_PCKG[] = {"org.apache.commons.logging", - "org.apache.commons.logging.impl"}; - - /** - * A custom classloader which "duplicates" logging classes available - * in the parent classloader into itself. - * <p> - * When asked to load a class that is in one of the LOG_PCKG packages, - * it loads the class itself (child-first). This class doesn't need - * to be set up with a classpath, as it simply uses the same classpath - * as the classloader that loaded it. - */ - static class AppClassLoader extends ClassLoader{ - - java.util.Map classes = new java.util.HashMap(); - - AppClassLoader(final ClassLoader parent){ - super(parent); - } - - private Class def(final String name)throws ClassNotFoundException{ - - Class result = (Class)classes.get(name); - if(result != null){ - return result; - } - - try{ - - final ClassLoader cl = this.getClass().getClassLoader(); - final String classFileName = name.replace('.','/') + ".class"; - final java.io.InputStream is = cl.getResourceAsStream(classFileName); - final java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); - - while(is.available() > 0){ - out.write(is.read()); - } - - final byte data [] = out.toByteArray(); - - result = super.defineClass(name, data, 0, data.length ); - classes.put(name,result); - - return result; - - }catch(final java.io.IOException ioe){ - - throw new ClassNotFoundException( name + " caused by " - + ioe.getMessage() ); - } - - - } - - // not very trivial to emulate we must implement "findClass", - // but it will delegete to junit class loder first - @Override - public Class loadClass(final String name)throws ClassNotFoundException{ - - //isolates all logging classes, application in the same classloader too. - //filters exeptions to simlify handling in test - for (final String element : LOG_PCKG) { - if( name.startsWith( element ) && - name.indexOf("Exception") == -1 ){ - return def(name); - } - } - return super.loadClass(name); - } - - } - - - /** - * Call the static setAllowFlawedContext method on the specified class - * (expected to be a UserClass loaded via a custom classloader), passing - * it the specified state parameter. - */ - private void setAllowFlawedContext(final Class c, final String state) throws Exception { - final Class[] params = {String.class}; - final java.lang.reflect.Method m = c.getDeclaredMethod("setAllowFlawedContext", params); - m.invoke(null, state); - } - - /** - * Test what happens when we play various classloader tricks like those - * that happen in web and j2ee containers. - * <p> - * Note that this test assumes that commons-logging.jar and log4j.jar - * are available via the system classpath. - */ - public void testInContainer()throws Exception{ - - //problem can be in this step (broken app container or missconfiguration) - //1. Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); - //2. Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); - // we expect this : - // 1. Thread.currentThread().setContextClassLoader(appLoader); - // 2. Thread.currentThread().setContextClassLoader(null); - - // Context classloader is same as class calling into log - Class cls = reload(); - Thread.currentThread().setContextClassLoader(cls.getClassLoader()); - execute(cls); - - // Context classloader is the "bootclassloader". This is technically - // bad, but LogFactoryImpl.ALLOW_FLAWED_CONTEXT defaults to true so - // this test should pass. - cls = reload(); - Thread.currentThread().setContextClassLoader(null); - execute(cls); - - // Context classloader is the "bootclassloader". This is same as above - // except that ALLOW_FLAWED_CONTEXT is set to false; an error should - // now be reported. - cls = reload(); - Thread.currentThread().setContextClassLoader(null); - try { - setAllowFlawedContext(cls, "false"); - execute(cls); - fail("Logging config succeeded when context classloader was null!"); - } catch(final LogConfigurationException ex) { - // expected; the boot classloader doesn't *have* JCL available - } - - // Context classloader is the system classloader. - // - // This is expected to cause problems, as LogFactoryImpl will attempt - // to use the system classloader to load the Log4JLogger class, which - // will then be unable to cast that object to the Log interface loaded - // via the child classloader. However as ALLOW_FLAWED_CONTEXT defaults - // to true this test should pass. - cls = reload(); - Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); - execute(cls); - - // Context classloader is the system classloader. This is the same - // as above except that ALLOW_FLAWED_CONTEXT is set to false; an error - // should now be reported. - cls = reload(); - Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); - try { - setAllowFlawedContext(cls, "false"); - execute(cls); - fail("Error: somehow downcast a Logger loaded via system classloader" - + " to the Log interface loaded via a custom classloader"); - } catch(final LogConfigurationException ex) { - // expected - } - } - - /** - * Load class UserClass via a temporary classloader which is a child of - * the classloader used to load this test class. - */ - private Class reload()throws Exception{ - - Class testObjCls = null; - - final AppClassLoader appLoader = new AppClassLoader( - this.getClass().getClassLoader()); - try{ - - testObjCls = appLoader.loadClass(UserClass.class.getName()); - - }catch(final ClassNotFoundException cnfe){ - throw cnfe; - }catch(final Throwable t){ - t.printStackTrace(); - fail("AppClassLoader failed "); - } - - assertSame("app isolated", testObjCls.getClassLoader(), appLoader); - - - return testObjCls; - - - } - - - private void execute(final Class cls)throws Exception{ - - cls.newInstance(); - - } - - @Override - public void setUp() { - // save state before test starts so we can restore it when test ends - origContextClassLoader = Thread.currentThread().getContextClassLoader(); - } - - @Override - public void tearDown() { - // restore original state so a test can't stuff up later tests. - Thread.currentThread().setContextClassLoader(origContextClassLoader); - } - - private ClassLoader origContextClassLoader; -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.logging; + +import junit.framework.TestCase; + +/** + * testcase to emulate container and application isolated from container + */ +public class LoadTestCase extends TestCase{ + //TODO: need some way to add service provider packages + static private String LOG_PCKG[] = {"org.apache.commons.logging", + "org.apache.commons.logging.impl"}; + + /** + * A custom classloader which "duplicates" logging classes available + * in the parent classloader into itself. + * <p> + * When asked to load a class that is in one of the LOG_PCKG packages, + * it loads the class itself (child-first). This class doesn't need + * to be set up with a classpath, as it simply uses the same classpath + * as the classloader that loaded it. + */ + static class AppClassLoader extends ClassLoader { + + java.util.Map classes = new java.util.HashMap(); + + AppClassLoader(final ClassLoader parent) { + super(parent); + } + + private Class def(final String name) throws ClassNotFoundException { + + Class result = (Class) classes.get(name); + if (result != null) { + return result; + } + + try { + + final ClassLoader cl = this.getClass().getClassLoader(); + final String classFileName = name.replace('.', '/') + ".class"; + final java.io.InputStream is = cl.getResourceAsStream(classFileName); + final java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + + while (is.available() > 0) { + out.write(is.read()); + } + + final byte data[] = out.toByteArray(); + + result = super.defineClass(name, data, 0, data.length); + classes.put(name, result); + + return result; + + } catch (final java.io.IOException ioe) { + + throw new ClassNotFoundException(name + " caused by " + ioe.getMessage()); + } + + } + + // not very trivial to emulate we must implement "findClass", + // but it will delegete to junit class loder first + @Override + public Class loadClass(final String name) throws ClassNotFoundException { + + // isolates all logging classes, application in the same classloader too. + // filters exeptions to simlify handling in test + for (final String element : LOG_PCKG) { + if (name.startsWith(element) && name.indexOf("Exception") == -1) { + return def(name); + } + } + return super.loadClass(name); + } + + } + + + /** + * Call the static setAllowFlawedContext method on the specified class + * (expected to be a UserClass loaded via a custom classloader), passing + * it the specified state parameter. + */ + private void setAllowFlawedContext(final Class c, final String state) throws Exception { + final Class[] params = {String.class}; + final java.lang.reflect.Method m = c.getDeclaredMethod("setAllowFlawedContext", params); + m.invoke(null, state); + } + + /** + * Test what happens when we play various classloader tricks like those + * that happen in web and j2ee containers. + * <p> + * Note that this test assumes that commons-logging.jar and log4j.jar + * are available via the system classpath. + */ + public void testInContainer()throws Exception{ + + //problem can be in this step (broken app container or missconfiguration) + //1. Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); + //2. Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + // we expect this : + // 1. Thread.currentThread().setContextClassLoader(appLoader); + // 2. Thread.currentThread().setContextClassLoader(null); + + // Context classloader is same as class calling into log + Class cls = reload(); + Thread.currentThread().setContextClassLoader(cls.getClassLoader()); + execute(cls); + + // Context classloader is the "bootclassloader". This is technically + // bad, but LogFactoryImpl.ALLOW_FLAWED_CONTEXT defaults to true so + // this test should pass. + cls = reload(); + Thread.currentThread().setContextClassLoader(null); + execute(cls); + + // Context classloader is the "bootclassloader". This is same as above + // except that ALLOW_FLAWED_CONTEXT is set to false; an error should + // now be reported. + cls = reload(); + Thread.currentThread().setContextClassLoader(null); + try { + setAllowFlawedContext(cls, "false"); + execute(cls); + fail("Logging config succeeded when context classloader was null!"); + } catch(final LogConfigurationException ex) { + // expected; the boot classloader doesn't *have* JCL available + } + + // Context classloader is the system classloader. + // + // This is expected to cause problems, as LogFactoryImpl will attempt + // to use the system classloader to load the Log4JLogger class, which + // will then be unable to cast that object to the Log interface loaded + // via the child classloader. However as ALLOW_FLAWED_CONTEXT defaults + // to true this test should pass. + cls = reload(); + Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); + execute(cls); + + // Context classloader is the system classloader. This is the same + // as above except that ALLOW_FLAWED_CONTEXT is set to false; an error + // should now be reported. + cls = reload(); + Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); + try { + setAllowFlawedContext(cls, "false"); + execute(cls); + fail("Error: somehow downcast a Logger loaded via system classloader" + + " to the Log interface loaded via a custom classloader"); + } catch(final LogConfigurationException ex) { + // expected + } + } + + /** + * Load class UserClass via a temporary classloader which is a child of + * the classloader used to load this test class. + */ + private Class reload() throws Exception { + Class testObjCls = null; + final AppClassLoader appLoader = new AppClassLoader(this.getClass().getClassLoader()); + try { + + testObjCls = appLoader.loadClass(UserClass.class.getName()); + + } catch (final ClassNotFoundException cnfe) { + throw cnfe; + } catch (final Throwable t) { + t.printStackTrace(); + fail("AppClassLoader failed "); + } + + assertSame("app isolated", testObjCls.getClassLoader(), appLoader); + + return testObjCls; + + } + + + private void execute(final Class cls) throws Exception { + cls.newInstance(); + } + + @Override + public void setUp() { + // save state before test starts so we can restore it when test ends + origContextClassLoader = Thread.currentThread().getContextClassLoader(); + } + + @Override + public void tearDown() { + // restore original state so a test can't stuff up later tests. + Thread.currentThread().setContextClassLoader(origContextClassLoader); + } + + private ClassLoader origContextClassLoader; +} diff --git a/src/test/java/org/apache/commons/logging/avalon/AvalonLoggerTestCase.java b/src/test/java/org/apache/commons/logging/avalon/AvalonLoggerTestCase.java index c408d5a..bce0a85 100644 --- a/src/test/java/org/apache/commons/logging/avalon/AvalonLoggerTestCase.java +++ b/src/test/java/org/apache/commons/logging/avalon/AvalonLoggerTestCase.java @@ -1,45 +1,43 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.logging.avalon; - -import org.apache.avalon.framework.logger.NullLogger; -import org.apache.commons.logging.impl.AvalonLogger; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.AbstractLogTest; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * @author <a href="mailto:ne...@apache.org">Neeme Praks</a> - * @version $Revision$ $Date$ - */ -public class AvalonLoggerTestCase extends AbstractLogTest { - - public static Test suite() { - final TestSuite suite = new TestSuite(); - suite.addTestSuite(AvalonLoggerTestCase.class); - return suite; - } - - @Override - public Log getLogObject() { - // Output does not seem to be used, so don't display it. - final Log log = new AvalonLogger(new NullLogger()); - return log; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.logging.avalon; + +import org.apache.avalon.framework.logger.NullLogger; +import org.apache.commons.logging.impl.AvalonLogger; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.AbstractLogTest; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + */ +public class AvalonLoggerTestCase extends AbstractLogTest { + + public static Test suite() { + final TestSuite suite = new TestSuite(); + suite.addTestSuite(AvalonLoggerTestCase.class); + return suite; + } + + @Override + public Log getLogObject() { + // Output does not seem to be used, so don't display it. + final Log log = new AvalonLogger(new NullLogger()); + return log; + } +} diff --git a/src/test/java/org/apache/commons/logging/jdk14/CustomConfigTestCase.java b/src/test/java/org/apache/commons/logging/jdk14/CustomConfigTestCase.java index 72d6ca6..9d058e8 100644 --- a/src/test/java/org/apache/commons/logging/jdk14/CustomConfigTestCase.java +++ b/src/test/java/org/apache/commons/logging/jdk14/CustomConfigTestCase.java @@ -1,399 +1,396 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging.jdk14; - - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.util.Iterator; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.LogRecord; -import java.util.logging.Logger; - -import junit.framework.Test; - -import org.apache.commons.logging.DummyException; -import org.apache.commons.logging.PathableClassLoader; -import org.apache.commons.logging.PathableTestSuite; - - -/** - * <p>TestCase for JDK 1.4 logging when running on a JDK 1.4 system with - * custom configuration, so that JDK 1.4 should be selected and an appropriate - * logger configured per the configuration properties.</p> - * - * @author Craig R. McClanahan - * @version $Revision$ $Date$ - */ - -public class CustomConfigTestCase extends DefaultConfigTestCase { - - protected static final String HANDLER_NAME = "org.apache.commons.logging.jdk14.TestHandler"; - - // ----------------------------------------------------------- Constructors - - - /** - * <p>Construct a new instance of this test case.</p> - * - * @param name Name of the test case - */ - public CustomConfigTestCase(final String name) { - super(name); - } - - - // ----------------------------------------------------- Instance Variables - - - /** - * <p>The customized {@code Handler} we will be using.</p> - */ - protected TestHandler handler; - - - /** - * <p>The underlying {@code Handler}s we will be using.</p> - */ - protected Handler handlers[]; - - - /** - * <p>The underlying {@code Logger} we will be using.</p> - */ - protected Logger logger; - - - /** - * <p>The underlying {@code LogManager} we will be using.</p> - */ - protected LogManager manager; - - - /** - * <p>The message levels that should have been logged.</p> - */ - protected Level testLevels[] = - { Level.FINE, Level.INFO, Level.WARNING, Level.SEVERE, Level.SEVERE }; - - - /** - * <p>The message strings that should have been logged.</p> - */ - protected String testMessages[] = - { "debug", "info", "warn", "error", "fatal" }; - - - // ------------------------------------------- JUnit Infrastructure Methods - - - /** - * Given the name of a class that is somewhere in the classpath of the provided - * classloader, return the contents of the corresponding .class file. - */ - protected static byte[] readClass(final String name, final ClassLoader srcCL) throws Exception { - final String resName = name.replace('.', '/') + ".class"; - System.err.println("Trying to load resource [" + resName + "]"); - final InputStream is = srcCL.getResourceAsStream(resName); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.err.println("Reading resource [" + resName + "]"); - final byte[] buf = new byte[1000]; - for(;;) { - final int read = is.read(buf); - if (read <= 0) { - break; - } - baos.write(buf, 0, read); - } - is.close(); - return baos.toByteArray(); - } - - /** - * Make a class available in the system classloader even when its classfile is - * not present in the classpath configured for that classloader. This only - * works for classes for which all dependencies are already loaded in - * that classloader. - */ - protected static void loadTestHandler(final String className, final ClassLoader targetCL) { - try { - targetCL.loadClass(className); - // fail("Class already in target classloader"); - return; - } catch(final ClassNotFoundException ex) { - // ok, go ahead and load it - } - - try { - final ClassLoader srcCL = CustomConfigAPITestCase.class.getClassLoader(); - final byte[] classData = readClass(className, srcCL); - - final Class[] params = new Class[] { String.class, classData.getClass(), Integer.TYPE, Integer.TYPE }; - final Method m = ClassLoader.class.getDeclaredMethod("defineClass", params); - - final Object[] args = new Object[4]; - args[0] = className; - args[1] = classData; - args[2] = new Integer(0); - args[3] = new Integer(classData.length); - m.setAccessible(true); - m.invoke(targetCL, args); - } catch(final Exception e) { - e.printStackTrace(); - fail("Unable to load class " + className); - } - } - - /** - * Set up instance variables required by this test case. - */ - @Override - public void setUp() throws Exception { - setUpManager - ("org/apache/commons/logging/jdk14/CustomConfig.properties"); - setUpLogger(this.getClass().getName()); - setUpHandlers(); - setUpFactory(); - setUpLog(this.getClass().getName()); - } - - - /** - * Return the tests included in this test suite. - */ - public static Test suite() throws Exception { - final PathableClassLoader cl = new PathableClassLoader(null); - cl.useExplicitLoader("junit.", Test.class.getClassLoader()); - - // the TestHandler class must be accessable from the System classloader - // in order for java.util.logging.LogManager.readConfiguration to - // be able to instantiate it. And this test case must see the same - // class in order to be able to access its data. Yes this is ugly - // but the whole jdk14 API is a ******* mess anyway. - final ClassLoader scl = ClassLoader.getSystemClassLoader(); - loadTestHandler(HANDLER_NAME, scl); - cl.useExplicitLoader(HANDLER_NAME, scl); - cl.addLogicalLib("commons-logging"); - cl.addLogicalLib("testclasses"); - - final Class testClass = cl.loadClass(CustomConfigTestCase.class.getName()); - return new PathableTestSuite(testClass, cl); - } - - /** - * Tear down instance variables required by this test case. - */ - @Override - public void tearDown() { - super.tearDown(); - handlers = null; - logger = null; - manager = null; - } - - - // ----------------------------------------------------------- Test Methods - - - // Test logging message strings with exceptions - public void testExceptionMessages() throws Exception { - - logExceptionMessages(); - checkLogRecords(true); - - } - - - // Test logging plain message strings - public void testPlainMessages() throws Exception { - - logPlainMessages(); - checkLogRecords(false); - - } - - - // Test pristine Handlers instances - public void testPristineHandlers() { - - assertNotNull(handlers); - assertEquals(1, handlers.length); - assertTrue(handlers[0] instanceof TestHandler); - assertNotNull(handler); - - } - - - // Test pristine Logger instance - public void testPristineLogger() { - - assertNotNull("Logger exists", logger); - assertEquals("Logger name", this.getClass().getName(), logger.getName()); - - // Assert which logging levels have been enabled - assertTrue(logger.isLoggable(Level.SEVERE)); - assertTrue(logger.isLoggable(Level.WARNING)); - assertTrue(logger.isLoggable(Level.INFO)); - assertTrue(logger.isLoggable(Level.CONFIG)); - assertTrue(logger.isLoggable(Level.FINE)); - assertFalse(logger.isLoggable(Level.FINER)); - assertFalse(logger.isLoggable(Level.FINEST)); - - } - - - // Test Serializability of Log instance - @Override - public void testSerializable() throws Exception { - - super.testSerializable(); - testExceptionMessages(); - - } - - - // -------------------------------------------------------- Support Methods - - - // Check the log instance - @Override - protected void checkLog() { - - assertNotNull("Log exists", log); - assertEquals("Log class", - "org.apache.commons.logging.impl.Jdk14Logger", - log.getClass().getName()); - - // Assert which logging levels have been enabled - assertTrue(log.isFatalEnabled()); - assertTrue(log.isErrorEnabled()); - assertTrue(log.isWarnEnabled()); - assertTrue(log.isInfoEnabled()); - assertTrue(log.isDebugEnabled()); - assertFalse(log.isTraceEnabled()); - - } - - - // Check the recorded messages - protected void checkLogRecords(final boolean thrown) { - final Iterator records = handler.records(); - for (int i = 0; i < testMessages.length; i++) { - assertTrue(records.hasNext()); - final LogRecord record = (LogRecord) records.next(); - assertEquals("LogRecord level", - testLevels[i], record.getLevel()); - assertEquals("LogRecord message", - testMessages[i], record.getMessage()); - assertTrue("LogRecord class", - record.getSourceClassName().startsWith( - "org.apache.commons.logging.jdk14.CustomConfig")); - if (thrown) { - assertEquals("LogRecord method", - "logExceptionMessages", - record.getSourceMethodName()); - } else { - assertEquals("LogRecord method", - "logPlainMessages", - record.getSourceMethodName()); - } - if (thrown) { - assertNotNull("LogRecord thrown", record.getThrown()); - assertTrue("LogRecord thrown type", - record.getThrown() instanceof DummyException); - } else { - assertNull("LogRecord thrown", - record.getThrown()); - } - } - assertFalse(records.hasNext()); - handler.flush(); - } - - - // Log the messages with exceptions - protected void logExceptionMessages() { - final Throwable t = new DummyException(); - log.trace("trace", t); // Should not actually get logged - log.debug("debug", t); - log.info("info", t); - log.warn("warn", t); - log.error("error", t); - log.fatal("fatal", t); - } - - - // Log the plain messages - protected void logPlainMessages() { - log.trace("trace"); // Should not actually get logged - log.debug("debug"); - log.info("info"); - log.warn("warn"); - log.error("error"); - log.fatal("fatal"); - } - - - // Set up handlers instance - protected void setUpHandlers() throws Exception { - Logger parent = logger; - while (parent.getParent() != null) { - parent = parent.getParent(); - } - handlers = parent.getHandlers(); - - // The CustomConfig.properties file explicitly defines one handler class - // to be attached to the root logger, so if it isn't there then - // something is badly wrong... - // - // Yes this testing is also done in testPristineHandlers but - // unfortunately: - // * we need to set up the handlers variable here, - // * we don't want that to be set up incorrectly, as that can - // produce weird error messages in other tests, and - // * we can't rely on testPristineHandlers being the first - // test to run. - // so we need to test things here too. - assertNotNull("No Handlers defined for JDK14 logging", handlers); - assertEquals("Unexpected number of handlers for JDK14 logging", 1, handlers.length); - assertNotNull("Handler is null", handlers[0]); - assertTrue("Handler not of expected type", handlers[0] instanceof TestHandler); - handler = (TestHandler) handlers[0]; - } - - - // Set up logger instance - protected void setUpLogger(final String name) throws Exception { - logger = Logger.getLogger(name); - } - - - // Set up LogManager instance - protected void setUpManager(final String config) throws Exception { - manager = LogManager.getLogManager(); - final InputStream is = - this.getClass().getClassLoader().getResourceAsStream(config); - manager.readConfiguration(is); - is.close(); - } - - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging.jdk14; + + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.util.Iterator; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogManager; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import junit.framework.Test; + +import org.apache.commons.logging.DummyException; +import org.apache.commons.logging.PathableClassLoader; +import org.apache.commons.logging.PathableTestSuite; + + +/** + * <p>TestCase for JDK 1.4 logging when running on a JDK 1.4 system with + * custom configuration, so that JDK 1.4 should be selected and an appropriate + * logger configured per the configuration properties.</p> + */ + +public class CustomConfigTestCase extends DefaultConfigTestCase { + + protected static final String HANDLER_NAME = "org.apache.commons.logging.jdk14.TestHandler"; + + // ----------------------------------------------------------- Constructors + + + /** + * <p>Construct a new instance of this test case.</p> + * + * @param name Name of the test case + */ + public CustomConfigTestCase(final String name) { + super(name); + } + + + // ----------------------------------------------------- Instance Variables + + + /** + * <p>The customized {@code Handler} we will be using.</p> + */ + protected TestHandler handler; + + + /** + * <p>The underlying {@code Handler}s we will be using.</p> + */ + protected Handler handlers[]; + + + /** + * <p>The underlying {@code Logger} we will be using.</p> + */ + protected Logger logger; + + + /** + * <p>The underlying {@code LogManager} we will be using.</p> + */ + protected LogManager manager; + + + /** + * <p>The message levels that should have been logged.</p> + */ + protected Level testLevels[] = + { Level.FINE, Level.INFO, Level.WARNING, Level.SEVERE, Level.SEVERE }; + + + /** + * <p>The message strings that should have been logged.</p> + */ + protected String testMessages[] = + { "debug", "info", "warn", "error", "fatal" }; + + + // ------------------------------------------- JUnit Infrastructure Methods + + + /** + * Given the name of a class that is somewhere in the classpath of the provided + * classloader, return the contents of the corresponding .class file. + */ + protected static byte[] readClass(final String name, final ClassLoader srcCL) throws Exception { + final String resName = name.replace('.', '/') + ".class"; + System.err.println("Trying to load resource [" + resName + "]"); + final InputStream is = srcCL.getResourceAsStream(resName); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + System.err.println("Reading resource [" + resName + "]"); + final byte[] buf = new byte[1000]; + for(;;) { + final int read = is.read(buf); + if (read <= 0) { + break; + } + baos.write(buf, 0, read); + } + is.close(); + return baos.toByteArray(); + } + + /** + * Make a class available in the system classloader even when its classfile is + * not present in the classpath configured for that classloader. This only + * works for classes for which all dependencies are already loaded in + * that classloader. + */ + protected static void loadTestHandler(final String className, final ClassLoader targetCL) { + try { + targetCL.loadClass(className); + // fail("Class already in target classloader"); + return; + } catch(final ClassNotFoundException ex) { + // ok, go ahead and load it + } + + try { + final ClassLoader srcCL = CustomConfigAPITestCase.class.getClassLoader(); + final byte[] classData = readClass(className, srcCL); + + final Class[] params = new Class[] { String.class, classData.getClass(), Integer.TYPE, Integer.TYPE }; + final Method m = ClassLoader.class.getDeclaredMethod("defineClass", params); + + final Object[] args = new Object[4]; + args[0] = className; + args[1] = classData; + args[2] = new Integer(0); + args[3] = new Integer(classData.length); + m.setAccessible(true); + m.invoke(targetCL, args); + } catch(final Exception e) { + e.printStackTrace(); + fail("Unable to load class " + className); + } + } + + /** + * Set up instance variables required by this test case. + */ + @Override + public void setUp() throws Exception { + setUpManager + ("org/apache/commons/logging/jdk14/CustomConfig.properties"); + setUpLogger(this.getClass().getName()); + setUpHandlers(); + setUpFactory(); + setUpLog(this.getClass().getName()); + } + + + /** + * Return the tests included in this test suite. + */ + public static Test suite() throws Exception { + final PathableClassLoader cl = new PathableClassLoader(null); + cl.useExplicitLoader("junit.", Test.class.getClassLoader()); + + // the TestHandler class must be accessable from the System classloader + // in order for java.util.logging.LogManager.readConfiguration to + // be able to instantiate it. And this test case must see the same + // class in order to be able to access its data. Yes this is ugly + // but the whole jdk14 API is a ******* mess anyway. + final ClassLoader scl = ClassLoader.getSystemClassLoader(); + loadTestHandler(HANDLER_NAME, scl); + cl.useExplicitLoader(HANDLER_NAME, scl); + cl.addLogicalLib("commons-logging"); + cl.addLogicalLib("testclasses"); + + final Class testClass = cl.loadClass(CustomConfigTestCase.class.getName()); + return new PathableTestSuite(testClass, cl); + } + + /** + * Tear down instance variables required by this test case. + */ + @Override + public void tearDown() { + super.tearDown(); + handlers = null; + logger = null; + manager = null; + } + + + // ----------------------------------------------------------- Test Methods + + + // Test logging message strings with exceptions + public void testExceptionMessages() throws Exception { + + logExceptionMessages(); + checkLogRecords(true); + + } + + + // Test logging plain message strings + public void testPlainMessages() throws Exception { + + logPlainMessages(); + checkLogRecords(false); + + } + + + // Test pristine Handlers instances + public void testPristineHandlers() { + + assertNotNull(handlers); + assertEquals(1, handlers.length); + assertTrue(handlers[0] instanceof TestHandler); + assertNotNull(handler); + + } + + + // Test pristine Logger instance + public void testPristineLogger() { + + assertNotNull("Logger exists", logger); + assertEquals("Logger name", this.getClass().getName(), logger.getName()); + + // Assert which logging levels have been enabled + assertTrue(logger.isLoggable(Level.SEVERE)); + assertTrue(logger.isLoggable(Level.WARNING)); + assertTrue(logger.isLoggable(Level.INFO)); + assertTrue(logger.isLoggable(Level.CONFIG)); + assertTrue(logger.isLoggable(Level.FINE)); + assertFalse(logger.isLoggable(Level.FINER)); + assertFalse(logger.isLoggable(Level.FINEST)); + + } + + + // Test Serializability of Log instance + @Override + public void testSerializable() throws Exception { + + super.testSerializable(); + testExceptionMessages(); + + } + + + // -------------------------------------------------------- Support Methods + + + // Check the log instance + @Override + protected void checkLog() { + + assertNotNull("Log exists", log); + assertEquals("Log class", + "org.apache.commons.logging.impl.Jdk14Logger", + log.getClass().getName()); + + // Assert which logging levels have been enabled + assertTrue(log.isFatalEnabled()); + assertTrue(log.isErrorEnabled()); + assertTrue(log.isWarnEnabled()); + assertTrue(log.isInfoEnabled()); + assertTrue(log.isDebugEnabled()); + assertFalse(log.isTraceEnabled()); + + } + + + // Check the recorded messages + protected void checkLogRecords(final boolean thrown) { + final Iterator records = handler.records(); + for (int i = 0; i < testMessages.length; i++) { + assertTrue(records.hasNext()); + final LogRecord record = (LogRecord) records.next(); + assertEquals("LogRecord level", + testLevels[i], record.getLevel()); + assertEquals("LogRecord message", + testMessages[i], record.getMessage()); + assertTrue("LogRecord class", + record.getSourceClassName().startsWith( + "org.apache.commons.logging.jdk14.CustomConfig")); + if (thrown) { + assertEquals("LogRecord method", + "logExceptionMessages", + record.getSourceMethodName()); + } else { + assertEquals("LogRecord method", + "logPlainMessages", + record.getSourceMethodName()); + } + if (thrown) { + assertNotNull("LogRecord thrown", record.getThrown()); + assertTrue("LogRecord thrown type", + record.getThrown() instanceof DummyException); + } else { + assertNull("LogRecord thrown", + record.getThrown()); + } + } + assertFalse(records.hasNext()); + handler.flush(); + } + + + // Log the messages with exceptions + protected void logExceptionMessages() { + final Throwable t = new DummyException(); + log.trace("trace", t); // Should not actually get logged + log.debug("debug", t); + log.info("info", t); + log.warn("warn", t); + log.error("error", t); + log.fatal("fatal", t); + } + + + // Log the plain messages + protected void logPlainMessages() { + log.trace("trace"); // Should not actually get logged + log.debug("debug"); + log.info("info"); + log.warn("warn"); + log.error("error"); + log.fatal("fatal"); + } + + + // Set up handlers instance + protected void setUpHandlers() throws Exception { + Logger parent = logger; + while (parent.getParent() != null) { + parent = parent.getParent(); + } + handlers = parent.getHandlers(); + + // The CustomConfig.properties file explicitly defines one handler class + // to be attached to the root logger, so if it isn't there then + // something is badly wrong... + // + // Yes this testing is also done in testPristineHandlers but + // unfortunately: + // * we need to set up the handlers variable here, + // * we don't want that to be set up incorrectly, as that can + // produce weird error messages in other tests, and + // * we can't rely on testPristineHandlers being the first + // test to run. + // so we need to test things here too. + assertNotNull("No Handlers defined for JDK14 logging", handlers); + assertEquals("Unexpected number of handlers for JDK14 logging", 1, handlers.length); + assertNotNull("Handler is null", handlers[0]); + assertTrue("Handler not of expected type", handlers[0] instanceof TestHandler); + handler = (TestHandler) handlers[0]; + } + + + // Set up logger instance + protected void setUpLogger(final String name) throws Exception { + logger = Logger.getLogger(name); + } + + + // Set up LogManager instance + protected void setUpManager(final String config) throws Exception { + manager = LogManager.getLogManager(); + final InputStream is = + this.getClass().getClassLoader().getResourceAsStream(config); + manager.readConfiguration(is); + is.close(); + } + + +} diff --git a/src/test/java/org/apache/commons/logging/jdk14/DefaultConfigTestCase.java b/src/test/java/org/apache/commons/logging/jdk14/DefaultConfigTestCase.java index 4d0c633..05f9c4d 100644 --- a/src/test/java/org/apache/commons/logging/jdk14/DefaultConfigTestCase.java +++ b/src/test/java/org/apache/commons/logging/jdk14/DefaultConfigTestCase.java @@ -1,193 +1,158 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging.jdk14; - - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import junit.framework.Test; -import junit.framework.TestCase; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.PathableClassLoader; -import org.apache.commons.logging.PathableTestSuite; - - -/** - * <p>TestCase for JDK 1.4 logging when running on a JDK 1.4 system with - * zero configuration, and with Log4J not present (so JDK 1.4 logging - * should be automatically configured.</p> - * - * @author Craig R. McClanahan - * @version $Revision$ $Date$ - */ - -public class DefaultConfigTestCase extends TestCase { - - - // ----------------------------------------------------------- Constructors - - - /** - * <p>Construct a new instance of this test case.</p> - * - * @param name Name of the test case - */ - public DefaultConfigTestCase(final String name) { - super(name); - } - - - // ----------------------------------------------------- Instance Variables - - - /** - * <p>The {@link LogFactory} implementation we have selected.</p> - */ - protected LogFactory factory; - - - /** - * <p>The {@link Log} implementation we have selected.</p> - */ - protected Log log; - - - // ------------------------------------------- JUnit Infrastructure Methods - - - /** - * Set up instance variables required by this test case. - */ - @Override - public void setUp() throws Exception { - setUpFactory(); - setUpLog("TestLogger"); - } - - - /** - * Return the tests included in this test suite. - */ - public static Test suite() throws Exception { - final PathableClassLoader loader = new PathableClassLoader(null); - loader.useExplicitLoader("junit.", Test.class.getClassLoader()); - loader.addLogicalLib("testclasses"); - loader.addLogicalLib("commons-logging"); - - final Class testClass = loader.loadClass(DefaultConfigTestCase.class.getName()); - return new PathableTestSuite(testClass, loader); - } - - /** - * Tear down instance variables required by this test case. - */ - @Override - public void tearDown() { - log = null; - factory = null; - LogFactory.releaseAll(); - } - - - // ----------------------------------------------------------- Test Methods - - - // Test pristine Log instance - public void testPristineLog() { - - checkLog(); - - } - - - // Test pristine LogFactory instance - public void testPristineFactory() { - - assertNotNull("LogFactory exists", factory); - assertEquals("LogFactory class", - "org.apache.commons.logging.impl.LogFactoryImpl", - factory.getClass().getName()); - - final String names[] = factory.getAttributeNames(); - assertNotNull("Names exists", names); - assertEquals("Names empty", 0, names.length); - - } - - - // Test Serializability of Log instance - public void testSerializable() throws Exception { - - // Serialize and deserialize the instance - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(log); - oos.close(); - final ByteArrayInputStream bais = - new ByteArrayInputStream(baos.toByteArray()); - final ObjectInputStream ois = new ObjectInputStream(bais); - log = (Log) ois.readObject(); - ois.close(); - - // Check the characteristics of the resulting object - checkLog(); - - } - - - // -------------------------------------------------------- Support Methods - - - - // Check the log instance - protected void checkLog() { - - assertNotNull("Log exists", log); - assertEquals("Log class", - "org.apache.commons.logging.impl.Jdk14Logger", - log.getClass().getName()); - - // Can we call level checkers with no exceptions? - log.isDebugEnabled(); - log.isErrorEnabled(); - log.isFatalEnabled(); - log.isInfoEnabled(); - log.isTraceEnabled(); - log.isWarnEnabled(); - - } - - - // Set up factory instance - protected void setUpFactory() throws Exception { - factory = LogFactory.getFactory(); - } - - - // Set up log instance - protected void setUpLog(final String name) throws Exception { - log = LogFactory.getLog(name); - } - - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging.jdk14; + + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import junit.framework.Test; +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.PathableClassLoader; +import org.apache.commons.logging.PathableTestSuite; + + +/** + * <p>TestCase for JDK 1.4 logging when running on a JDK 1.4 system with + * zero configuration, and with Log4J not present (so JDK 1.4 logging + * should be automatically configured.</p> + */ +public class DefaultConfigTestCase extends TestCase { + + /** + * <p>Construct a new instance of this test case.</p> + * + * @param name Name of the test case + */ + public DefaultConfigTestCase(final String name) { + super(name); + } + + /** + * <p>The {@link LogFactory} implementation we have selected.</p> + */ + protected LogFactory factory; + + /** + * <p>The {@link Log} implementation we have selected.</p> + */ + protected Log log; + + /** + * Set up instance variables required by this test case. + */ + @Override + public void setUp() throws Exception { + setUpFactory(); + setUpLog("TestLogger"); + } + + /** + * Return the tests included in this test suite. + */ + public static Test suite() throws Exception { + final PathableClassLoader loader = new PathableClassLoader(null); + loader.useExplicitLoader("junit.", Test.class.getClassLoader()); + loader.addLogicalLib("testclasses"); + loader.addLogicalLib("commons-logging"); + + final Class testClass = loader.loadClass(DefaultConfigTestCase.class.getName()); + return new PathableTestSuite(testClass, loader); + } + + /** + * Tear down instance variables required by this test case. + */ + @Override + public void tearDown() { + log = null; + factory = null; + LogFactory.releaseAll(); + } + + // Test pristine Log instance + public void testPristineLog() { + checkLog(); + } + + // Test pristine LogFactory instance + public void testPristineFactory() { + assertNotNull("LogFactory exists", factory); + assertEquals("LogFactory class", + "org.apache.commons.logging.impl.LogFactoryImpl", + factory.getClass().getName()); + + final String names[] = factory.getAttributeNames(); + assertNotNull("Names exists", names); + assertEquals("Names empty", 0, names.length); + } + + + // Test Serializability of Log instance + public void testSerializable() throws Exception { + + // Serialize and deserialize the instance + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(log); + oos.close(); + final ByteArrayInputStream bais = + new ByteArrayInputStream(baos.toByteArray()); + final ObjectInputStream ois = new ObjectInputStream(bais); + log = (Log) ois.readObject(); + ois.close(); + + // Check the characteristics of the resulting object + checkLog(); + + } + + // Check the log instance + protected void checkLog() { + + assertNotNull("Log exists", log); + assertEquals("Log class", + "org.apache.commons.logging.impl.Jdk14Logger", + log.getClass().getName()); + + // Can we call level checkers with no exceptions? + log.isDebugEnabled(); + log.isErrorEnabled(); + log.isFatalEnabled(); + log.isInfoEnabled(); + log.isTraceEnabled(); + log.isWarnEnabled(); + + } + + // Set up factory instance + protected void setUpFactory() throws Exception { + factory = LogFactory.getFactory(); + } + + // Set up log instance + protected void setUpLog(final String name) throws Exception { + log = LogFactory.getLog(name); + } + +} diff --git a/src/test/java/org/apache/commons/logging/jdk14/TestHandler.java b/src/test/java/org/apache/commons/logging/jdk14/TestHandler.java index b4184a1..4ec320c 100644 --- a/src/test/java/org/apache/commons/logging/jdk14/TestHandler.java +++ b/src/test/java/org/apache/commons/logging/jdk14/TestHandler.java @@ -1,73 +1,53 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.logging.jdk14; - - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Handler; -import java.util.logging.LogRecord; - - -/** - * <p>Test implementation of {@code java.util.logging.Handler}.</p> - * - * @author Craig R. McClanahan - * @version $Revision$ $Date$ - */ - -public class TestHandler extends Handler { - - - - // ----------------------------------------------------- Instance Variables - - - // The set of logged records for this handler - private final List records = new ArrayList(); - - - // --------------------------------------------------------- Public Methods - - - public Iterator records() { - return records.iterator(); - } - - - // -------------------------------------------------------- Handler Methods - - - @Override - public void close() { - } - - - @Override - public void flush() { - records.clear(); - } - - - @Override - public void publish(final LogRecord record) { - records.add(record); - } - - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.logging.jdk14; + + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; + + +/** + * <p>Test implementation of {@code java.util.logging.Handler}.</p> + */ +public class TestHandler extends Handler { + + // The set of logged records for this handler + private final List records = new ArrayList(); + + public Iterator records() { + return records.iterator(); + } + + @Override + public void close() { + } + + @Override + public void flush() { + records.clear(); + } + + @Override + public void publish(final LogRecord record) { + records.add(record); + } + +} diff --git a/src/test/java/org/apache/commons/logging/simple/CustomConfigTestCase.java b/src/test/java/org/apache/commons/logging/simple/CustomConfigTestCase.java index 2143de3..cd7edef 100644 --- a/src/test/java/org/apache/commons/logging/simple/CustomConfigTestCase.java +++ b/src/test/java/org/apache/commons/logging/simple/CustomConfigTestCase.java @@ -34,22 +34,14 @@ import org.apache.commons.logging.impl.SimpleLog; /** * <p>TestCase for simple logging when running with custom configuration * properties.</p> - * - * @author Craig R. McClanahan - * @version $Revision$ $Date$ */ public class CustomConfigTestCase extends DefaultConfigTestCase { - - // ----------------------------------------------------- Instance Variables - - /** * <p>The expected log records.</p> */ protected List expected; - /** * <p>The message levels that should have been logged.</p> */ @@ -58,16 +50,12 @@ public class CustomConfigTestCase extends DefaultConfigTestCase { { Level.FINE, Level.INFO, Level.WARNING, Level.SEVERE, Level.SEVERE }; */ - /** * <p>The message strings that should have been logged.</p> */ protected String testMessages[] = { "debug", "info", "warn", "error", "fatal" }; - - // ------------------------------------------- JUnit Infrastructure Methods - /** * Set system properties that will control the LogFactory/Log objects * when they are created. Subclasses can override this method to @@ -95,7 +83,6 @@ public class CustomConfigTestCase extends DefaultConfigTestCase { setUpLog("DecoratedLogger"); } - /** * Return the tests included in this test suite. * <p> @@ -129,46 +116,30 @@ public class CustomConfigTestCase extends DefaultConfigTestCase { expected = null; } - - // ----------------------------------------------------------- Test Methods - - // Test logging message strings with exceptions public void testExceptionMessages() throws Exception { - ((DecoratedSimpleLog) log).clearCache(); logExceptionMessages(); checkExpected(); - } - // Test logging plain message strings public void testPlainMessages() throws Exception { - ((DecoratedSimpleLog) log).clearCache(); logPlainMessages(); checkExpected(); - } - // Test Serializability of standard instance @Override public void testSerializable() throws Exception { - ((DecoratedSimpleLog) log).clearCache(); logPlainMessages(); super.testSerializable(); logExceptionMessages(); checkExpected(); - } - - // -------------------------------------------------------- Support Methods - - // Check the decorated log instance @Override protected void checkDecorated() { @@ -213,7 +184,6 @@ public class CustomConfigTestCase extends DefaultConfigTestCase { // Check the actual log records against the expected ones protected void checkExpected() { - final List acts = ((DecoratedSimpleLog) log).getCache(); final Iterator exps = expected.iterator(); int n = 0; @@ -224,22 +194,18 @@ public class CustomConfigTestCase extends DefaultConfigTestCase { assertEquals("Row " + n + " message", exp.message, act.message); assertEquals("Row " + n + " throwable", exp.t, act.t); } - } // Check the standard log instance @Override protected void checkStandard() { - checkDecorated(); - } // Log the messages with exceptions protected void logExceptionMessages() { - // Generate log records final Throwable t = new DummyException(); log.trace("trace", t); // Should not actually get logged @@ -255,13 +221,11 @@ public class CustomConfigTestCase extends DefaultConfigTestCase { expected.add(new LogRecord(SimpleLog.LOG_LEVEL_WARN, "warn", t)); expected.add(new LogRecord(SimpleLog.LOG_LEVEL_ERROR, "error", t)); expected.add(new LogRecord(SimpleLog.LOG_LEVEL_FATAL, "fatal", t)); - } // Log the plain messages protected void logPlainMessages() { - // Generate log records log.trace("trace"); // Should not actually get logged log.debug("debug"); @@ -276,8 +240,5 @@ public class CustomConfigTestCase extends DefaultConfigTestCase { expected.add(new LogRecord(SimpleLog.LOG_LEVEL_WARN, "warn", null)); expected.add(new LogRecord(SimpleLog.LOG_LEVEL_ERROR, "error", null)); expected.add(new LogRecord(SimpleLog.LOG_LEVEL_FATAL, "fatal", null)); - } - - } diff --git a/src/test/java/org/apache/commons/logging/simple/DefaultConfigTestCase.java b/src/test/java/org/apache/commons/logging/simple/DefaultConfigTestCase.java index bfccecf..682af46 100644 --- a/src/test/java/org/apache/commons/logging/simple/DefaultConfigTestCase.java +++ b/src/test/java/org/apache/commons/logging/simple/DefaultConfigTestCase.java @@ -36,32 +36,20 @@ import org.apache.commons.logging.impl.SimpleLog; /** * <p>TestCase for simple logging when running with zero configuration * other than selecting the SimpleLog implementation.</p> - * - * @author Craig R. McClanahan - * @version $Revision$ $Date$ */ public class DefaultConfigTestCase extends TestCase { - - // ----------------------------------------------------- Instance Variables - - /** * <p>The {@link LogFactory} implementation we have selected.</p> */ protected LogFactory factory; - /** * <p>The {@link Log} implementation we have selected.</p> */ protected Log log; - - // ------------------------------------------- JUnit Infrastructure Methods - - /** * Return the tests included in this test suite. * <p> @@ -118,30 +106,19 @@ public class DefaultConfigTestCase extends TestCase { LogFactory.releaseAll(); } - - // ----------------------------------------------------------- Test Methods - - // Test pristine DecoratedSimpleLog instance public void testPristineDecorated() { - setUpDecorated("DecoratedLogger"); checkDecorated(); - } - // Test pristine Log instance public void testPristineLog() { - checkStandard(); - } - // Test pristine LogFactory instance public void testPristineFactory() { - assertNotNull("LogFactory exists", factory); assertEquals("LogFactory class", "org.apache.commons.logging.impl.LogFactoryImpl", @@ -150,10 +127,8 @@ public class DefaultConfigTestCase extends TestCase { final String names[] = factory.getAttributeNames(); assertNotNull("Names exists", names); assertEquals("Names empty", 0, names.length); - } - // Test Serializability of standard instance public void testSerializable() throws Exception { @@ -173,14 +148,8 @@ public class DefaultConfigTestCase extends TestCase { } - - // -------------------------------------------------------- Support Methods - - - // Check the decorated log instance protected void checkDecorated() { - assertNotNull("Log exists", log); assertEquals("Log class", "org.apache.commons.logging.simple.DecoratedSimpleLog", @@ -204,13 +173,11 @@ public class DefaultConfigTestCase extends TestCase { ((DecoratedSimpleLog) log).getLogName()); assertFalse(((DecoratedSimpleLog) log).getShowDateTime()); assertTrue(((DecoratedSimpleLog) log).getShowShortName()); - } // Check the standard log instance protected void checkStandard() { - assertNotNull("Log exists", log); assertEquals("Log class", "org.apache.commons.logging.impl.SimpleLog", @@ -226,7 +193,6 @@ public class DefaultConfigTestCase extends TestCase { // Can we retrieve the current log level? assertEquals(SimpleLog.LOG_LEVEL_INFO, ((SimpleLog) log).getLevel()); - } @@ -247,5 +213,4 @@ public class DefaultConfigTestCase extends TestCase { log = LogFactory.getLog(name); } - }