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