1
0

We don't use author tag, CVS/SVN tags or lots of whitespace

Add a space before { when missing
This commit is contained in:
Gary Gregory
2022-08-30 09:46:14 -04:00
parent 0080bcbf79
commit 5f5affb467
8 changed files with 932 additions and 1105 deletions

View File

@@ -1,94 +1,66 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.commons.logging; package org.apache.commons.logging;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
* Generic tests that can be applied to any log adapter by * Generic tests that can be applied to any log adapter by
* subclassing this class and defining method getLogObject * subclassing this class and defining method getLogObject
* appropriately. * appropriately.
* */
* @author Sean C. Sullivan public abstract class AbstractLogTest extends TestCase {
* @version $Revision$
*/ public abstract Log getLogObject();
public abstract class AbstractLogTest extends TestCase {
public void testLoggingWithNullParameters()
public abstract Log getLogObject(); {
final Log log = this.getLogObject();
public void testLoggingWithNullParameters() assertNotNull(log);
{
final Log log = this.getLogObject(); log.debug(null);
log.debug(null, null);
assertNotNull(log); log.debug(log.getClass().getName() + ": debug statement");
log.debug(log.getClass().getName() + ": debug statement w/ null exception", new RuntimeException());
log.debug(null); log.error(null);
log.error(null, null);
log.debug(null, null); log.error(log.getClass().getName() + ": error statement");
log.error(log.getClass().getName() + ": error statement w/ null exception", new RuntimeException());
log.debug(log.getClass().getName() + ": debug statement");
log.fatal(null);
log.debug(log.getClass().getName() + ": debug statement w/ null exception", new RuntimeException()); log.fatal(null, null);
log.fatal(log.getClass().getName() + ": fatal statement");
log.fatal(log.getClass().getName() + ": fatal statement w/ null exception", new RuntimeException());
log.error(null);
log.info(null);
log.error(null, null); log.info(null, null);
log.info(log.getClass().getName() + ": info statement");
log.error(log.getClass().getName() + ": error statement"); log.info(log.getClass().getName() + ": info statement w/ null exception", new RuntimeException());
log.error(log.getClass().getName() + ": error statement w/ null exception", new RuntimeException()); log.trace(null);
log.trace(null, null);
log.trace(log.getClass().getName() + ": trace statement");
log.fatal(null); log.trace(log.getClass().getName() + ": trace statement w/ null exception", new RuntimeException());
log.fatal(null, null); log.warn(null);
log.warn(null, null);
log.fatal(log.getClass().getName() + ": fatal statement"); log.warn(log.getClass().getName() + ": warn statement");
log.warn(log.getClass().getName() + ": warn statement w/ null exception", new RuntimeException());
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());
}
}

View File

@@ -1,227 +1,216 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.commons.logging; package org.apache.commons.logging;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
* testcase to emulate container and application isolated from container * testcase to emulate container and application isolated from container
* @author baliuka */
*/ public class LoadTestCase extends TestCase{
public class LoadTestCase extends TestCase{ //TODO: need some way to add service provider packages
//TODO: need some way to add service provider packages static private String LOG_PCKG[] = {"org.apache.commons.logging",
static private String LOG_PCKG[] = {"org.apache.commons.logging", "org.apache.commons.logging.impl"};
"org.apache.commons.logging.impl"};
/**
/** * A custom classloader which "duplicates" logging classes available
* A custom classloader which "duplicates" logging classes available * in the parent classloader into itself.
* in the parent classloader into itself. * <p>
* <p> * When asked to load a class that is in one of the LOG_PCKG packages,
* 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
* 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
* to be set up with a classpath, as it simply uses the same classpath * as the classloader that loaded it.
* as the classloader that loaded it. */
*/ static class AppClassLoader extends ClassLoader {
static class AppClassLoader extends ClassLoader{
java.util.Map classes = new java.util.HashMap();
java.util.Map classes = new java.util.HashMap();
AppClassLoader(final ClassLoader parent) {
AppClassLoader(final ClassLoader parent){ super(parent);
super(parent); }
}
private Class def(final String name) throws ClassNotFoundException {
private Class def(final String name)throws ClassNotFoundException{
Class result = (Class) classes.get(name);
Class result = (Class)classes.get(name); if (result != null) {
if(result != null){ return result;
return result; }
}
try {
try{
final ClassLoader cl = this.getClass().getClassLoader();
final ClassLoader cl = this.getClass().getClassLoader(); final String classFileName = name.replace('.', '/') + ".class";
final String classFileName = name.replace('.','/') + ".class"; final java.io.InputStream is = cl.getResourceAsStream(classFileName);
final java.io.InputStream is = cl.getResourceAsStream(classFileName); final java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
final java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
while (is.available() > 0) {
while(is.available() > 0){ out.write(is.read());
out.write(is.read()); }
}
final byte data[] = out.toByteArray();
final byte data [] = out.toByteArray();
result = super.defineClass(name, data, 0, data.length);
result = super.defineClass(name, data, 0, data.length ); classes.put(name, result);
classes.put(name,result);
return result;
return result;
} catch (final java.io.IOException ioe) {
}catch(final java.io.IOException ioe){
throw new ClassNotFoundException(name + " caused by " + ioe.getMessage());
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
// not very trivial to emulate we must implement "findClass", public Class loadClass(final String name) throws ClassNotFoundException {
// but it will delegete to junit class loder first
@Override // isolates all logging classes, application in the same classloader too.
public Class loadClass(final String name)throws ClassNotFoundException{ // filters exeptions to simlify handling in test
for (final String element : LOG_PCKG) {
//isolates all logging classes, application in the same classloader too. if (name.startsWith(element) && name.indexOf("Exception") == -1) {
//filters exeptions to simlify handling in test return def(name);
for (final String element : LOG_PCKG) { }
if( name.startsWith( element ) && }
name.indexOf("Exception") == -1 ){ return super.loadClass(name);
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.
/** */
* Call the static setAllowFlawedContext method on the specified class private void setAllowFlawedContext(final Class c, final String state) throws Exception {
* (expected to be a UserClass loaded via a custom classloader), passing final Class[] params = {String.class};
* it the specified state parameter. final java.lang.reflect.Method m = c.getDeclaredMethod("setAllowFlawedContext", params);
*/ m.invoke(null, state);
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
* Test what happens when we play various classloader tricks like those * are available via the system classpath.
* that happen in web and j2ee containers. */
* <p> public void testInContainer()throws Exception{
* Note that this test assumes that commons-logging.jar and log4j.jar
* are available via the system classpath. //problem can be in this step (broken app container or missconfiguration)
*/ //1. Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
public void testInContainer()throws Exception{ //2. Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
// we expect this :
//problem can be in this step (broken app container or missconfiguration) // 1. Thread.currentThread().setContextClassLoader(appLoader);
//1. Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); // 2. Thread.currentThread().setContextClassLoader(null);
//2. Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
// we expect this : // Context classloader is same as class calling into log
// 1. Thread.currentThread().setContextClassLoader(appLoader); Class cls = reload();
// 2. Thread.currentThread().setContextClassLoader(null); Thread.currentThread().setContextClassLoader(cls.getClassLoader());
execute(cls);
// Context classloader is same as class calling into log
Class cls = reload(); // Context classloader is the "bootclassloader". This is technically
Thread.currentThread().setContextClassLoader(cls.getClassLoader()); // bad, but LogFactoryImpl.ALLOW_FLAWED_CONTEXT defaults to true so
execute(cls); // this test should pass.
cls = reload();
// Context classloader is the "bootclassloader". This is technically Thread.currentThread().setContextClassLoader(null);
// bad, but LogFactoryImpl.ALLOW_FLAWED_CONTEXT defaults to true so execute(cls);
// this test should pass.
cls = reload(); // Context classloader is the "bootclassloader". This is same as above
Thread.currentThread().setContextClassLoader(null); // except that ALLOW_FLAWED_CONTEXT is set to false; an error should
execute(cls); // now be reported.
cls = reload();
// Context classloader is the "bootclassloader". This is same as above Thread.currentThread().setContextClassLoader(null);
// except that ALLOW_FLAWED_CONTEXT is set to false; an error should try {
// now be reported. setAllowFlawedContext(cls, "false");
cls = reload(); execute(cls);
Thread.currentThread().setContextClassLoader(null); fail("Logging config succeeded when context classloader was null!");
try { } catch(final LogConfigurationException ex) {
setAllowFlawedContext(cls, "false"); // expected; the boot classloader doesn't *have* JCL available
execute(cls); }
fail("Logging config succeeded when context classloader was null!");
} catch(final LogConfigurationException ex) { // Context classloader is the system classloader.
// expected; the boot classloader doesn't *have* JCL available //
} // This is expected to cause problems, as LogFactoryImpl will attempt
// to use the system classloader to load the Log4JLogger class, which
// Context classloader is the system classloader. // will then be unable to cast that object to the Log interface loaded
// // via the child classloader. However as ALLOW_FLAWED_CONTEXT defaults
// This is expected to cause problems, as LogFactoryImpl will attempt // to true this test should pass.
// to use the system classloader to load the Log4JLogger class, which cls = reload();
// will then be unable to cast that object to the Log interface loaded Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
// via the child classloader. However as ALLOW_FLAWED_CONTEXT defaults execute(cls);
// to true this test should pass.
cls = reload(); // Context classloader is the system classloader. This is the same
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); // as above except that ALLOW_FLAWED_CONTEXT is set to false; an error
execute(cls); // should now be reported.
cls = reload();
// Context classloader is the system classloader. This is the same Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
// as above except that ALLOW_FLAWED_CONTEXT is set to false; an error try {
// should now be reported. setAllowFlawedContext(cls, "false");
cls = reload(); execute(cls);
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); fail("Error: somehow downcast a Logger loaded via system classloader"
try { + " to the Log interface loaded via a custom classloader");
setAllowFlawedContext(cls, "false"); } catch(final LogConfigurationException ex) {
execute(cls); // expected
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 {
* Load class UserClass via a temporary classloader which is a child of Class testObjCls = null;
* the classloader used to load this test class. final AppClassLoader appLoader = new AppClassLoader(this.getClass().getClassLoader());
*/ try {
private Class reload()throws Exception{
testObjCls = appLoader.loadClass(UserClass.class.getName());
Class testObjCls = null;
} catch (final ClassNotFoundException cnfe) {
final AppClassLoader appLoader = new AppClassLoader( throw cnfe;
this.getClass().getClassLoader()); } catch (final Throwable t) {
try{ t.printStackTrace();
fail("AppClassLoader failed ");
testObjCls = appLoader.loadClass(UserClass.class.getName()); }
}catch(final ClassNotFoundException cnfe){ assertSame("app isolated", testObjCls.getClassLoader(), appLoader);
throw cnfe;
}catch(final Throwable t){ return testObjCls;
t.printStackTrace();
fail("AppClassLoader failed "); }
}
assertSame("app isolated", testObjCls.getClassLoader(), appLoader); private void execute(final Class cls) throws Exception {
cls.newInstance();
}
return testObjCls;
@Override
public void setUp() {
} // save state before test starts so we can restore it when test ends
origContextClassLoader = Thread.currentThread().getContextClassLoader();
}
private void execute(final Class cls)throws Exception{
@Override
cls.newInstance(); public void tearDown() {
// restore original state so a test can't stuff up later tests.
} Thread.currentThread().setContextClassLoader(origContextClassLoader);
}
@Override
public void setUp() { private ClassLoader origContextClassLoader;
// 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;
}

View File

@@ -1,45 +1,43 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.commons.logging.avalon; package org.apache.commons.logging.avalon;
import org.apache.avalon.framework.logger.NullLogger; import org.apache.avalon.framework.logger.NullLogger;
import org.apache.commons.logging.impl.AvalonLogger; import org.apache.commons.logging.impl.AvalonLogger;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.AbstractLogTest; import org.apache.commons.logging.AbstractLogTest;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
/** /**
* @author <a href="mailto:neeme@apache.org">Neeme Praks</a> */
* @version $Revision$ $Date$ public class AvalonLoggerTestCase extends AbstractLogTest {
*/
public class AvalonLoggerTestCase extends AbstractLogTest { public static Test suite() {
final TestSuite suite = new TestSuite();
public static Test suite() { suite.addTestSuite(AvalonLoggerTestCase.class);
final TestSuite suite = new TestSuite(); return suite;
suite.addTestSuite(AvalonLoggerTestCase.class); }
return suite;
} @Override
public Log getLogObject() {
@Override // Output does not seem to be used, so don't display it.
public Log getLogObject() { final Log log = new AvalonLogger(new NullLogger());
// Output does not seem to be used, so don't display it. return log;
final Log log = new AvalonLogger(new NullLogger()); }
return log; }
}
}

View File

@@ -1,399 +1,396 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.commons.logging.jdk14; package org.apache.commons.logging.jdk14;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Iterator; import java.util.Iterator;
import java.util.logging.Handler; import java.util.logging.Handler;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.LogManager; import java.util.logging.LogManager;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
import java.util.logging.Logger; import java.util.logging.Logger;
import junit.framework.Test; import junit.framework.Test;
import org.apache.commons.logging.DummyException; import org.apache.commons.logging.DummyException;
import org.apache.commons.logging.PathableClassLoader; import org.apache.commons.logging.PathableClassLoader;
import org.apache.commons.logging.PathableTestSuite; import org.apache.commons.logging.PathableTestSuite;
/** /**
* <p>TestCase for JDK 1.4 logging when running on a JDK 1.4 system with * <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 * custom configuration, so that JDK 1.4 should be selected and an appropriate
* logger configured per the configuration properties.</p> * 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";
public class CustomConfigTestCase extends DefaultConfigTestCase {
// ----------------------------------------------------------- Constructors
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
* <p>Construct a new instance of this test case.</p> */
* public CustomConfigTestCase(final String name) {
* @param name Name of the test case super(name);
*/ }
public CustomConfigTestCase(final String name) {
super(name);
} // ----------------------------------------------------- Instance Variables
// ----------------------------------------------------- Instance Variables /**
* <p>The customized {@code Handler} we will be using.</p>
*/
/** protected TestHandler handler;
* <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 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 Logger} we will be using.</p>
*/
protected Logger logger; /**
* <p>The underlying {@code LogManager} we will be using.</p>
*/
/** protected LogManager manager;
* <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[] =
* <p>The message levels that should have been logged.</p> { Level.FINE, Level.INFO, Level.WARNING, Level.SEVERE, Level.SEVERE };
*/
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[] =
* <p>The message strings that should have been logged.</p> { "debug", "info", "warn", "error", "fatal" };
*/
protected String testMessages[] =
{ "debug", "info", "warn", "error", "fatal" }; // ------------------------------------------- JUnit Infrastructure Methods
// ------------------------------------------- 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.
/** */
* Given the name of a class that is somewhere in the classpath of the provided protected static byte[] readClass(final String name, final ClassLoader srcCL) throws Exception {
* classloader, return the contents of the corresponding .class file. final String resName = name.replace('.', '/') + ".class";
*/ System.err.println("Trying to load resource [" + resName + "]");
protected static byte[] readClass(final String name, final ClassLoader srcCL) throws Exception { final InputStream is = srcCL.getResourceAsStream(resName);
final String resName = name.replace('.', '/') + ".class"; final ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.err.println("Trying to load resource [" + resName + "]"); System.err.println("Reading resource [" + resName + "]");
final InputStream is = srcCL.getResourceAsStream(resName); final byte[] buf = new byte[1000];
final ByteArrayOutputStream baos = new ByteArrayOutputStream(); for(;;) {
System.err.println("Reading resource [" + resName + "]"); final int read = is.read(buf);
final byte[] buf = new byte[1000]; if (read <= 0) {
for(;;) { break;
final int read = is.read(buf); }
if (read <= 0) { baos.write(buf, 0, read);
break; }
} is.close();
baos.write(buf, 0, read); return baos.toByteArray();
} }
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
* Make a class available in the system classloader even when its classfile is * that classloader.
* not present in the classpath configured for that classloader. This only */
* works for classes for which all dependencies are already loaded in protected static void loadTestHandler(final String className, final ClassLoader targetCL) {
* that classloader. try {
*/ targetCL.loadClass(className);
protected static void loadTestHandler(final String className, final ClassLoader targetCL) { // fail("Class already in target classloader");
try { return;
targetCL.loadClass(className); } catch(final ClassNotFoundException ex) {
// fail("Class already in target classloader"); // ok, go ahead and load it
return; }
} catch(final ClassNotFoundException ex) {
// ok, go ahead and load it try {
} final ClassLoader srcCL = CustomConfigAPITestCase.class.getClassLoader();
final byte[] classData = readClass(className, srcCL);
try {
final ClassLoader srcCL = CustomConfigAPITestCase.class.getClassLoader(); final Class[] params = new Class[] { String.class, classData.getClass(), Integer.TYPE, Integer.TYPE };
final byte[] classData = readClass(className, srcCL); final Method m = ClassLoader.class.getDeclaredMethod("defineClass", params);
final Class[] params = new Class[] { String.class, classData.getClass(), Integer.TYPE, Integer.TYPE }; final Object[] args = new Object[4];
final Method m = ClassLoader.class.getDeclaredMethod("defineClass", params); args[0] = className;
args[1] = classData;
final Object[] args = new Object[4]; args[2] = new Integer(0);
args[0] = className; args[3] = new Integer(classData.length);
args[1] = classData; m.setAccessible(true);
args[2] = new Integer(0); m.invoke(targetCL, args);
args[3] = new Integer(classData.length); } catch(final Exception e) {
m.setAccessible(true); e.printStackTrace();
m.invoke(targetCL, args); fail("Unable to load class " + className);
} catch(final Exception e) { }
e.printStackTrace(); }
fail("Unable to load class " + className);
} /**
} * Set up instance variables required by this test case.
*/
/** @Override
* Set up instance variables required by this test case. public void setUp() throws Exception {
*/ setUpManager
@Override ("org/apache/commons/logging/jdk14/CustomConfig.properties");
public void setUp() throws Exception { setUpLogger(this.getClass().getName());
setUpManager setUpHandlers();
("org/apache/commons/logging/jdk14/CustomConfig.properties"); setUpFactory();
setUpLogger(this.getClass().getName()); setUpLog(this.getClass().getName());
setUpHandlers(); }
setUpFactory();
setUpLog(this.getClass().getName());
} /**
* Return the tests included in this test suite.
*/
/** public static Test suite() throws Exception {
* Return the tests included in this test suite. final PathableClassLoader cl = new PathableClassLoader(null);
*/ cl.useExplicitLoader("junit.", Test.class.getClassLoader());
public static Test suite() throws Exception {
final PathableClassLoader cl = new PathableClassLoader(null); // the TestHandler class must be accessable from the System classloader
cl.useExplicitLoader("junit.", Test.class.getClassLoader()); // in order for java.util.logging.LogManager.readConfiguration to
// be able to instantiate it. And this test case must see the same
// the TestHandler class must be accessable from the System classloader // class in order to be able to access its data. Yes this is ugly
// in order for java.util.logging.LogManager.readConfiguration to // but the whole jdk14 API is a ******* mess anyway.
// be able to instantiate it. And this test case must see the same final ClassLoader scl = ClassLoader.getSystemClassLoader();
// class in order to be able to access its data. Yes this is ugly loadTestHandler(HANDLER_NAME, scl);
// but the whole jdk14 API is a ******* mess anyway. cl.useExplicitLoader(HANDLER_NAME, scl);
final ClassLoader scl = ClassLoader.getSystemClassLoader(); cl.addLogicalLib("commons-logging");
loadTestHandler(HANDLER_NAME, scl); cl.addLogicalLib("testclasses");
cl.useExplicitLoader(HANDLER_NAME, scl);
cl.addLogicalLib("commons-logging"); final Class testClass = cl.loadClass(CustomConfigTestCase.class.getName());
cl.addLogicalLib("testclasses"); return new PathableTestSuite(testClass, cl);
}
final Class testClass = cl.loadClass(CustomConfigTestCase.class.getName());
return new PathableTestSuite(testClass, cl); /**
} * Tear down instance variables required by this test case.
*/
/** @Override
* Tear down instance variables required by this test case. public void tearDown() {
*/ super.tearDown();
@Override handlers = null;
public void tearDown() { logger = null;
super.tearDown(); manager = null;
handlers = null; }
logger = null;
manager = null;
} // ----------------------------------------------------------- Test Methods
// ----------------------------------------------------------- Test Methods // Test logging message strings with exceptions
public void testExceptionMessages() throws Exception {
// Test logging message strings with exceptions logExceptionMessages();
public void testExceptionMessages() throws Exception { checkLogRecords(true);
logExceptionMessages(); }
checkLogRecords(true);
} // Test logging plain message strings
public void testPlainMessages() throws Exception {
// Test logging plain message strings logPlainMessages();
public void testPlainMessages() throws Exception { checkLogRecords(false);
logPlainMessages(); }
checkLogRecords(false);
} // Test pristine Handlers instances
public void testPristineHandlers() {
// Test pristine Handlers instances assertNotNull(handlers);
public void testPristineHandlers() { assertEquals(1, handlers.length);
assertTrue(handlers[0] instanceof TestHandler);
assertNotNull(handlers); assertNotNull(handler);
assertEquals(1, handlers.length);
assertTrue(handlers[0] instanceof TestHandler); }
assertNotNull(handler);
} // Test pristine Logger instance
public void testPristineLogger() {
// Test pristine Logger instance assertNotNull("Logger exists", logger);
public void testPristineLogger() { assertEquals("Logger name", this.getClass().getName(), logger.getName());
assertNotNull("Logger exists", logger); // Assert which logging levels have been enabled
assertEquals("Logger name", this.getClass().getName(), logger.getName()); assertTrue(logger.isLoggable(Level.SEVERE));
assertTrue(logger.isLoggable(Level.WARNING));
// Assert which logging levels have been enabled assertTrue(logger.isLoggable(Level.INFO));
assertTrue(logger.isLoggable(Level.SEVERE)); assertTrue(logger.isLoggable(Level.CONFIG));
assertTrue(logger.isLoggable(Level.WARNING)); assertTrue(logger.isLoggable(Level.FINE));
assertTrue(logger.isLoggable(Level.INFO)); assertFalse(logger.isLoggable(Level.FINER));
assertTrue(logger.isLoggable(Level.CONFIG)); assertFalse(logger.isLoggable(Level.FINEST));
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 {
// Test Serializability of Log instance
@Override super.testSerializable();
public void testSerializable() throws Exception { testExceptionMessages();
super.testSerializable(); }
testExceptionMessages();
} // -------------------------------------------------------- Support Methods
// -------------------------------------------------------- Support Methods // Check the log instance
@Override
protected void checkLog() {
// Check the log instance
@Override assertNotNull("Log exists", log);
protected void checkLog() { assertEquals("Log class",
"org.apache.commons.logging.impl.Jdk14Logger",
assertNotNull("Log exists", log); log.getClass().getName());
assertEquals("Log class",
"org.apache.commons.logging.impl.Jdk14Logger", // Assert which logging levels have been enabled
log.getClass().getName()); assertTrue(log.isFatalEnabled());
assertTrue(log.isErrorEnabled());
// Assert which logging levels have been enabled assertTrue(log.isWarnEnabled());
assertTrue(log.isFatalEnabled()); assertTrue(log.isInfoEnabled());
assertTrue(log.isErrorEnabled()); assertTrue(log.isDebugEnabled());
assertTrue(log.isWarnEnabled()); assertFalse(log.isTraceEnabled());
assertTrue(log.isInfoEnabled());
assertTrue(log.isDebugEnabled()); }
assertFalse(log.isTraceEnabled());
} // Check the recorded messages
protected void checkLogRecords(final boolean thrown) {
final Iterator records = handler.records();
// Check the recorded messages for (int i = 0; i < testMessages.length; i++) {
protected void checkLogRecords(final boolean thrown) { assertTrue(records.hasNext());
final Iterator records = handler.records(); final LogRecord record = (LogRecord) records.next();
for (int i = 0; i < testMessages.length; i++) { assertEquals("LogRecord level",
assertTrue(records.hasNext()); testLevels[i], record.getLevel());
final LogRecord record = (LogRecord) records.next(); assertEquals("LogRecord message",
assertEquals("LogRecord level", testMessages[i], record.getMessage());
testLevels[i], record.getLevel()); assertTrue("LogRecord class",
assertEquals("LogRecord message", record.getSourceClassName().startsWith(
testMessages[i], record.getMessage()); "org.apache.commons.logging.jdk14.CustomConfig"));
assertTrue("LogRecord class", if (thrown) {
record.getSourceClassName().startsWith( assertEquals("LogRecord method",
"org.apache.commons.logging.jdk14.CustomConfig")); "logExceptionMessages",
if (thrown) { record.getSourceMethodName());
assertEquals("LogRecord method", } else {
"logExceptionMessages", assertEquals("LogRecord method",
record.getSourceMethodName()); "logPlainMessages",
} else { record.getSourceMethodName());
assertEquals("LogRecord method", }
"logPlainMessages", if (thrown) {
record.getSourceMethodName()); assertNotNull("LogRecord thrown", record.getThrown());
} assertTrue("LogRecord thrown type",
if (thrown) { record.getThrown() instanceof DummyException);
assertNotNull("LogRecord thrown", record.getThrown()); } else {
assertTrue("LogRecord thrown type", assertNull("LogRecord thrown",
record.getThrown() instanceof DummyException); record.getThrown());
} else { }
assertNull("LogRecord thrown", }
record.getThrown()); assertFalse(records.hasNext());
} handler.flush();
} }
assertFalse(records.hasNext());
handler.flush();
} // Log the messages with exceptions
protected void logExceptionMessages() {
final Throwable t = new DummyException();
// Log the messages with exceptions log.trace("trace", t); // Should not actually get logged
protected void logExceptionMessages() { log.debug("debug", t);
final Throwable t = new DummyException(); log.info("info", t);
log.trace("trace", t); // Should not actually get logged log.warn("warn", t);
log.debug("debug", t); log.error("error", t);
log.info("info", t); log.fatal("fatal", 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 the plain messages log.debug("debug");
protected void logPlainMessages() { log.info("info");
log.trace("trace"); // Should not actually get logged log.warn("warn");
log.debug("debug"); log.error("error");
log.info("info"); log.fatal("fatal");
log.warn("warn"); }
log.error("error");
log.fatal("fatal");
} // Set up handlers instance
protected void setUpHandlers() throws Exception {
Logger parent = logger;
// Set up handlers instance while (parent.getParent() != null) {
protected void setUpHandlers() throws Exception { parent = parent.getParent();
Logger parent = logger; }
while (parent.getParent() != null) { handlers = parent.getHandlers();
parent = parent.getParent();
} // The CustomConfig.properties file explicitly defines one handler class
handlers = parent.getHandlers(); // to be attached to the root logger, so if it isn't there then
// something is badly wrong...
// The CustomConfig.properties file explicitly defines one handler class //
// to be attached to the root logger, so if it isn't there then // Yes this testing is also done in testPristineHandlers but
// something is badly wrong... // unfortunately:
// // * we need to set up the handlers variable here,
// Yes this testing is also done in testPristineHandlers but // * we don't want that to be set up incorrectly, as that can
// unfortunately: // produce weird error messages in other tests, and
// * we need to set up the handlers variable here, // * we can't rely on testPristineHandlers being the first
// * we don't want that to be set up incorrectly, as that can // test to run.
// produce weird error messages in other tests, and // so we need to test things here too.
// * we can't rely on testPristineHandlers being the first assertNotNull("No Handlers defined for JDK14 logging", handlers);
// test to run. assertEquals("Unexpected number of handlers for JDK14 logging", 1, handlers.length);
// so we need to test things here too. assertNotNull("Handler is null", handlers[0]);
assertNotNull("No Handlers defined for JDK14 logging", handlers); assertTrue("Handler not of expected type", handlers[0] instanceof TestHandler);
assertEquals("Unexpected number of handlers for JDK14 logging", 1, handlers.length); handler = (TestHandler) handlers[0];
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 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();
// Set up LogManager instance final InputStream is =
protected void setUpManager(final String config) throws Exception { this.getClass().getClassLoader().getResourceAsStream(config);
manager = LogManager.getLogManager(); manager.readConfiguration(is);
final InputStream is = is.close();
this.getClass().getClassLoader().getResourceAsStream(config); }
manager.readConfiguration(is);
is.close();
} }
}

View File

@@ -1,193 +1,158 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.commons.logging.jdk14; package org.apache.commons.logging.jdk14;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.PathableClassLoader; import org.apache.commons.logging.PathableClassLoader;
import org.apache.commons.logging.PathableTestSuite; import org.apache.commons.logging.PathableTestSuite;
/** /**
* <p>TestCase for JDK 1.4 logging when running on a JDK 1.4 system with * <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 * zero configuration, and with Log4J not present (so JDK 1.4 logging
* should be automatically configured.</p> * should be automatically configured.</p>
* */
* @author Craig R. McClanahan public class DefaultConfigTestCase extends TestCase {
* @version $Revision$ $Date$
*/ /**
* <p>Construct a new instance of this test case.</p>
public class DefaultConfigTestCase extends TestCase { *
* @param name Name of the test case
*/
// ----------------------------------------------------------- Constructors public DefaultConfigTestCase(final String name) {
super(name);
}
/**
* <p>Construct a new instance of this test case.</p> /**
* * <p>The {@link LogFactory} implementation we have selected.</p>
* @param name Name of the test case */
*/ protected LogFactory factory;
public DefaultConfigTestCase(final String name) {
super(name); /**
} * <p>The {@link Log} implementation we have selected.</p>
*/
protected Log log;
// ----------------------------------------------------- Instance Variables
/**
* Set up instance variables required by this test case.
/** */
* <p>The {@link LogFactory} implementation we have selected.</p> @Override
*/ public void setUp() throws Exception {
protected LogFactory factory; setUpFactory();
setUpLog("TestLogger");
}
/**
* <p>The {@link Log} implementation we have selected.</p> /**
*/ * Return the tests included in this test suite.
protected Log log; */
public static Test suite() throws Exception {
final PathableClassLoader loader = new PathableClassLoader(null);
// ------------------------------------------- JUnit Infrastructure Methods loader.useExplicitLoader("junit.", Test.class.getClassLoader());
loader.addLogicalLib("testclasses");
loader.addLogicalLib("commons-logging");
/**
* Set up instance variables required by this test case. final Class testClass = loader.loadClass(DefaultConfigTestCase.class.getName());
*/ return new PathableTestSuite(testClass, loader);
@Override }
public void setUp() throws Exception {
setUpFactory(); /**
setUpLog("TestLogger"); * Tear down instance variables required by this test case.
} */
@Override
public void tearDown() {
/** log = null;
* Return the tests included in this test suite. factory = null;
*/ LogFactory.releaseAll();
public static Test suite() throws Exception { }
final PathableClassLoader loader = new PathableClassLoader(null);
loader.useExplicitLoader("junit.", Test.class.getClassLoader()); // Test pristine Log instance
loader.addLogicalLib("testclasses"); public void testPristineLog() {
loader.addLogicalLib("commons-logging"); checkLog();
}
final Class testClass = loader.loadClass(DefaultConfigTestCase.class.getName());
return new PathableTestSuite(testClass, loader); // Test pristine LogFactory instance
} public void testPristineFactory() {
assertNotNull("LogFactory exists", factory);
/** assertEquals("LogFactory class",
* Tear down instance variables required by this test case. "org.apache.commons.logging.impl.LogFactoryImpl",
*/ factory.getClass().getName());
@Override
public void tearDown() { final String names[] = factory.getAttributeNames();
log = null; assertNotNull("Names exists", names);
factory = null; assertEquals("Names empty", 0, names.length);
LogFactory.releaseAll(); }
}
// Test Serializability of Log instance
// ----------------------------------------------------------- Test Methods public void testSerializable() throws Exception {
// Serialize and deserialize the instance
// Test pristine Log instance final ByteArrayOutputStream baos = new ByteArrayOutputStream();
public void testPristineLog() { final ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(log);
checkLog(); oos.close();
final ByteArrayInputStream bais =
} new ByteArrayInputStream(baos.toByteArray());
final ObjectInputStream ois = new ObjectInputStream(bais);
log = (Log) ois.readObject();
// Test pristine LogFactory instance ois.close();
public void testPristineFactory() {
// Check the characteristics of the resulting object
assertNotNull("LogFactory exists", factory); checkLog();
assertEquals("LogFactory class",
"org.apache.commons.logging.impl.LogFactoryImpl", }
factory.getClass().getName());
// Check the log instance
final String names[] = factory.getAttributeNames(); protected void checkLog() {
assertNotNull("Names exists", names);
assertEquals("Names empty", 0, names.length); assertNotNull("Log exists", log);
assertEquals("Log class",
} "org.apache.commons.logging.impl.Jdk14Logger",
log.getClass().getName());
// Test Serializability of Log instance // Can we call level checkers with no exceptions?
public void testSerializable() throws Exception { log.isDebugEnabled();
log.isErrorEnabled();
// Serialize and deserialize the instance log.isFatalEnabled();
final ByteArrayOutputStream baos = new ByteArrayOutputStream(); log.isInfoEnabled();
final ObjectOutputStream oos = new ObjectOutputStream(baos); log.isTraceEnabled();
oos.writeObject(log); log.isWarnEnabled();
oos.close();
final ByteArrayInputStream bais = }
new ByteArrayInputStream(baos.toByteArray());
final ObjectInputStream ois = new ObjectInputStream(bais); // Set up factory instance
log = (Log) ois.readObject(); protected void setUpFactory() throws Exception {
ois.close(); factory = LogFactory.getFactory();
}
// Check the characteristics of the resulting object
checkLog(); // Set up log instance
protected void setUpLog(final String name) throws Exception {
} log = LogFactory.getLog(name);
}
// -------------------------------------------------------- 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);
}
}

View File

@@ -1,73 +1,53 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.commons.logging.jdk14; package org.apache.commons.logging.jdk14;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.logging.Handler; import java.util.logging.Handler;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
/** /**
* <p>Test implementation of {@code java.util.logging.Handler}.</p> * <p>Test implementation of {@code java.util.logging.Handler}.</p>
* */
* @author Craig R. McClanahan public class TestHandler extends Handler {
* @version $Revision$ $Date$
*/ // The set of logged records for this handler
private final List records = new ArrayList();
public class TestHandler extends Handler {
public Iterator records() {
return records.iterator();
}
// ----------------------------------------------------- Instance Variables
@Override
public void close() {
// The set of logged records for this handler }
private final List records = new ArrayList();
@Override
public void flush() {
// --------------------------------------------------------- Public Methods records.clear();
}
public Iterator records() { @Override
return records.iterator(); public void publish(final LogRecord record) {
} records.add(record);
}
// -------------------------------------------------------- Handler Methods }
@Override
public void close() {
}
@Override
public void flush() {
records.clear();
}
@Override
public void publish(final LogRecord record) {
records.add(record);
}
}

View File

@@ -34,22 +34,14 @@ import org.apache.commons.logging.impl.SimpleLog;
/** /**
* <p>TestCase for simple logging when running with custom configuration * <p>TestCase for simple logging when running with custom configuration
* properties.</p> * properties.</p>
*
* @author Craig R. McClanahan
* @version $Revision$ $Date$
*/ */
public class CustomConfigTestCase extends DefaultConfigTestCase { public class CustomConfigTestCase extends DefaultConfigTestCase {
// ----------------------------------------------------- Instance Variables
/** /**
* <p>The expected log records.</p> * <p>The expected log records.</p>
*/ */
protected List expected; protected List expected;
/** /**
* <p>The message levels that should have been logged.</p> * <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 }; { Level.FINE, Level.INFO, Level.WARNING, Level.SEVERE, Level.SEVERE };
*/ */
/** /**
* <p>The message strings that should have been logged.</p> * <p>The message strings that should have been logged.</p>
*/ */
protected String testMessages[] = protected String testMessages[] =
{ "debug", "info", "warn", "error", "fatal" }; { "debug", "info", "warn", "error", "fatal" };
// ------------------------------------------- JUnit Infrastructure Methods
/** /**
* Set system properties that will control the LogFactory/Log objects * Set system properties that will control the LogFactory/Log objects
* when they are created. Subclasses can override this method to * when they are created. Subclasses can override this method to
@@ -95,7 +83,6 @@ public class CustomConfigTestCase extends DefaultConfigTestCase {
setUpLog("DecoratedLogger"); setUpLog("DecoratedLogger");
} }
/** /**
* Return the tests included in this test suite. * Return the tests included in this test suite.
* <p> * <p>
@@ -129,46 +116,30 @@ public class CustomConfigTestCase extends DefaultConfigTestCase {
expected = null; expected = null;
} }
// ----------------------------------------------------------- Test Methods
// Test logging message strings with exceptions // Test logging message strings with exceptions
public void testExceptionMessages() throws Exception { public void testExceptionMessages() throws Exception {
((DecoratedSimpleLog) log).clearCache(); ((DecoratedSimpleLog) log).clearCache();
logExceptionMessages(); logExceptionMessages();
checkExpected(); checkExpected();
} }
// Test logging plain message strings // Test logging plain message strings
public void testPlainMessages() throws Exception { public void testPlainMessages() throws Exception {
((DecoratedSimpleLog) log).clearCache(); ((DecoratedSimpleLog) log).clearCache();
logPlainMessages(); logPlainMessages();
checkExpected(); checkExpected();
} }
// Test Serializability of standard instance // Test Serializability of standard instance
@Override @Override
public void testSerializable() throws Exception { public void testSerializable() throws Exception {
((DecoratedSimpleLog) log).clearCache(); ((DecoratedSimpleLog) log).clearCache();
logPlainMessages(); logPlainMessages();
super.testSerializable(); super.testSerializable();
logExceptionMessages(); logExceptionMessages();
checkExpected(); checkExpected();
} }
// -------------------------------------------------------- Support Methods
// Check the decorated log instance // Check the decorated log instance
@Override @Override
protected void checkDecorated() { protected void checkDecorated() {
@@ -213,7 +184,6 @@ public class CustomConfigTestCase extends DefaultConfigTestCase {
// Check the actual log records against the expected ones // Check the actual log records against the expected ones
protected void checkExpected() { protected void checkExpected() {
final List acts = ((DecoratedSimpleLog) log).getCache(); final List acts = ((DecoratedSimpleLog) log).getCache();
final Iterator exps = expected.iterator(); final Iterator exps = expected.iterator();
int n = 0; int n = 0;
@@ -224,22 +194,18 @@ public class CustomConfigTestCase extends DefaultConfigTestCase {
assertEquals("Row " + n + " message", exp.message, act.message); assertEquals("Row " + n + " message", exp.message, act.message);
assertEquals("Row " + n + " throwable", exp.t, act.t); assertEquals("Row " + n + " throwable", exp.t, act.t);
} }
} }
// Check the standard log instance // Check the standard log instance
@Override @Override
protected void checkStandard() { protected void checkStandard() {
checkDecorated(); checkDecorated();
} }
// Log the messages with exceptions // Log the messages with exceptions
protected void logExceptionMessages() { protected void logExceptionMessages() {
// Generate log records // Generate log records
final Throwable t = new DummyException(); final Throwable t = new DummyException();
log.trace("trace", t); // Should not actually get logged 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_WARN, "warn", t));
expected.add(new LogRecord(SimpleLog.LOG_LEVEL_ERROR, "error", t)); expected.add(new LogRecord(SimpleLog.LOG_LEVEL_ERROR, "error", t));
expected.add(new LogRecord(SimpleLog.LOG_LEVEL_FATAL, "fatal", t)); expected.add(new LogRecord(SimpleLog.LOG_LEVEL_FATAL, "fatal", t));
} }
// Log the plain messages // Log the plain messages
protected void logPlainMessages() { protected void logPlainMessages() {
// Generate log records // Generate log records
log.trace("trace"); // Should not actually get logged log.trace("trace"); // Should not actually get logged
log.debug("debug"); 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_WARN, "warn", null));
expected.add(new LogRecord(SimpleLog.LOG_LEVEL_ERROR, "error", null)); expected.add(new LogRecord(SimpleLog.LOG_LEVEL_ERROR, "error", null));
expected.add(new LogRecord(SimpleLog.LOG_LEVEL_FATAL, "fatal", null)); expected.add(new LogRecord(SimpleLog.LOG_LEVEL_FATAL, "fatal", null));
} }
} }

View File

@@ -36,32 +36,20 @@ import org.apache.commons.logging.impl.SimpleLog;
/** /**
* <p>TestCase for simple logging when running with zero configuration * <p>TestCase for simple logging when running with zero configuration
* other than selecting the SimpleLog implementation.</p> * other than selecting the SimpleLog implementation.</p>
*
* @author Craig R. McClanahan
* @version $Revision$ $Date$
*/ */
public class DefaultConfigTestCase extends TestCase { public class DefaultConfigTestCase extends TestCase {
// ----------------------------------------------------- Instance Variables
/** /**
* <p>The {@link LogFactory} implementation we have selected.</p> * <p>The {@link LogFactory} implementation we have selected.</p>
*/ */
protected LogFactory factory; protected LogFactory factory;
/** /**
* <p>The {@link Log} implementation we have selected.</p> * <p>The {@link Log} implementation we have selected.</p>
*/ */
protected Log log; protected Log log;
// ------------------------------------------- JUnit Infrastructure Methods
/** /**
* Return the tests included in this test suite. * Return the tests included in this test suite.
* <p> * <p>
@@ -118,30 +106,19 @@ public class DefaultConfigTestCase extends TestCase {
LogFactory.releaseAll(); LogFactory.releaseAll();
} }
// ----------------------------------------------------------- Test Methods
// Test pristine DecoratedSimpleLog instance // Test pristine DecoratedSimpleLog instance
public void testPristineDecorated() { public void testPristineDecorated() {
setUpDecorated("DecoratedLogger"); setUpDecorated("DecoratedLogger");
checkDecorated(); checkDecorated();
} }
// Test pristine Log instance // Test pristine Log instance
public void testPristineLog() { public void testPristineLog() {
checkStandard(); checkStandard();
} }
// Test pristine LogFactory instance // Test pristine LogFactory instance
public void testPristineFactory() { public void testPristineFactory() {
assertNotNull("LogFactory exists", factory); assertNotNull("LogFactory exists", factory);
assertEquals("LogFactory class", assertEquals("LogFactory class",
"org.apache.commons.logging.impl.LogFactoryImpl", "org.apache.commons.logging.impl.LogFactoryImpl",
@@ -150,10 +127,8 @@ public class DefaultConfigTestCase extends TestCase {
final String names[] = factory.getAttributeNames(); final String names[] = factory.getAttributeNames();
assertNotNull("Names exists", names); assertNotNull("Names exists", names);
assertEquals("Names empty", 0, names.length); assertEquals("Names empty", 0, names.length);
} }
// Test Serializability of standard instance // Test Serializability of standard instance
public void testSerializable() throws Exception { public void testSerializable() throws Exception {
@@ -173,14 +148,8 @@ public class DefaultConfigTestCase extends TestCase {
} }
// -------------------------------------------------------- Support Methods
// Check the decorated log instance // Check the decorated log instance
protected void checkDecorated() { protected void checkDecorated() {
assertNotNull("Log exists", log); assertNotNull("Log exists", log);
assertEquals("Log class", assertEquals("Log class",
"org.apache.commons.logging.simple.DecoratedSimpleLog", "org.apache.commons.logging.simple.DecoratedSimpleLog",
@@ -204,13 +173,11 @@ public class DefaultConfigTestCase extends TestCase {
((DecoratedSimpleLog) log).getLogName()); ((DecoratedSimpleLog) log).getLogName());
assertFalse(((DecoratedSimpleLog) log).getShowDateTime()); assertFalse(((DecoratedSimpleLog) log).getShowDateTime());
assertTrue(((DecoratedSimpleLog) log).getShowShortName()); assertTrue(((DecoratedSimpleLog) log).getShowShortName());
} }
// Check the standard log instance // Check the standard log instance
protected void checkStandard() { protected void checkStandard() {
assertNotNull("Log exists", log); assertNotNull("Log exists", log);
assertEquals("Log class", assertEquals("Log class",
"org.apache.commons.logging.impl.SimpleLog", "org.apache.commons.logging.impl.SimpleLog",
@@ -226,7 +193,6 @@ public class DefaultConfigTestCase extends TestCase {
// Can we retrieve the current log level? // Can we retrieve the current log level?
assertEquals(SimpleLog.LOG_LEVEL_INFO, ((SimpleLog) log).getLevel()); assertEquals(SimpleLog.LOG_LEVEL_INFO, ((SimpleLog) log).getLevel());
} }
@@ -247,5 +213,4 @@ public class DefaultConfigTestCase extends TestCase {
log = LogFactory.getLog(name); log = LogFactory.getLog(name);
} }
} }