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