Clover coverage report - Code Coverage for hivemind release 1.0-rc-1
Coverage timestamp: Wed Aug 25 2004 13:06:02 EDT
file stats: LOC: 473   Methods: 0
NCLOC: 257   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   
         super.tearDown();
 153   
 
 154   
         if (_appender != null)
 155   
         {
 156   
             _appender = null;
 157   
 
 158   
             Logger logger = LogManager.getLogger(_interceptedLoggerName);
 159   
             logger.setLevel(null);
 160   
             logger.setAdditivity(true);
 161   
             logger.removeAllAppenders();
 162   
         }
 163   
     }
 164   
 
 165   
     /**
 166   
      * Checks that the provided substring exists in the exceptions message.
 167   
      */
 168   
     protected void assertExceptionSubstring(Throwable ex, String substring)
 169   
     {
 170   
         String message = ex.getMessage();
 171   
         assertNotNull(message);
 172   
 
 173   
         int pos = message.indexOf(substring);
 174   
 
 175   
         if (pos < 0)
 176   
             throw new AssertionFailedError(
 177   
                 "Exception message (" + message + ") does not contain [" + substring + "]");
 178   
     }
 179   
 
 180   
     /**
 181   
      * Checks that the message for an exception matches a regular expression.
 182   
      */
 183   
 
 184   
     protected void assertExceptionRegexp(Throwable ex, String pattern) throws Exception
 185   
     {
 186   
         String message = ex.getMessage();
 187   
         assertNotNull(message);
 188   
 
 189   
         setupMatcher();
 190   
 
 191   
         Pattern compiled = _compiler.compile(pattern);
 192   
 
 193   
         if (_matcher.contains(message, compiled))
 194   
             return;
 195   
 
 196   
         throw new AssertionFailedError(
 197   
             "Exception message ("
 198   
                 + message
 199   
                 + ") does not contain regular expression ["
 200   
                 + pattern
 201   
                 + "].");
 202   
     }
 203   
 
 204   
     protected void assertRegexp(String pattern, String actual) throws Exception
 205   
     {
 206   
         setupMatcher();
 207   
 
 208   
         Pattern compiled = _compiler.compile(pattern);
 209   
 
 210   
         if (_matcher.contains(actual, compiled))
 211   
             return;
 212   
 
 213   
         throw new AssertionFailedError(
 214   
             "\"" + actual + "\" does not contain regular expression[" + pattern + "].");
 215   
     }
 216   
 
 217   
     /**
 218   
      * Digs down through (potentially) a stack of ApplicationRuntimeExceptions until it
 219   
      * reaches the originating exception, which is returned.
 220   
      */
 221   
     protected Throwable findNestedException(ApplicationRuntimeException ex)
 222   
     {
 223   
         Throwable cause = ex.getRootCause();
 224   
 
 225   
         if (cause == null || cause == ex)
 226   
             return ex;
 227   
 
 228   
         if (cause instanceof ApplicationRuntimeException)
 229   
             return findNestedException((ApplicationRuntimeException) cause);
 230   
 
 231   
         return cause;
 232   
     }
 233   
 
 234   
     /**
 235   
      * Checks to see if a specific event matches the name and message.
 236   
      * @param message exact message to search for
 237   
      * @param events the list of events {@link #getInterceptedLogEvents()}
 238   
      * @param index the index to check at
 239   
      */
 240   
     private void assertLoggedMessage(String message, List events, int index)
 241   
     {
 242   
         LoggingEvent e = (LoggingEvent) events.get(index);
 243   
 
 244   
         assertEquals("Message", message, e.getMessage());
 245   
     }
 246   
 
 247   
     /**
 248   
      * Checks the messages for all logged events for exact match against
 249   
      * the supplied list.
 250   
      */
 251   
     protected void assertLoggedMessages(String[] messages)
 252   
     {
 253   
         List events = getInterceptedLogEvents();
 254   
 
 255   
         for (int i = 0; i < messages.length; i++)
 256   
         {
 257   
             assertLoggedMessage(messages[i], events, i);
 258   
         }
 259   
     }
 260   
 
 261   
     /**
 262   
      * Asserts that some capture log event matches the given message exactly.
 263   
      */
 264   
     protected void assertLoggedMessage(String message)
 265   
     {
 266   
         assertLoggedMessage(message, getInterceptedLogEvents());
 267   
     }
 268   
 
 269   
     /**
 270   
      * Asserts that some capture log event matches the given message exactly.
 271   
      * @param message to search for; success is finding a logged message contain the parameter as a substring
 272   
      * @param events from {@link #getInterceptedLogEvents()}
 273   
      */
 274   
     protected void assertLoggedMessage(String message, List events)
 275   
     {
 276   
         int count = events.size();
 277   
 
 278   
         for (int i = 0; i < count; i++)
 279   
         {
 280   
             LoggingEvent e = (LoggingEvent) events.get(i);
 281   
 
 282   
             String eventMessage = String.valueOf(e.getMessage());
 283   
 
 284   
             if (eventMessage.indexOf(message) >= 0)
 285   
                 return;
 286   
         }
 287   
 
 288   
         throw new AssertionFailedError("Could not find logged message: " + message);
 289   
     }
 290   
 
 291   
     protected void assertLoggedMessagePattern(String pattern) throws Exception
 292   
     {
 293   
         assertLoggedMessagePattern(pattern, getInterceptedLogEvents());
 294   
     }
 295   
 
 296   
     protected void assertLoggedMessagePattern(String pattern, List events) throws Exception
 297   
     {
 298   
         setupMatcher();
 299   
 
 300   
         Pattern compiled = null;
 301   
 
 302   
         int count = events.size();
 303   
 
 304   
         for (int i = 0; i < count; i++)
 305   
         {
 306   
             LoggingEvent e = (LoggingEvent) events.get(i);
 307   
 
 308   
             String eventMessage = e.getMessage().toString();
 309   
 
 310   
             if (compiled == null)
 311   
                 compiled = _compiler.compile(pattern);
 312   
 
 313   
             if (_matcher.contains(eventMessage, compiled))
 314   
                 return;
 315   
 
 316   
         }
 317   
 
 318   
         throw new AssertionFailedError("Could not find logging event: " + pattern);
 319   
     }
 320   
 
 321   
     private void setupMatcher()
 322   
     {
 323   
         if (_compiler == null)
 324   
             _compiler = new Perl5Compiler();
 325   
 
 326   
         if (_matcher == null)
 327   
             _matcher = new Perl5Matcher();
 328   
     }
 329   
 
 330   
     /**
 331   
      * Convienience method for invoking
 332   
      * {@link #buildFrameworkRegistry(String[])} with only a single file.
 333   
      */
 334   
     protected Registry buildFrameworkRegistry(String file) throws Exception
 335   
     {
 336   
         return buildFrameworkRegistry(new String[] { file });
 337   
     }
 338   
 
 339   
     /**
 340   
      * Builds a minimal registry, containing only the specified files, plus
 341   
      * the master module descriptor (i.e., those visible on the classpath).
 342   
      * Files are resolved using {@link HiveMindTestCase#getResource(String)}.
 343   
      */
 344   
     protected Registry buildFrameworkRegistry(String[] files) throws Exception
 345   
     {
 346   
         ClassResolver resolver = new DefaultClassResolver();
 347   
 
 348   
         RegistryBuilder builder = new RegistryBuilder();
 349   
 
 350   
         for (int i = 0; i < files.length; i++)
 351   
         {
 352   
             Resource resource = getResource(files[i]);
 353   
 
 354   
             builder.processModule(resolver, resource);
 355   
         }
 356   
 
 357   
         builder.processModules(resolver);
 358   
 
 359   
         return builder.constructRegistry(Locale.getDefault());
 360   
     }
 361   
 
 362   
     /**
 363   
      * Builds a registry from exactly the provided resource; this registry
 364   
      * will not include the <code>hivemind</code> module.
 365   
      */
 366   
     protected Registry buildMinimalRegistry(Resource l) throws Exception
 367   
     {
 368   
         RegistryBuilder builder = new RegistryBuilder();
 369   
 
 370   
         builder.processModule(new DefaultClassResolver(), l);
 371   
 
 372   
         return builder.constructRegistry(Locale.getDefault());
 373   
     }
 374   
 
 375   
     /**
 376   
      * Creates a <em>managed</em> control via
 377   
      * {@link MockControl#createStrictControl(java.lang.Class)}.
 378   
      * The created control is remembered, and will be
 379   
      * invoked by {@link #replayControls()},
 380   
      * {@link #verifyControls()}, etc..
 381   
      */
 382   
     protected MockControl newControl(Class mockClass)
 383   
     {
 384   
         MockControl result = MockControl.createStrictControl(mockClass);
 385   
 
 386   
         addControl(result);
 387   
 
 388   
         return result;
 389   
     }
 390   
 
 391   
     /**
 392   
      * Adds the control to the list of managed controls used by
 393   
      * {@link #replayControls()} and {@link #verifyControls()}.
 394   
      */
 395   
     protected void addControl(MockControl control)
 396   
     {
 397   
         _controls.add(control);
 398   
     }
 399   
 
 400   
     /**
 401   
      * Convienience for invoking {@link #newControl(Class)} and then
 402   
      * invoking {@link MockControl#getMock()} on the result.
 403   
      */
 404   
     protected Object newMock(Class mockClass)
 405   
     {
 406   
         return newControl(mockClass).getMock();
 407   
     }
 408   
 
 409   
     /**
 410   
      * Invokes {@link MockControl#replay()} on all controls
 411   
      * created by {@link #newControl(Class)}.
 412   
      */
 413   
     protected void replayControls()
 414   
     {
 415   
         Iterator i = _controls.iterator();
 416   
         while (i.hasNext())
 417   
         {
 418   
             MockControl c = (MockControl) i.next();
 419   
             c.replay();
 420   
         }
 421   
     }
 422   
 
 423   
     /**
 424   
      * Invokes {@link org.easymock.MockControl#verify()} and
 425   
      * {@link MockControl#reset()} on all
 426   
      * controls created by {@link #newControl(Class)}.
 427   
      */
 428   
 
 429   
     protected void verifyControls()
 430   
     {
 431   
         Iterator i = _controls.iterator();
 432   
         while (i.hasNext())
 433   
         {
 434   
             MockControl c = (MockControl) i.next();
 435   
             c.verify();
 436   
             c.reset();
 437   
         }
 438   
     }
 439   
 
 440   
     /**
 441   
      * Invokes {@link org.easymock.MockControl#reset()} on all
 442   
      * controls.
 443   
      */
 444   
 
 445   
     protected void resetControls()
 446   
     {
 447   
         Iterator i = _controls.iterator();
 448   
         while (i.hasNext())
 449   
         {
 450   
             MockControl c = (MockControl) i.next();
 451   
             c.reset();
 452   
         }
 453   
     }
 454   
 
 455   
     protected Location fabricateLocation(int line)
 456   
     {
 457   
         String path = "/" + getClass().getName().replace('.', '/');
 458   
 
 459   
         Resource r = new ClasspathResource(new DefaultClassResolver(), path);
 460   
 
 461   
         return new LocationImpl(r, line);
 462   
     }
 463   
 
 464   
     protected boolean matches(String input, String pattern) throws Exception
 465   
     {
 466   
         setupMatcher();
 467   
 
 468   
         Pattern compiled = _compiler.compile(pattern);
 469   
 
 470   
         return _matcher.matches(input, compiled);
 471   
     }
 472   
 }
 473