aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/testng/internal/RegexpExpectedExceptionsHolder.java
blob: f1f1e9311ecb439de020c6e67be1420ebd63afa2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package org.testng.internal;

import org.testng.IExpectedExceptionsHolder;
import org.testng.ITestNGMethod;
import org.testng.annotations.IExpectedExceptionsAnnotation;
import org.testng.annotations.ITestAnnotation;
import org.testng.internal.annotations.IAnnotationFinder;

import java.util.regex.Pattern;

/**
 * A class that contains the expected exceptions and the message regular expression.
 * @author cbeust
 */
public class RegexpExpectedExceptionsHolder implements IExpectedExceptionsHolder {
  public static final String DEFAULT_REGEXP = ".*";

  private final IAnnotationFinder finder;
  private final ITestNGMethod method;

  public RegexpExpectedExceptionsHolder(IAnnotationFinder finder, ITestNGMethod method) {
    this.finder = finder;
    this.method = method;
  }

  /**
   *   message / regEx  .*      other
   *   null             true    false
   *   non-null         true    match
   */
  @Override
  public boolean isThrowableMatching(Throwable ite) {
    String messageRegExp = getRegExp();

    if (DEFAULT_REGEXP.equals(messageRegExp)) {
      return true;
    }

    final String message = ite.getMessage();
    return message != null && Pattern.compile(messageRegExp, Pattern.DOTALL).matcher(message).matches();
  }

  public String getWrongExceptionMessage(Throwable ite) {
    return "The exception was thrown with the wrong message:" +
           " expected \"" + getRegExp() + "\"" +
           " but got \"" + ite.getMessage() + "\"";
  }

  private String getRegExp() {
    IExpectedExceptionsAnnotation expectedExceptions =
        finder.findAnnotation(method, IExpectedExceptionsAnnotation.class);
    if (expectedExceptions != null) {
      // Old syntax => default value
      return DEFAULT_REGEXP;
    }

    // New syntax
    ITestAnnotation testAnnotation = finder.findAnnotation(method, ITestAnnotation.class);
    if (testAnnotation != null) {
      return testAnnotation.getExpectedExceptionsMessageRegExp();
    }

    return DEFAULT_REGEXP;
  }
}