Clover coverage report - Code Coverage for hivemind release 1.1-alpha-2
Coverage timestamp: Wed Feb 23 2005 09:59:04 EST
file stats: LOC: 556   Methods: 0
NCLOC: 311   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   
 
 187   
         logger.setLevel(Level.DEBUG);
 188   
         logger.setAdditivity(false);
 189   
         logger.addAppender(_appender);
 190   
     }
 191   
 
 192   
     /**
 193   
      * Gets the list of events most recently intercepted. This resets the appender, clearing the
 194   
      * list of stored events.
 195   
      * 
 196   
      * @see #interceptLogging(String)
 197   
      */
 198   
 
 199   
     protected List getInterceptedLogEvents()
 200   
     {
 201   
         return _appender.getEvents();
 202   
     }
 203   
 
 204   
     /**
 205   
      * Removes the appender that may have been setup by {@link #interceptLogging(String)}. Also,
 206   
      * invokes {@link org.apache.hivemind.util.PropertyUtils#clearCache()}.
 207   
      */
 208   
     protected void tearDown() throws Exception
 209   
     {
 210   
         super.tearDown();
 211   
 
 212   
         if (_appender != null)
 213   
         {
 214   
             _appender = null;
 215   
 
 216   
             Logger logger = LogManager.getLogger(_interceptedLoggerName);
 217   
             logger.setLevel(null);
 218   
             logger.setAdditivity(true);
 219   
             logger.removeAllAppenders();
 220   
         }
 221   
 
 222   
         PropertyUtils.clearCache();
 223   
 
 224   
         ServiceSerializationHelper.setServiceSerializationSupport(null);
 225   
     }
 226   
 
 227   
     /**
 228   
      * Checks that the provided substring exists in the exceptions message.
 229   
      */
 230   
     protected void assertExceptionSubstring(Throwable ex, String substring)
 231   
     {
 232   
         String message = ex.getMessage();
 233   
         assertNotNull(message);
 234   
 
 235   
         int pos = message.indexOf(substring);
 236   
 
 237   
         if (pos < 0)
 238   
             throw new AssertionFailedError("Exception message (" + message + ") does not contain ["
 239   
                     + substring + "]");
 240   
     }
 241   
 
 242   
     /**
 243   
      * Checks that the message for an exception matches a regular expression.
 244   
      */
 245   
 
 246   
     protected void assertExceptionRegexp(Throwable ex, String pattern) throws Exception
 247   
     {
 248   
         String message = ex.getMessage();
 249   
         assertNotNull(message);
 250   
 
 251   
         setupMatcher();
 252   
 
 253   
         Pattern compiled = _compiler.compile(pattern);
 254   
 
 255   
         if (_matcher.contains(message, compiled))
 256   
             return;
 257   
 
 258   
         throw new AssertionFailedError("Exception message (" + message
 259   
                 + ") does not contain regular expression [" + pattern + "].");
 260   
     }
 261   
 
 262   
     protected void assertRegexp(String pattern, String actual) throws Exception
 263   
     {
 264   
         setupMatcher();
 265   
 
 266   
         Pattern compiled = _compiler.compile(pattern);
 267   
 
 268   
         if (_matcher.contains(actual, compiled))
 269   
             return;
 270   
 
 271   
         throw new AssertionFailedError("\"" + actual + "\" does not contain regular expression["
 272   
                 + pattern + "].");
 273   
     }
 274   
 
 275   
     /**
 276   
      * Digs down through (potentially) a stack of ApplicationRuntimeExceptions until it reaches the
 277   
      * originating exception, which is returned.
 278   
      */
 279   
     protected Throwable findNestedException(ApplicationRuntimeException ex)
 280   
     {
 281   
         Throwable cause = ex.getRootCause();
 282   
 
 283   
         if (cause == null || cause == ex)
 284   
             return ex;
 285   
 
 286   
         if (cause instanceof ApplicationRuntimeException)
 287   
             return findNestedException((ApplicationRuntimeException) cause);
 288   
 
 289   
         return cause;
 290   
     }
 291   
 
 292   
     /**
 293   
      * Checks to see if a specific event matches the name and message.
 294   
      * 
 295   
      * @param message
 296   
      *            exact message to search for
 297   
      * @param events
 298   
      *            the list of events {@link #getInterceptedLogEvents()}
 299   
      * @param index
 300   
      *            the index to check at
 301   
      */
 302   
     private void assertLoggedMessage(String message, List events, int index)
 303   
     {
 304   
         LoggingEvent e = (LoggingEvent) events.get(index);
 305   
 
 306   
         assertEquals("Message", message, e.getMessage());
 307   
     }
 308   
 
 309   
     /**
 310   
      * Checks the messages for all logged events for exact match against the supplied list.
 311   
      */
 312   
     protected void assertLoggedMessages(String[] messages)
 313   
     {
 314   
         List events = getInterceptedLogEvents();
 315   
 
 316   
         for (int i = 0; i < messages.length; i++)
 317   
         {
 318   
             assertLoggedMessage(messages[i], events, i);
 319   
         }
 320   
     }
 321   
 
 322   
     /**
 323   
      * Asserts that some capture log event matches the given message exactly.
 324   
      */
 325   
     protected void assertLoggedMessage(String message)
 326   
     {
 327   
         assertLoggedMessage(message, getInterceptedLogEvents());
 328   
     }
 329   
 
 330   
     /**
 331   
      * Asserts that some capture log event matches the given message exactly.
 332   
      * 
 333   
      * @param message
 334   
      *            to search for; success is finding a logged message contain the parameter as a
 335   
      *            substring
 336   
      * @param events
 337   
      *            from {@link #getInterceptedLogEvents()}
 338   
      */
 339   
     protected void assertLoggedMessage(String message, List events)
 340   
     {
 341   
         int count = events.size();
 342   
 
 343   
         for (int i = 0; i < count; i++)
 344   
         {
 345   
             LoggingEvent e = (LoggingEvent) events.get(i);
 346   
 
 347   
             String eventMessage = String.valueOf(e.getMessage());
 348   
 
 349   
             if (eventMessage.indexOf(message) >= 0)
 350   
                 return;
 351   
         }
 352   
 
 353   
         throw new AssertionFailedError("Could not find logged message: " + message);
 354   
     }
 355   
 
 356   
     protected void assertLoggedMessagePattern(String pattern) throws Exception
 357   
     {
 358   
         assertLoggedMessagePattern(pattern, getInterceptedLogEvents());
 359   
     }
 360   
 
 361   
     protected void assertLoggedMessagePattern(String pattern, List events) throws Exception
 362   
     {
 363   
         setupMatcher();
 364   
 
 365   
         Pattern compiled = null;
 366   
 
 367   
         int count = events.size();
 368   
 
 369   
         for (int i = 0; i < count; i++)
 370   
         {
 371   
             LoggingEvent e = (LoggingEvent) events.get(i);
 372   
 
 373   
             String eventMessage = e.getMessage().toString();
 374   
 
 375   
             if (compiled == null)
 376   
                 compiled = _compiler.compile(pattern);
 377   
 
 378   
             if (_matcher.contains(eventMessage, compiled))
 379   
                 return;
 380   
 
 381   
         }
 382   
 
 383   
         throw new AssertionFailedError("Could not find logged message with pattern: " + pattern);
 384   
     }
 385   
 
 386   
     private void setupMatcher()
 387   
     {
 388   
         if (_compiler == null)
 389   
             _compiler = new Perl5Compiler();
 390   
 
 391   
         if (_matcher == null)
 392   
             _matcher = new Perl5Matcher();
 393   
     }
 394   
 
 395   
     /**
 396   
      * Convienience method for invoking {@link #buildFrameworkRegistry(String[])}with only a single
 397   
      * file.
 398   
      */
 399   
     protected Registry buildFrameworkRegistry(String file) throws Exception
 400   
     {
 401   
         return buildFrameworkRegistry(new String[]
 402   
         { file });
 403   
     }
 404   
 
 405   
     /**
 406   
      * Builds a minimal registry, containing only the specified files, plus the master module
 407   
      * descriptor (i.e., those visible on the classpath). Files are resolved using
 408   
      * {@link HiveMindTestCase#getResource(String)}.
 409   
      */
 410   
     protected Registry buildFrameworkRegistry(String[] files) throws Exception
 411   
     {
 412   
         ClassResolver resolver = new DefaultClassResolver();
 413   
 
 414   
         List descriptorResources = new ArrayList();
 415   
         for (int i = 0; i < files.length; i++)
 416   
         {
 417   
             Resource resource = getResource(files[i]);
 418   
 
 419   
             descriptorResources.add(resource);
 420   
         }
 421   
 
 422   
         ModuleDescriptorProvider provider = new XmlModuleDescriptorProvider(resolver,
 423   
                 descriptorResources);
 424   
 
 425   
         return buildFrameworkRegistry(provider);
 426   
     }
 427   
 
 428   
     /**
 429   
      * Builds a registry, containing only the modules delivered by the specified
 430   
      * {@link org.apache.hivemind.ModuleDescriptorProvider}, plus the master module descriptor
 431   
      * (i.e., those visible on the classpath).
 432   
      */
 433   
     protected Registry buildFrameworkRegistry(ModuleDescriptorProvider customProvider)
 434   
     {
 435   
         ClassResolver resolver = new DefaultClassResolver();
 436   
 
 437   
         RegistryBuilder builder = new RegistryBuilder();
 438   
 
 439   
         builder.addModuleDescriptorProvider(new XmlModuleDescriptorProvider(resolver));
 440   
         builder.addModuleDescriptorProvider(customProvider);
 441   
 
 442   
         return builder.constructRegistry(Locale.getDefault());
 443   
     }
 444   
 
 445   
     /**
 446   
      * Builds a registry from exactly the provided resource; this registry will not include the
 447   
      * <code>hivemind</code> module.
 448   
      */
 449   
     protected Registry buildMinimalRegistry(Resource l) throws Exception
 450   
     {
 451   
         RegistryBuilder builder = new RegistryBuilder();
 452   
 
 453   
         return builder.constructRegistry(Locale.getDefault());
 454   
     }
 455   
 
 456   
     /**
 457   
      * Creates a <em>managed</em> control via
 458   
      * {@link MockControl#createStrictControl(java.lang.Class)}. The created control is remembered,
 459   
      * and will be invoked by {@link #replayControls()},{@link #verifyControls()}, etc..
 460   
      * <p>
 461   
      * The class to mock may be either an interface or a class. The EasyMock class extension
 462   
      * (easymockclassextension-1.1.jar) and CGLIB (cglib-full-2.01.jar) must be present in the
 463   
      * latter case (new since 1.1).
 464   
      */
 465   
     protected MockControl newControl(Class mockClass)
 466   
     {
 467   
         MockControlFactory factory = mockClass.isInterface() ? _interfaceMockControlFactory
 468   
                 : _classMockControlFactory;
 469   
 
 470   
         MockControl result = factory.newControl(mockClass);
 471   
 
 472   
         addControl(result);
 473   
 
 474   
         return result;
 475   
     }
 476   
 
 477   
     /**
 478   
      * Adds the control to the list of managed controls used by {@link #replayControls()}and
 479   
      * {@link #verifyControls()}.
 480   
      */
 481   
     protected void addControl(MockControl control)
 482   
     {
 483   
         _controls.add(control);
 484   
     }
 485   
 
 486   
     /**
 487   
      * Convienience for invoking {@link #newControl(Class)}and then invoking
 488   
      * {@link MockControl#getMock()}on the result.
 489   
      */
 490   
     protected Object newMock(Class mockClass)
 491   
     {
 492   
         return newControl(mockClass).getMock();
 493   
     }
 494   
 
 495   
     /**
 496   
      * Invokes {@link MockControl#replay()}on all controls created by {@link #newControl(Class)}.
 497   
      */
 498   
     protected void replayControls()
 499   
     {
 500   
         Iterator i = _controls.iterator();
 501   
         while (i.hasNext())
 502   
         {
 503   
             MockControl c = (MockControl) i.next();
 504   
             c.replay();
 505   
         }
 506   
     }
 507   
 
 508   
     /**
 509   
      * Invokes {@link org.easymock.MockControl#verify()}and {@link MockControl#reset()}on all
 510   
      * controls created by {@link #newControl(Class)}.
 511   
      */
 512   
 
 513   
     protected void verifyControls()
 514   
     {
 515   
         Iterator i = _controls.iterator();
 516   
         while (i.hasNext())
 517   
         {
 518   
             MockControl c = (MockControl) i.next();
 519   
             c.verify();
 520   
             c.reset();
 521   
         }
 522   
     }
 523   
 
 524   
     /**
 525   
      * Invokes {@link org.easymock.MockControl#reset()}on all controls.
 526   
      */
 527   
 
 528   
     protected void resetControls()
 529   
     {
 530   
         Iterator i = _controls.iterator();
 531   
         while (i.hasNext())
 532   
         {
 533   
             MockControl c = (MockControl) i.next();
 534   
             c.reset();
 535   
         }
 536   
     }
 537   
 
 538   
     protected Location fabricateLocation(int line)
 539   
     {
 540   
         String path = "/" + getClass().getName().replace('.', '/');
 541   
 
 542   
         Resource r = new ClasspathResource(new DefaultClassResolver(), path);
 543   
 
 544   
         return new LocationImpl(r, line);
 545   
     }
 546   
 
 547   
     protected boolean matches(String input, String pattern) throws Exception
 548   
     {
 549   
         setupMatcher();
 550   
 
 551   
         Pattern compiled = _compiler.compile(pattern);
 552   
 
 553   
         return _matcher.matches(input, compiled);
 554   
     }
 555   
 
 556   
 }