01: package org.acm.seguin.pmd.rules.junit;
02:
03: import org.acm.seguin.pmd.AbstractRule;
04: import org.acm.seguin.pmd.Rule;
05: import org.acm.seguin.pmd.RuleContext;
06: import net.sourceforge.jrefactory.ast.ASTArguments;
07: import net.sourceforge.jrefactory.ast.ASTName;
08: import net.sourceforge.jrefactory.ast.ASTPrimaryExpression;
09: import net.sourceforge.jrefactory.ast.ASTPrimaryPrefix;
10:
11: import java.util.ArrayList;
12: import java.util.Iterator;
13: import java.util.List;
14:
15: public class JUnitAssertionsShouldIncludeMessageRule extends
16: AbstractRule implements Rule {
17:
18: private static class AssertionCall {
19: public int args;
20: public String name;
21:
22: public AssertionCall(int args, String name) {
23: this .args = args;
24: this .name = name;
25: }
26: }
27:
28: private List checks = new ArrayList();
29:
30: public JUnitAssertionsShouldIncludeMessageRule() {
31: checks.add(new AssertionCall(2, "assertEquals"));
32: checks.add(new AssertionCall(1, "assertTrue"));
33: checks.add(new AssertionCall(1, "assertNull"));
34: checks.add(new AssertionCall(2, "assertSame"));
35: checks.add(new AssertionCall(1, "assertNotNull"));
36: }
37:
38: public Object visit(ASTArguments node, Object data) {
39: for (Iterator i = checks.iterator(); i.hasNext();) {
40: AssertionCall call = (AssertionCall) i.next();
41: check((RuleContext) data, node, call.args, call.name);
42: }
43: return super .visit(node, data);
44: }
45:
46: private void check(RuleContext ctx, ASTArguments node, int args,
47: String targetMethodName) {
48: if (node.getArgumentCount() == args
49: && node.jjtGetParent().jjtGetParent() instanceof ASTPrimaryExpression) {
50: ASTPrimaryExpression primary = (ASTPrimaryExpression) node
51: .jjtGetParent().jjtGetParent();
52: if (primary.jjtGetFirstChild() instanceof ASTPrimaryPrefix
53: && primary.jjtGetFirstChild().jjtGetNumChildren() > 0
54: && primary.jjtGetFirstChild().jjtGetFirstChild() instanceof ASTName) {
55: ASTName name = (ASTName) primary.jjtGetFirstChild()
56: .jjtGetFirstChild();
57: if (name.getImage().equals(targetMethodName)) {
58: ctx.getReport().addRuleViolation(
59: createRuleViolation(ctx, name
60: .getBeginLine()));
61: }
62: }
63: }
64: }
65: }
|