summaryrefslogtreecommitdiff
path: root/plugins/InspectionGadgets/src/com/siyeh/ig/junit/TestMethodWithoutAssertionInspection.java
blob: de8c3bd65b78b414533c78deefe59af225c83da5 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/*
 * Copyright 2003-2013 Dave Griffith, Bas Leijdekkers
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.siyeh.ig.junit;

import com.intellij.codeInspection.ui.ListTable;
import com.intellij.codeInspection.ui.ListWrappingTableModel;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.*;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.util.ui.CheckBox;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.TestUtils;
import com.siyeh.ig.ui.UiUtils;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class TestMethodWithoutAssertionInspection extends BaseInspection {

  /**
   * @noinspection PublicField
   */
  @NonNls public String assertionMethods =
    "org.junit.Assert,assert.*|fail.*," +
    "junit.framework.Assert,assert.*|fail.*," +
    "org.mockito.Mockito,verify.*," +
    "org.junit.rules.ExpectedException,expect.*";

  private final List<String> methodNamePatterns = new ArrayList();
  private final List<String> classNames = new ArrayList();
  private Map<String, Pattern> patternCache = null;

  @SuppressWarnings({"PublicField"})
  public boolean assertKeywordIsAssertion = false;

  public TestMethodWithoutAssertionInspection() {
    parseString(assertionMethods, classNames, methodNamePatterns);
  }

  @Override
  @NotNull
  public String getID() {
    return "JUnitTestMethodWithNoAssertions";
  }

  @Override
  @NotNull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("test.method.without.assertion.display.name");
  }

  @Override
  @NotNull
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message("test.method.without.assertion.problem.descriptor");
  }

  @Override
  public JComponent createOptionsPanel() {
    final JPanel panel = new JPanel(new BorderLayout());
    final ListTable table = new ListTable(
      new ListWrappingTableModel(Arrays.asList(classNames, methodNamePatterns), "Assertion class name",
                                 InspectionGadgetsBundle.message("method.name.pattern")));
    final JPanel tablePanel = UiUtils.createAddRemoveTreeClassChooserPanel(table, "Choose assertion class");
    final CheckBox checkBox =
      new CheckBox(InspectionGadgetsBundle.message("assert.keyword.is.considered.an.assertion"), this, "assertKeywordIsAssertion");
    panel.add(tablePanel, BorderLayout.CENTER);
    panel.add(checkBox, BorderLayout.SOUTH);
    return panel;
  }

  @Override
  public void readSettings(@NotNull Element element) throws InvalidDataException {
    super.readSettings(element);
    parseString(assertionMethods, classNames, methodNamePatterns);
  }

  @Override
  public void writeSettings(@NotNull Element element) throws WriteExternalException {
    assertionMethods = formatString(classNames, methodNamePatterns);
    super.writeSettings(element);
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new TestMethodWithoutAssertionVisitor();
  }

  private class TestMethodWithoutAssertionVisitor
    extends BaseInspectionVisitor {

    @Override
    public void visitMethod(@NotNull PsiMethod method) {
      super.visitMethod(method);
      if (!TestUtils.isJUnitTestMethod(method)) {
        return;
      }
      if (hasExpectedExceptionAnnotation(method)) {
        return;
      }
      if (containsAssertion(method)) {
        return;
      }
      if (lastStatementIsCallToMethodWithAssertion(method)) {
        return;
      }
      registerMethodError(method);
    }

    private boolean lastStatementIsCallToMethodWithAssertion(PsiMethod method) {
      final PsiCodeBlock body = method.getBody();
      if (body == null) {
        return false;
      }
      final PsiStatement[] statements = body.getStatements();
      if (statements.length <= 0) {
        return false;
      }
      final PsiStatement lastStatement = statements[0];
      if (!(lastStatement instanceof PsiExpressionStatement)) {
        return false;
      }
      final PsiExpressionStatement expressionStatement = (PsiExpressionStatement)lastStatement;
      final PsiExpression expression = expressionStatement.getExpression();
      if (!(expression instanceof PsiMethodCallExpression)) {
        return false;
      }
      final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression;
      final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
      final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
      if (qualifierExpression != null && !(qualifierExpression instanceof PsiThisExpression)) {
        return false;
      }
      final PsiMethod targetMethod = methodCallExpression.resolveMethod();
      return containsAssertion(targetMethod);
    }

    private boolean containsAssertion(PsiElement element) {
      if (element == null) {
        return false;
      }
      final ContainsAssertionVisitor visitor = new ContainsAssertionVisitor();
      element.accept(visitor);
      return visitor.containsAssertion();
    }

    private boolean hasExpectedExceptionAnnotation(PsiMethod method) {
      final PsiModifierList modifierList = method.getModifierList();
      final PsiAnnotation testAnnotation = modifierList.findAnnotation("org.junit.Test");
      if (testAnnotation == null) {
        return false;
      }
      final PsiAnnotationParameterList parameterList = testAnnotation.getParameterList();
      final PsiNameValuePair[] nameValuePairs = parameterList.getAttributes();
      for (PsiNameValuePair nameValuePair : nameValuePairs) {
        @NonNls final String parameterName = nameValuePair.getName();
        if ("expected".equals(parameterName)) {
          return true;
        }
      }
      return false;
    }
  }

  private class ContainsAssertionVisitor extends JavaRecursiveElementVisitor {

    private boolean containsAssertion = false;

    @Override
    public void visitElement(@NotNull PsiElement element) {
      if (!containsAssertion) {
        super.visitElement(element);
      }
    }

    @Override
    public void visitMethodCallExpression(@NotNull PsiMethodCallExpression call) {
      if (containsAssertion) {
        return;
      }
      super.visitMethodCallExpression(call);
      final PsiReferenceExpression methodExpression = call.getMethodExpression();
      @NonNls final String methodName = methodExpression.getReferenceName();
      if (methodName == null) {
        return;
      }
      final int methodNamesSize = methodNamePatterns.size();
      for (int i = 0; i < methodNamesSize; i++) {
        final String pattern = methodNamePatterns.get(i);
        if (!methodNamesMatch(methodName, pattern)) {
          continue;
        }
        final PsiMethod method = call.resolveMethod();
        if (method == null || method.isConstructor()) {
          continue;
        }
        final PsiClass aClass = method.getContainingClass();
        if (!InheritanceUtil.isInheritor(aClass, classNames.get(i))) {
          continue;
        }
        containsAssertion = true;
        break;
      }
    }

    @Override
    public void visitAssertStatement(PsiAssertStatement statement) {
      if (containsAssertion) {
        return;
      }
      super.visitAssertStatement(statement);
      if (!assertKeywordIsAssertion) {
        return;
      }
      containsAssertion = true;
    }

    public boolean containsAssertion() {
      return containsAssertion;
    }
  }

  private boolean methodNamesMatch(String methodName, String methodNamePattern) {
    Pattern pattern;
    if (patternCache != null) {
      pattern = patternCache.get(methodNamePattern);
    }
    else {
      patternCache = new HashMap(methodNamePatterns.size());
      pattern = null;
    }
    if (pattern == null) {
      try {
        pattern = Pattern.compile(methodNamePattern);
        patternCache.put(methodNamePattern, pattern);
      }
      catch (PatternSyntaxException ignore) {
        return false;
      }
      catch (NullPointerException ignore) {
        return false;
      }
    }
    if (pattern == null) {
      return false;
    }
    final Matcher matcher = pattern.matcher(methodName);
    return matcher.matches();
  }
}