01 /**
02 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03 */
04 package net.sourceforge.pmd.lang.java.rule.junit;
05
06 import net.sourceforge.pmd.lang.ast.Node;
07 import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
08 import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
09 import net.sourceforge.pmd.lang.java.ast.ASTName;
10 import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
11 import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
12 import net.sourceforge.pmd.lang.java.ast.ASTStatementExpression;
13
14 public class JUnitTestsShouldIncludeAssertRule extends AbstractJUnitRule {
15
16 @Override
17 public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
18 if (node.isInterface()) {
19 return data;
20 }
21 return super.visit(node, data);
22 }
23
24 @Override
25 public Object visit(ASTMethodDeclaration method, Object data) {
26 if (isJUnitMethod(method, data)) {
27 if (!containsAssert(method.getBlock(), false)) {
28 addViolation(data, method);
29 }
30 }
31 return data;
32 }
33
34 private boolean containsAssert(Node n, boolean assertFound) {
35 if (!assertFound) {
36 if (n instanceof ASTStatementExpression) {
37 if (isAssertOrFailStatement((ASTStatementExpression)n)) {
38 return true;
39 }
40 }
41 if (!assertFound) {
42 for (int i=0;i<n.jjtGetNumChildren() && ! assertFound;i++) {
43 Node c = n.jjtGetChild(i);
44 if (containsAssert(c, assertFound)) {
45 return true;
46 }
47 }
48 }
49 }
50 return false;
51 }
52
53 /**
54 * Tells if the expression is an assert statement or not.
55 */
56 private boolean isAssertOrFailStatement(ASTStatementExpression expression) {
57 if (expression!=null
58 && expression.jjtGetNumChildren()>0
59 && expression.jjtGetChild(0) instanceof ASTPrimaryExpression
60 ) {
61 ASTPrimaryExpression pe = (ASTPrimaryExpression) expression.jjtGetChild(0);
62 if (pe.jjtGetNumChildren()> 0 && pe.jjtGetChild(0) instanceof ASTPrimaryPrefix) {
63 ASTPrimaryPrefix pp = (ASTPrimaryPrefix) pe.jjtGetChild(0);
64 if (pp.jjtGetNumChildren()>0 && pp.jjtGetChild(0) instanceof ASTName) {
65 String img = ((ASTName) pp.jjtGetChild(0)).getImage();
66 if (img != null && (img.startsWith("assert") || img.startsWith("fail") || img.startsWith("Assert.assert") || img.startsWith("Assert.fail") )) {
67 return true;
68 }
69 }
70 }
71 }
72 return false;
73 }
74 }
|