-
Notifications
You must be signed in to change notification settings - Fork 37.7k
/
MethodInvocationTests.java
383 lines (320 loc) · 14.4 KB
/
MethodInvocationTests.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
* Copyright 2002-2021 the original author or authors.
*
* 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
*
* https://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.springframework.expression.spel;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionInvocationTargetException;
import org.springframework.expression.MethodExecutor;
import org.springframework.expression.MethodFilter;
import org.springframework.expression.MethodResolver;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testresources.PlaceOfBirth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests invocation of methods.
*
* @author Andy Clement
* @author Phillip Webb
* @author Sam Brannen
*/
public class MethodInvocationTests extends AbstractExpressionTests {
@Test
public void testSimpleAccess01() {
evaluate("getPlaceOfBirth().getCity()", "SmilJan", String.class);
}
@Test
public void testStringClass() {
evaluate("new java.lang.String('hello').charAt(2)", 'l', Character.class);
evaluate("new java.lang.String('hello').charAt(2).equals('l'.charAt(0))", true, Boolean.class);
evaluate("'HELLO'.toLowerCase()", "hello", String.class);
evaluate("' abcba '.trim()", "abcba", String.class);
}
@Test
public void testNonExistentMethods() {
// name is ok but madeup() does not exist
evaluateAndCheckError("name.madeup()", SpelMessage.METHOD_NOT_FOUND, 5);
}
@Test
public void testWidening01() {
// widening of int 3 to double 3 is OK
evaluate("new Double(3.0d).compareTo(8)", -1, Integer.class);
evaluate("new Double(3.0d).compareTo(3)", 0, Integer.class);
evaluate("new Double(3.0d).compareTo(2)", 1, Integer.class);
}
@Test
public void testArgumentConversion01() {
// Rely on Double>String conversion for calling startsWith()
evaluate("new String('hello 2.0 to you').startsWith(7.0d)", false, Boolean.class);
evaluate("new String('7.0 foobar').startsWith(7.0d)", true, Boolean.class);
}
@Test
public void testMethodThrowingException_SPR6760() {
// Test method on inventor: throwException()
// On 1 it will throw an IllegalArgumentException
// On 2 it will throw a RuntimeException
// On 3 it will exit normally
// In each case it increments the Inventor field 'counter' when invoked
SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression("throwException(#bar)");
// Normal exit
StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext();
eContext.setVariable("bar", 3);
Object o = expr.getValue(eContext);
assertThat(o).isEqualTo(3);
assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(1);
// Now the expression has cached that throwException(int) is the right thing to call
// Let's change 'bar' to be a PlaceOfBirth which indicates the cached reference is
// out of date.
eContext.setVariable("bar", new PlaceOfBirth("London"));
o = expr.getValue(eContext);
assertThat(o).isEqualTo("London");
// That confirms the logic to mark the cached reference stale and retry is working
// Now let's cause the method to exit via exception and ensure it doesn't cause a retry.
// First, switch back to throwException(int)
eContext.setVariable("bar", 3);
o = expr.getValue(eContext);
assertThat(o).isEqualTo(3);
assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(2);
// Now cause it to throw an exception:
eContext.setVariable("bar", 1);
assertThatExceptionOfType(Exception.class).isThrownBy(() -> expr.getValue(eContext))
.isNotInstanceOf(SpelEvaluationException.class);
// If counter is 4 then the method got called twice!
assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(3);
eContext.setVariable("bar", 4);
assertThatExceptionOfType(ExpressionInvocationTargetException.class).isThrownBy(() -> expr.getValue(eContext));
// If counter is 5 then the method got called twice!
assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(4);
}
/**
* Check on first usage (when the cachedExecutor in MethodReference is null) that the exception is not wrapped.
*/
@Test
public void testMethodThrowingException_SPR6941() {
// Test method on inventor: throwException()
// On 1 it will throw an IllegalArgumentException
// On 2 it will throw a RuntimeException
// On 3 it will exit normally
// In each case it increments the Inventor field 'counter' when invoked
SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression("throwException(#bar)");
context.setVariable("bar", 2);
assertThatExceptionOfType(Exception.class).isThrownBy(() -> expr.getValue(context))
.satisfies(ex -> assertThat(ex).isNotInstanceOf(SpelEvaluationException.class));
}
@Test
public void testMethodThrowingException_SPR6941_2() {
// Test method on inventor: throwException()
// On 1 it will throw an IllegalArgumentException
// On 2 it will throw a RuntimeException
// On 3 it will exit normally
// In each case it increments the Inventor field 'counter' when invoked
SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression("throwException(#bar)");
context.setVariable("bar", 4);
assertThatExceptionOfType(ExpressionInvocationTargetException.class).isThrownBy(() -> expr.getValue(context))
.satisfies(ex -> assertThat(ex.getCause().getClass().getName()).isEqualTo(
"org.springframework.expression.spel.testresources.Inventor$TestException"));
}
@Test
public void testMethodFiltering_SPR6764() {
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(new TestObject());
LocalFilter filter = new LocalFilter();
context.registerMethodFilter(TestObject.class,filter);
// Filter will be called but not do anything, so first doit() will be invoked
SpelExpression expr = (SpelExpression) parser.parseExpression("doit(1)");
String result = expr.getValue(context, String.class);
assertThat(result).isEqualTo("1");
assertThat(filter.filterCalled).isTrue();
// Filter will now remove non @Anno annotated methods
filter.removeIfNotAnnotated = true;
filter.filterCalled = false;
expr = (SpelExpression) parser.parseExpression("doit(1)");
result = expr.getValue(context, String.class);
assertThat(result).isEqualTo("double 1.0");
assertThat(filter.filterCalled).isTrue();
// check not called for other types
filter.filterCalled = false;
context.setRootObject(new String("abc"));
expr = (SpelExpression) parser.parseExpression("charAt(0)");
result = expr.getValue(context, String.class);
assertThat(result).isEqualTo("a");
assertThat(filter.filterCalled).isFalse();
// check de-registration works
filter.filterCalled = false;
context.registerMethodFilter(TestObject.class,null);//clear filter
context.setRootObject(new TestObject());
expr = (SpelExpression) parser.parseExpression("doit(1)");
result = expr.getValue(context, String.class);
assertThat(result).isEqualTo("1");
assertThat(filter.filterCalled).isFalse();
}
@Test
public void testAddingMethodResolvers() {
StandardEvaluationContext ctx = new StandardEvaluationContext();
// reflective method accessor is the only one by default
List<MethodResolver> methodResolvers = ctx.getMethodResolvers();
assertThat(methodResolvers.size()).isEqualTo(1);
MethodResolver dummy = new DummyMethodResolver();
ctx.addMethodResolver(dummy);
assertThat(ctx.getMethodResolvers().size()).isEqualTo(2);
List<MethodResolver> copy = new ArrayList<>(ctx.getMethodResolvers());
assertThat(ctx.removeMethodResolver(dummy)).isTrue();
assertThat(ctx.removeMethodResolver(dummy)).isFalse();
assertThat(ctx.getMethodResolvers().size()).isEqualTo(1);
ctx.setMethodResolvers(copy);
assertThat(ctx.getMethodResolvers().size()).isEqualTo(2);
}
@Test
public void testVarargsInvocation01() {
// Calling 'public String aVarargsMethod(String... strings)'
evaluate("aVarargsMethod('a','b','c')", "[a, b, c]", String.class);
evaluate("aVarargsMethod('a')", "[a]", String.class);
evaluate("aVarargsMethod()", "[]", String.class);
evaluate("aVarargsMethod(1,2,3)", "[1, 2, 3]", String.class); // all need converting to strings
evaluate("aVarargsMethod(1)", "[1]", String.class); // needs string conversion
evaluate("aVarargsMethod(1,'a',3.0d)", "[1, a, 3.0]", String.class); // first and last need conversion
evaluate("aVarargsMethod(new String[]{'a','b','c'})", "[a, b, c]", String.class);
evaluate("aVarargsMethod(new String[]{})", "[]", String.class);
evaluate("aVarargsMethod(null)", "[null]", String.class);
evaluate("aVarargsMethod(null,'a')", "[null, a]", String.class);
evaluate("aVarargsMethod('a',null,'b')", "[a, null, b]", String.class);
}
@Test
public void testVarargsInvocation02() {
// Calling 'public String aVarargsMethod2(int i, String... strings)'
evaluate("aVarargsMethod2(5,'a','b','c')", "5-[a, b, c]", String.class);
evaluate("aVarargsMethod2(2,'a')", "2-[a]", String.class);
evaluate("aVarargsMethod2(4)", "4-[]", String.class);
evaluate("aVarargsMethod2(8,2,3)", "8-[2, 3]", String.class);
evaluate("aVarargsMethod2(2,'a',3.0d)", "2-[a, 3.0]", String.class);
evaluate("aVarargsMethod2(8,new String[]{'a','b','c'})", "8-[a, b, c]", String.class);
evaluate("aVarargsMethod2(8,new String[]{})", "8-[]", String.class);
evaluate("aVarargsMethod2(8,null)", "8-[null]", String.class);
evaluate("aVarargsMethod2(8,null,'a')", "8-[null, a]", String.class);
evaluate("aVarargsMethod2(8,'a',null,'b')", "8-[a, null, b]", String.class);
}
@Test
public void testVarargsOptionalInvocation() {
// Calling 'public String optionalVarargsMethod(Optional<String>... values)'
evaluate("optionalVarargsMethod()", "[]", String.class);
evaluate("optionalVarargsMethod(new String[0])", "[]", String.class);
evaluate("optionalVarargsMethod('a')", "[Optional[a]]", String.class);
evaluate("optionalVarargsMethod('a','b','c')", "[Optional[a], Optional[b], Optional[c]]", String.class);
evaluate("optionalVarargsMethod(9)", "[Optional[9]]", String.class);
evaluate("optionalVarargsMethod(2,3)", "[Optional[2], Optional[3]]", String.class);
evaluate("optionalVarargsMethod('a',3.0d)", "[Optional[a], Optional[3.0]]", String.class);
evaluate("optionalVarargsMethod(new String[]{'a','b','c'})", "[Optional[a], Optional[b], Optional[c]]", String.class);
// The following should actually evaluate to [Optional.empty] instead of [null],
// but ReflectionHelper.convertArguments() passes the array type instead of
// the array's component type as the target type to the ConversionService, and
// GenericConversionService.convertNullSource() therefore fails to convert null
// to Optional.empty().
evaluate("optionalVarargsMethod(null)", "[null]", String.class);
evaluate("optionalVarargsMethod(null,'a')", "[Optional.empty, Optional[a]]", String.class);
evaluate("optionalVarargsMethod('a',null,'b')", "[Optional[a], Optional.empty, Optional[b]]", String.class);
}
@Test
public void testInvocationOnNullContextObject() {
evaluateAndCheckError("null.toString()",SpelMessage.METHOD_CALL_ON_NULL_OBJECT_NOT_ALLOWED);
}
@Test
public void testMethodOfClass() throws Exception {
Expression expression = parser.parseExpression("getName()");
Object value = expression.getValue(new StandardEvaluationContext(String.class));
assertThat(value).isEqualTo("java.lang.String");
}
@Test
public void invokeMethodWithoutConversion() throws Exception {
final BytesService service = new BytesService();
byte[] bytes = new byte[100];
StandardEvaluationContext context = new StandardEvaluationContext(bytes);
context.setBeanResolver((context1, beanName) -> ("service".equals(beanName) ? service : null));
Expression expression = parser.parseExpression("@service.handleBytes(#root)");
byte[] outBytes = expression.getValue(context, byte[].class);
assertThat(outBytes).isSameAs(bytes);
}
// Simple filter
static class LocalFilter implements MethodFilter {
public boolean removeIfNotAnnotated = false;
public boolean filterCalled = false;
private boolean isAnnotated(Method method) {
Annotation[] anns = method.getAnnotations();
if (anns == null) {
return false;
}
for (Annotation ann : anns) {
String name = ann.annotationType().getName();
if (name.endsWith("Anno")) {
return true;
}
}
return false;
}
@Override
public List<Method> filter(List<Method> methods) {
filterCalled = true;
List<Method> forRemoval = new ArrayList<>();
for (Method method: methods) {
if (removeIfNotAnnotated && !isAnnotated(method)) {
forRemoval.add(method);
}
}
for (Method method: forRemoval) {
methods.remove(method);
}
return methods;
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface Anno {
}
class TestObject {
public int doit(int i) {
return i;
}
@Anno
public String doit(double d) {
return "double "+d;
}
}
static class DummyMethodResolver implements MethodResolver {
@Override
public MethodExecutor resolve(EvaluationContext context, Object targetObject, String name,
List<TypeDescriptor> argumentTypes) throws AccessException {
throw new UnsupportedOperationException();
}
}
public static class BytesService {
public byte[] handleBytes(byte[] bytes) {
return bytes;
}
}
}