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 package com.qulice.pmd.rules;
32
33 import net.sourceforge.pmd.lang.ast.Node;
34 import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
35 import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
36 import net.sourceforge.pmd.lang.java.ast.ASTName;
37 import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
38 import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
39 import net.sourceforge.pmd.lang.java.ast.ASTStatementExpression;
40
41
42
43
44
45 @SuppressWarnings("deprecation")
46 public final class ProhibitPlainJunitAssertionsRule
47 extends net.sourceforge.pmd.lang.java.rule.AbstractJUnitRule {
48
49
50
51
52 private static final String[] PROHIBITED = {
53 "org.junit.Assert.assert",
54 "junit.framework.Assert.assert",
55 };
56
57 @Override
58 public Object visit(final ASTMethodDeclaration method, final Object data) {
59 if (this.isJUnitMethod(method, data)
60 && this.containsPlainJunitAssert(method.getBody())) {
61 this.asCtx(data).addViolation(method);
62 }
63 return data;
64 }
65
66 @Override
67 public Object visit(final ASTImportDeclaration imp, final Object data) {
68 for (final String element : ProhibitPlainJunitAssertionsRule
69 .PROHIBITED) {
70 if (imp.getImportedName().contains(element)) {
71 this.asCtx(data).addViolation(imp);
72 break;
73 }
74 }
75 return super.visit(imp, data);
76 }
77
78
79
80
81
82
83
84 private boolean containsPlainJunitAssert(final Node node) {
85 boolean found = false;
86 if (node instanceof ASTStatementExpression
87 && ProhibitPlainJunitAssertionsRule.isPlainJunitAssert(node)) {
88 found = true;
89 }
90 if (!found) {
91 for (int iter = 0; iter < node.jjtGetNumChildren(); iter += 1) {
92 final Node child = node.jjtGetChild(iter);
93 if (this.containsPlainJunitAssert(child)) {
94 found = true;
95 break;
96 }
97 }
98 }
99 return found;
100 }
101
102
103
104
105
106
107 private static boolean isPlainJunitAssert(final Node statement) {
108 final ASTPrimaryExpression expression =
109 ProhibitPlainJunitAssertionsRule.getChildNodeWithType(
110 statement, ASTPrimaryExpression.class
111 );
112 final ASTPrimaryPrefix prefix =
113 ProhibitPlainJunitAssertionsRule.getChildNodeWithType(
114 expression, ASTPrimaryPrefix.class
115 );
116 final ASTName name = ProhibitPlainJunitAssertionsRule
117 .getChildNodeWithType(prefix, ASTName.class);
118 boolean assrt = false;
119 if (name != null) {
120 final String img = name.getImage();
121 assrt = img != null && (img.startsWith("assert")
122 || img.startsWith("Assert.assert"));
123 }
124 return assrt;
125 }
126
127
128
129
130
131
132
133
134 private static <T extends Node> T getChildNodeWithType(final Node node,
135 final Class<T> clazz) {
136 T expression = null;
137 if (node != null && node.jjtGetNumChildren() > 0
138 && clazz.isInstance(node.jjtGetChild(0))) {
139 expression = clazz.cast(node.jjtGetChild(0));
140 }
141 return expression;
142 }
143
144 }