Home | History | Annotate | Download | only in internal
      1 package org.testng.internal;
      2 
      3 import org.testng.IExpectedExceptionsHolder;
      4 import org.testng.ITestNGMethod;
      5 import org.testng.annotations.IExpectedExceptionsAnnotation;
      6 import org.testng.annotations.ITestAnnotation;
      7 import org.testng.internal.annotations.IAnnotationFinder;
      8 
      9 import java.util.regex.Pattern;
     10 
     11 /**
     12  * A class that contains the expected exceptions and the message regular expression.
     13  * @author cbeust
     14  */
     15 public class RegexpExpectedExceptionsHolder implements IExpectedExceptionsHolder {
     16   public static final String DEFAULT_REGEXP = ".*";
     17 
     18   private final IAnnotationFinder finder;
     19   private final ITestNGMethod method;
     20 
     21   public RegexpExpectedExceptionsHolder(IAnnotationFinder finder, ITestNGMethod method) {
     22     this.finder = finder;
     23     this.method = method;
     24   }
     25 
     26   /**
     27    *   message / regEx  .*      other
     28    *   null             true    false
     29    *   non-null         true    match
     30    */
     31   @Override
     32   public boolean isThrowableMatching(Throwable ite) {
     33     String messageRegExp = getRegExp();
     34 
     35     if (DEFAULT_REGEXP.equals(messageRegExp)) {
     36       return true;
     37     }
     38 
     39     final String message = ite.getMessage();
     40     return message != null && Pattern.compile(messageRegExp, Pattern.DOTALL).matcher(message).matches();
     41   }
     42 
     43   public String getWrongExceptionMessage(Throwable ite) {
     44     return "The exception was thrown with the wrong message:" +
     45            " expected \"" + getRegExp() + "\"" +
     46            " but got \"" + ite.getMessage() + "\"";
     47   }
     48 
     49   private String getRegExp() {
     50     IExpectedExceptionsAnnotation expectedExceptions =
     51         finder.findAnnotation(method, IExpectedExceptionsAnnotation.class);
     52     if (expectedExceptions != null) {
     53       // Old syntax => default value
     54       return DEFAULT_REGEXP;
     55     }
     56 
     57     // New syntax
     58     ITestAnnotation testAnnotation = finder.findAnnotation(method, ITestAnnotation.class);
     59     if (testAnnotation != null) {
     60       return testAnnotation.getExpectedExceptionsMessageRegExp();
     61     }
     62 
     63     return DEFAULT_REGEXP;
     64   }
     65 }
     66