/
TestMixinTransformation.java
266 lines (230 loc) · 12 KB
/
TestMixinTransformation.java
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
/*
* Copyright 2011 SpringSource
*
* 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 org.codehaus.groovy.grails.compiler.injection.test;
import grails.test.mixin.TestMixin;
import grails.test.mixin.support.MixinMethod;
import grails.util.GrailsNameUtils;
import groovy.lang.GroovyObjectSupport;
import junit.framework.TestCase;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.messages.SimpleMessage;
import org.codehaus.groovy.grails.compiler.injection.GrailsASTUtils;
import org.codehaus.groovy.grails.compiler.injection.GrailsArtefactClassInjector;
import org.codehaus.groovy.transform.ASTTransformation;
import org.codehaus.groovy.transform.GroovyASTTransformation;
import org.junit.*;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
/**
* An AST transformation to be applied to tests for adding behavior to a target test class.
*
* @author Graeme Rocher
* @since 2.0
*/
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
public class TestMixinTransformation implements ASTTransformation{
public static final AnnotationNode MIXIN_METHOD_ANNOTATION = new AnnotationNode(new ClassNode(MixinMethod.class));
private static final ClassNode MY_TYPE = new ClassNode(TestMixin.class);
private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage();
public static final String OBJECT_CLASS = "java.lang.Object";
public static final String SPEC_CLASS = "spock.lang.Specification";
private static final String JUNIT3_CLASS = "junit.framework.TestCase";
public static final String SET_UP_METHOD = "setUp";
public static final VariableExpression THIS_EXPRESSION = new VariableExpression("this");
public static final String TEAR_DOWN_METHOD = "tearDown";
public static final ClassNode GROOVY_OBJECT_CLASS_NODE = new ClassNode(GroovyObjectSupport.class);
public void visit(ASTNode[] astNodes, SourceUnit source) {
if (!(astNodes[0] instanceof AnnotationNode) || !(astNodes[1] instanceof AnnotatedNode)) {
throw new RuntimeException("Internal error: wrong types: $node.class / $parent.class");
}
AnnotatedNode parent = (AnnotatedNode) astNodes[1];
AnnotationNode node = (AnnotationNode) astNodes[0];
if (!MY_TYPE.equals(node.getClassNode()) || !(parent instanceof ClassNode)) {
return;
}
ClassNode classNode = (ClassNode) parent;
String cName = classNode.getName();
if (classNode.isInterface()) {
throw new RuntimeException("Error processing interface '" + cName + "'. " +
MY_TYPE_NAME + " not allowed for interfaces.");
}
autoAnnotateSetupTeardown(classNode);
ListExpression values = getListOfClasses(node);
weaveMixinsIntoClass(classNode, values);
}
protected ListExpression getListOfClasses(AnnotationNode node) {
Expression value = node.getMember("value");
ListExpression values = null;
if (value instanceof ListExpression) {
values = (ListExpression) value;
}
else if (value instanceof ClassExpression) {
values = new ListExpression();
values.addExpression(value);
}
return values;
}
public void weaveMixinsIntoClass(ClassNode classNode, ListExpression values) {
if (values != null) {
boolean isJunit3 = isJunit3Test(classNode);
List<MethodNode> beforeMethods = null;
List<MethodNode> afterMethods = null;
if (isJunit3) {
beforeMethods = new ArrayList<MethodNode>();
afterMethods = new ArrayList<MethodNode>();
}
for (Expression current : values.getExpressions()) {
if (current instanceof ClassExpression) {
ClassExpression ce = (ClassExpression) current;
ClassNode mixinClassNode = ce.getType();
final String fieldName = '$' + GrailsNameUtils.getPropertyName(mixinClassNode.getName());
FieldNode fieldNode = GrailsASTUtils.addFieldIfNonExistent(classNode, mixinClassNode, fieldName);
if(fieldNode == null) return; // already woven
VariableExpression fieldReference = new VariableExpression(fieldName);
while (!mixinClassNode.getName().equals(OBJECT_CLASS)) {
final List<MethodNode> mixinMethods = mixinClassNode.getMethods();
int beforeClassMethodCount = 0;
int afterClassMethodCount = 0;
for (MethodNode mixinMethod : mixinMethods) {
if (isCandidateMethod(mixinMethod) && !hasDeclaredMethod(classNode, mixinMethod)) {
if (mixinMethod.isStatic()) {
MethodNode methodNode = GrailsASTUtils.addDelegateStaticMethod(classNode, mixinMethod);
if (methodNode != null) {
methodNode.addAnnotation(MIXIN_METHOD_ANNOTATION);
}
}
else {
MethodNode methodNode = GrailsASTUtils.addDelegateInstanceMethod(classNode, fieldReference, mixinMethod, false);
if (methodNode != null) {
methodNode.addAnnotation(MIXIN_METHOD_ANNOTATION);
}
}
if (isJunit3) {
if (hasAnnotation(mixinMethod, Before.class)) {
beforeMethods.add(mixinMethod);
}
if (hasAnnotation(mixinMethod, BeforeClass.class)) {
beforeMethods.add(beforeClassMethodCount++, mixinMethod);
}
if (hasAnnotation(mixinMethod, After.class)) {
afterMethods.add(mixinMethod);
}
if (hasAnnotation(mixinMethod, AfterClass.class)) {
afterMethods.add(afterClassMethodCount++, mixinMethod);
}
}
}
}
mixinClassNode = mixinClassNode.getSuperClass();
}
}
}
if (isJunit3) {
addMethodCallsToMethod(classNode, SET_UP_METHOD, beforeMethods);
addMethodCallsToMethod(classNode, TEAR_DOWN_METHOD, afterMethods);
}
}
}
protected boolean hasDeclaredMethod(ClassNode classNode, MethodNode mixinMethod) {
return classNode.hasDeclaredMethod(mixinMethod.getName(), mixinMethod.getParameters());
}
protected boolean hasAnnotation(MethodNode mixinMethod, Class<?> beforeClass) {
return !mixinMethod.getAnnotations(new ClassNode(beforeClass)).isEmpty();
}
protected void addMethodCallsToMethod(ClassNode classNode, String name, List<MethodNode> methods) {
if (methods != null && !methods.isEmpty()) {
BlockStatement setupMethodBody = getOrCreateNoArgsMethodBody(classNode, name);
for (MethodNode beforeMethod : methods) {
setupMethodBody.addStatement(new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, beforeMethod.getName(), GrailsArtefactClassInjector.ZERO_ARGS)));
}
}
}
protected BlockStatement getOrCreateNoArgsMethodBody(ClassNode classNode, String name) {
MethodNode setupMethod = classNode.getMethod(name, GrailsArtefactClassInjector.ZERO_PARAMETERS);
return getOrCreateMethodBody(classNode, setupMethod, name);
}
protected BlockStatement getOrCreateMethodBody(ClassNode classNode, MethodNode setupMethod, String name) {
BlockStatement methodBody;
if (setupMethod.getDeclaringClass().getName().equals(TestCase.class.getName())) {
methodBody = new BlockStatement();
setupMethod = new MethodNode(name, Modifier.PUBLIC,setupMethod.getReturnType(), GrailsArtefactClassInjector.ZERO_PARAMETERS,null, methodBody);
classNode.addMethod(setupMethod);
}
else {
final Statement setupMethodBody = setupMethod.getCode();
if (!(setupMethodBody instanceof BlockStatement)) {
methodBody = new BlockStatement();
if (setupMethodBody != null) {
if (!(setupMethodBody instanceof ReturnStatement)) {
methodBody.addStatement(setupMethodBody);
}
}
setupMethod.setCode(methodBody);
}
else {
methodBody = (BlockStatement) setupMethodBody;
}
}
return methodBody;
}
public static boolean isJunit3Test(ClassNode classNode) {
return isSubclassOf(classNode, JUNIT3_CLASS);
}
public static boolean isSpockTest(ClassNode classNode) {
return isSubclassOf(classNode, SPEC_CLASS);
}
private static boolean isSubclassOf(ClassNode classNode, String testType) {
ClassNode currentSuper = classNode.getSuperClass();
while (currentSuper != null && !currentSuper.getName().equals(OBJECT_CLASS)) {
if (currentSuper.getName().equals(testType)) return true;
currentSuper = currentSuper.getSuperClass();
}
return false;
}
protected boolean isCandidateMethod(MethodNode declaredMethod) {
return isAddableMethod(declaredMethod);
}
public static boolean isAddableMethod(MethodNode declaredMethod) {
ClassNode groovyMethods = GROOVY_OBJECT_CLASS_NODE;
String methodName = declaredMethod.getName();
return !declaredMethod.isSynthetic() &&
!methodName.contains("$") &&
Modifier.isPublic(declaredMethod.getModifiers()) &&
!Modifier.isAbstract(declaredMethod.getModifiers()) &&
!groovyMethods.hasMethod(declaredMethod.getName(), declaredMethod.getParameters());
}
protected void error(SourceUnit source, String me) {
source.getErrorCollector().addError(new SimpleMessage(me,source), true);
}
protected void autoAnnotateSetupTeardown(ClassNode classNode) {
MethodNode setupMethod = classNode.getMethod(SET_UP_METHOD, GrailsArtefactClassInjector.ZERO_PARAMETERS);
if ( setupMethod != null && setupMethod.getAnnotations(TestForTransformation.BEFORE_CLASS_NODE).size() == 0) {
setupMethod.addAnnotation(TestForTransformation.BEFORE_ANNOTATION);
}
MethodNode tearDown = classNode.getMethod(TEAR_DOWN_METHOD, GrailsArtefactClassInjector.ZERO_PARAMETERS);
if ( tearDown != null && tearDown.getAnnotations(TestForTransformation.AFTER_CLASS_NODE).size() == 0) {
tearDown.addAnnotation(TestForTransformation.AFTER_ANNOTATION);
}
}
}