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