Clover coverage report - Code Coverage for hivemind release 1.0-beta-1
Coverage timestamp: Sat Jul 3 2004 09:41:37 EDT
file stats: LOC: 420   Methods: 0
NCLOC: 222   Classes: 1
30 day Evaluation Version distributed via the Maven Jar Repository. Clover is not free. You have 30 days to evaluate it. Please visit http://www.thecortex.net/clover to obtain a licensed version of Clover
 
 Source file Conditionals Statements Methods TOTAL
HiveMindTestCase.java - - - -
coverage
 1   
 //  Copyright 2004 The Apache Software Foundation
 2   
 //
 3   
 // Licensed under the Apache License, Version 2.0 (the "License");
 4   
 // you may not use this file except in compliance with the License.
 5   
 // You may obtain a copy of the License at
 6   
 //
 7   
 //     http://www.apache.org/licenses/LICENSE-2.0
 8   
 //
 9   
 // Unless required by applicable law or agreed to in writing, software
 10   
 // distributed under the License is distributed on an "AS IS" BASIS,
 11   
 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12   
 // See the License for the specific language governing permissions and
 13   
 // limitations under the License.
 14   
 
 15   
 package org.apache.hivemind.test;
 16   
 
 17   
 import java.net.URL;
 18   
 import java.util.ArrayList;
 19   
 import java.util.Iterator;
 20   
 import java.util.List;
 21   
 import java.util.Locale;
 22   
 
 23   
 import junit.framework.AssertionFailedError;
 24   
 import junit.framework.TestCase;
 25   
 
 26   
 import org.apache.hivemind.ApplicationRuntimeException;
 27   
 import org.apache.hivemind.ClassResolver;
 28   
 import org.apache.hivemind.Registry;
 29   
 import org.apache.hivemind.Resource;
 30   
 import org.apache.hivemind.impl.DefaultClassResolver;
 31   
 import org.apache.hivemind.impl.RegistryBuilder;
 32   
 import org.apache.hivemind.util.URLResource;
 33   
 import org.apache.log4j.Level;
 34   
 import org.apache.log4j.LogManager;
 35   
 import org.apache.log4j.Logger;
 36   
 import org.apache.log4j.spi.LoggingEvent;
 37   
 import org.apache.oro.text.regex.Pattern;
 38   
 import org.apache.oro.text.regex.Perl5Compiler;
 39   
 import org.apache.oro.text.regex.Perl5Matcher;
 40   
 import org.easymock.MockControl;
 41   
 
 42   
 /**
 43   
  * Contains some support for creating HiveMind tests; this is useful enough that
 44   
  * has been moved into the main framework, to simplify creation of tests in the dependent
 45   
  * libraries.
 46   
  *
 47   
  * @author Howard Lewis Ship
 48   
  */
 49   
 public abstract class HiveMindTestCase extends TestCase
 50   
 {
 51   
     ///CLOVER:OFF
 52   
 
 53   
     protected String _interceptedLoggerName;
 54   
     protected StoreAppender _appender;
 55   
 
 56   
     private static Perl5Compiler _compiler;
 57   
     private static Perl5Matcher _matcher;
 58   
 
 59   
     /** List of {@link org.easymock.MockControl}. */
 60   
 
 61   
     private List _controls = new ArrayList();
 62   
 
 63   
     /**
 64   
      * Returns the given file as a {@link Resource} from the classpath. Typically,
 65   
      * this is to find files in the same folder as the invoking class.
 66   
      */
 67   
     protected Resource getResource(String file)
 68   
     {
 69   
         URL url = getClass().getResource(file);
 70   
 
 71   
         if (url == null)
 72   
             throw new NullPointerException("No resource named '" + file + "'.");
 73   
 
 74   
         return new URLResource(url);
 75   
     }
 76   
 
 77   
     /**
 78   
      * Converts the actual list to an array and invokes
 79   
      * {@link #assertListsEqual(Object[], Object[])}.
 80   
      */
 81   
     protected static void assertListsEqual(Object[] expected, List actual)
 82   
     {
 83   
         assertListsEqual(expected, actual.toArray());
 84   
     }
 85   
 
 86   
     /**
 87   
      * Asserts that the two arrays are equal; same length and all elements
 88   
      * equal.  Checks the elements first, then the length.
 89   
      */
 90   
     protected static void assertListsEqual(Object[] expected, Object[] actual)
 91   
     {
 92   
         assertNotNull(actual);
 93   
 
 94   
         int min = Math.min(expected.length, actual.length);
 95   
 
 96   
         for (int i = 0; i < min; i++)
 97   
             assertEquals("list[" + i + "]", expected[i], actual[i]);
 98   
 
 99   
         assertEquals("list length", expected.length, actual.length);
 100   
     }
 101   
 
 102   
     /**
 103   
      * Called when code should not be reachable (because a test is expected
 104   
      * to throw an exception); throws
 105   
      * AssertionFailedError always.
 106   
      */
 107   
     protected static void unreachable()
 108   
     {
 109   
         throw new AssertionFailedError("This code should be unreachable.");
 110   
     }
 111   
 
 112   
     /**
 113   
      * Sets up a {@link StoreAppender} to intercept logging for the specified
 114   
      * logger. Captured log events can be recovered via
 115   
      * {@link #getInterceptedLogEvents()}.
 116   
      */
 117   
     protected void interceptLogging(String loggerName)
 118   
     {
 119   
         Logger logger = LogManager.getLogger(loggerName);
 120   
 
 121   
         logger.removeAllAppenders();
 122   
 
 123   
         _interceptedLoggerName = loggerName;
 124   
         _appender = new StoreAppender();
 125   
 
 126   
         logger.setLevel(Level.DEBUG);
 127   
         logger.setAdditivity(false);
 128   
         logger.addAppender(_appender);
 129   
     }
 130   
 
 131   
     /**
 132   
      * Gets the list of events most recently intercepted. This resets
 133   
      * the {@link StoreAppender} (it clears its list of log events).
 134   
      * 
 135   
      * @see #interceptLogging(String)
 136   
      * @see StoreAppender#getEvents()
 137   
      */
 138   
     protected List getInterceptedLogEvents()
 139   
     {
 140   
         return _appender.getEvents();
 141   
     }
 142   
 
 143   
     /**
 144   
      * Removes the {@link StoreAppender} that may have been setup by
 145   
      * {@link #interceptLogging(String)}.
 146   
      */
 147   
     protected void tearDown() throws Exception
 148   
     {
 149   
         if (_appender != null)
 150   
         {
 151   
             _appender = null;
 152   
 
 153   
             Logger logger = LogManager.getLogger(_interceptedLoggerName);
 154   
             logger.setLevel(null);
 155   
             logger.setAdditivity(true);
 156   
             logger.removeAllAppenders();
 157   
         }
 158   
     }
 159   
 
 160   
     /**
 161   
      * Checks that the provided substring exists in the exceptions message.
 162   
      */
 163   
     protected void assertExceptionSubstring(Throwable ex, String substring)
 164   
     {
 165   
         String message = ex.getMessage();
 166   
         assertNotNull(message);
 167   
 
 168   
         int pos = message.indexOf(substring);
 169   
 
 170   
         if (pos < 0)
 171   
             throw new AssertionFailedError(
 172   
                 "Exception message (" + message + ") does not contain [" + substring + "]");
 173   
     }
 174   
 
 175   
     /**
 176   
      * Checks that the message for an exception matches a regular expression.
 177   
      */
 178   
 
 179   
     protected void assertExceptionRegexp(Throwable ex, String pattern) throws Exception
 180   
     {
 181   
         String message = ex.getMessage();
 182   
         assertNotNull(message);
 183   
 
 184   
         setupMatcher();
 185   
 
 186   
         Pattern compiled = _compiler.compile(pattern);
 187   
 
 188   
         if (_matcher.contains(message, compiled))
 189   
             return;
 190   
 
 191   
         throw new AssertionFailedError(
 192   
             "Exception message ("
 193   
                 + message
 194   
                 + ") does not contain regular expression ["
 195   
                 + pattern
 196   
                 + "].");
 197   
     }
 198   
 
 199   
     /**
 200   
      * Digs down through (potentially) a stack of ApplicationRuntimeExceptions until it
 201   
      * reaches the originating exception, which is returned.
 202   
      */
 203   
     protected Throwable findNestedException(ApplicationRuntimeException ex)
 204   
     {
 205   
         Throwable cause = ex.getRootCause();
 206   
 
 207   
         if (cause == null || cause == ex)
 208   
             return ex;
 209   
 
 210   
         if (cause instanceof ApplicationRuntimeException)
 211   
             return findNestedException((ApplicationRuntimeException) cause);
 212   
 
 213   
         return cause;
 214   
     }
 215   
 
 216   
     /**
 217   
      * Checks to see if a specific event matches the name and message.
 218   
      * @param message exact message to search for
 219   
      * @param events the list of events {@link #getInterceptedLogEvents()}
 220   
      * @param index the index to check at
 221   
      */
 222   
     private void assertLoggedMessage(String message, List events, int index)
 223   
     {
 224   
         LoggingEvent e = (LoggingEvent) events.get(index);
 225   
 
 226   
         assertEquals("Message", message, e.getMessage());
 227   
     }
 228   
 
 229   
     /**
 230   
      * Checks the messages for all logged events for exact match against
 231   
      * the supplied list.
 232   
      */
 233   
     protected void assertLoggedMessages(String[] messages)
 234   
     {
 235   
         List events = getInterceptedLogEvents();
 236   
 
 237   
         for (int i = 0; i < messages.length; i++)
 238   
         {
 239   
             assertLoggedMessage(messages[i], events, i);
 240   
         }
 241   
     }
 242   
 
 243   
     /**
 244   
      * Asserts that some capture log event matches the given message exactly.
 245   
      */
 246   
     protected void assertLoggedMessage(String message)
 247   
     {
 248   
         assertLoggedMessage(message, getInterceptedLogEvents());
 249   
     }
 250   
 
 251   
     /**
 252   
      * Asserts that some capture log event matches the given message exactly.
 253   
      * @param message to search for; success is finding a logged message contain the parameter as a substring
 254   
      * @param events from {@link #getInterceptedLogEvents()}
 255   
      */
 256   
     protected void assertLoggedMessage(String message, List events)
 257   
     {
 258   
         int count = events.size();
 259   
 
 260   
         for (int i = 0; i < count; i++)
 261   
         {
 262   
             LoggingEvent e = (LoggingEvent) events.get(i);
 263   
 
 264   
             String eventMessage = String.valueOf(e.getMessage());
 265   
 
 266   
             if (eventMessage.indexOf(message) >= 0)
 267   
                 return;
 268   
         }
 269   
 
 270   
         throw new AssertionFailedError("Could not find logged message: " + message);
 271   
     }
 272   
 
 273   
     protected void assertLoggedMessagePattern(String pattern) throws Exception
 274   
     {
 275   
         assertLoggedMessagePattern(pattern, getInterceptedLogEvents());
 276   
     }
 277   
 
 278   
     protected void assertLoggedMessagePattern(String pattern, List events) throws Exception
 279   
     {
 280   
         setupMatcher();
 281   
 
 282   
         Pattern compiled = null;
 283   
 
 284   
         int count = events.size();
 285   
 
 286   
         for (int i = 0; i < count; i++)
 287   
         {
 288   
             LoggingEvent e = (LoggingEvent) events.get(i);
 289   
 
 290   
             String eventMessage = e.getMessage().toString();
 291   
 
 292   
             if (compiled == null)
 293   
                 compiled = _compiler.compile(pattern);
 294   
 
 295   
             if (_matcher.contains(eventMessage, compiled))
 296   
                 return;
 297   
 
 298   
         }
 299   
 
 300   
         throw new AssertionFailedError("Could not find logging event: " + pattern);
 301   
     }
 302   
 
 303   
     private void setupMatcher()
 304   
     {
 305   
         if (_compiler == null)
 306   
             _compiler = new Perl5Compiler();
 307   
 
 308   
         if (_matcher == null)
 309   
             _matcher = new Perl5Matcher();
 310   
     }
 311   
 
 312   
     /**
 313   
      * Convienience method for invoking
 314   
      * {@link #buildFrameworkRegistry(String[])} with only a single file.
 315   
      */
 316   
     protected Registry buildFrameworkRegistry(String file) throws Exception
 317   
     {
 318   
         return buildFrameworkRegistry(new String[] { file });
 319   
     }
 320   
 
 321   
     /**
 322   
      * Builds a minimal registry, containing only the specified files, plus
 323   
      * the master module descriptor (i.e., those visible on the classpath).
 324   
      * Files are resolved using {@link HiveMindTestCase#getResource(String)}.
 325   
      */
 326   
     protected Registry buildFrameworkRegistry(String[] files) throws Exception
 327   
     {
 328   
         ClassResolver resolver = new DefaultClassResolver();
 329   
 
 330   
         RegistryBuilder builder = new RegistryBuilder();
 331   
 
 332   
         for (int i = 0; i < files.length; i++)
 333   
         {
 334   
             Resource resource = getResource(files[i]);
 335   
 
 336   
             builder.processModule(resolver, resource);
 337   
         }
 338   
 
 339   
         builder.processModules(resolver);
 340   
 
 341   
         return builder.constructRegistry(Locale.getDefault());
 342   
     }
 343   
 
 344   
     /**
 345   
      * Builds a registry from exactly the provided resource; this registry
 346   
      * will not include the <code>hivemind</code> module.
 347   
      */
 348   
     protected Registry buildMinimalRegistry(Resource l) throws Exception
 349   
     {
 350   
         RegistryBuilder builder = new RegistryBuilder();
 351   
 
 352   
         builder.processModule(new DefaultClassResolver(), l);
 353   
 
 354   
         return builder.constructRegistry(Locale.getDefault());
 355   
     }
 356   
 
 357   
     /**
 358   
      * Creates a <em>managed</em> control via
 359   
      * {@link MockControl#createStrictControl(java.lang.Class)}.
 360   
      * The created control is remembered, and will be
 361   
      * invoked by {@link #replayControls()} and
 362   
      * {@link #verifyControls()}.
 363   
      */
 364   
     protected MockControl newControl(Class mockClass)
 365   
     {
 366   
         MockControl result = MockControl.createStrictControl(mockClass);
 367   
 
 368   
         addControl(result);
 369   
 
 370   
         return result;
 371   
     }
 372   
 
 373   
     /**
 374   
      * Adds the control to the list of managed controls used by
 375   
      * {@link #replayControls()} and {@link #verifyControls()}.
 376   
      */
 377   
     protected void addControl(MockControl control)
 378   
     {
 379   
         _controls.add(control);
 380   
     }
 381   
 
 382   
     /**
 383   
      * Convienience for invoking {@link #newControl(Class)} and then
 384   
      * invoking {@link MockControl#getMock()} on the result.
 385   
      */
 386   
     protected Object newMock(Class mockClass)
 387   
     {
 388   
         return newControl(mockClass).getMock();
 389   
     }
 390   
 
 391   
     /**
 392   
      * Invokes {@link MockControl#replay()} on all controls
 393   
      * created by {@link #newControl(Class)}.
 394   
      */
 395   
     protected void replayControls()
 396   
     {
 397   
         Iterator i = _controls.iterator();
 398   
         while (i.hasNext())
 399   
         {
 400   
             MockControl c = (MockControl) i.next();
 401   
             c.replay();
 402   
         }
 403   
     }
 404   
 
 405   
     /**
 406   
      * Invokes {@link org.easymock.MockControl#verify()} on all
 407   
      * controls created by {@link #newControl(Class)}.
 408   
      */
 409   
 
 410   
     protected void verifyControls()
 411   
     {
 412   
         Iterator i = _controls.iterator();
 413   
         while (i.hasNext())
 414   
         {
 415   
             MockControl c = (MockControl) i.next();
 416   
             c.verify();
 417   
         }
 418   
     }
 419   
 }
 420