-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
MethodArgumentsProvider.java
207 lines (175 loc) · 8.43 KB
/
MethodArgumentsProvider.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
/*
* Copyright 2015-2023 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/
package org.junit.jupiter.params.provider;
import static java.lang.String.format;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated;
import static org.junit.platform.commons.util.CollectionUtils.isConvertibleToStream;
import java.lang.reflect.Method;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.support.AnnotationConsumer;
import org.junit.platform.commons.JUnitException;
import org.junit.platform.commons.PreconditionViolationException;
import org.junit.platform.commons.util.CollectionUtils;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.util.StringUtils;
/**
* @since 5.0
*/
class MethodArgumentsProvider implements ArgumentsProvider, AnnotationConsumer<MethodSource> {
private String[] methodNames;
private static final Predicate<Method> isFactoryMethod = //
method -> isConvertibleToStream(method.getReturnType()) && !isTestMethod(method);
@Override
public void accept(MethodSource annotation) {
this.methodNames = annotation.value();
}
@Override
public Stream<Arguments> provideArguments(ExtensionContext context) {
Class<?> testClass = context.getRequiredTestClass();
Method testMethod = context.getRequiredTestMethod();
Object testInstance = context.getTestInstance().orElse(null);
// @formatter:off
return stream(this.methodNames)
.map(factoryMethodName -> findFactoryMethod(testClass, testMethod, factoryMethodName))
.map(factoryMethod -> context.getExecutableInvoker().invoke(factoryMethod, testInstance))
.flatMap(CollectionUtils::toStream)
.map(MethodArgumentsProvider::toArguments);
// @formatter:on
}
private static Method findFactoryMethod(Class<?> testClass, Method testMethod, String factoryMethodName) {
String originalFactoryMethodName = factoryMethodName;
// If the user did not provide a factory method name, find a "default" local
// factory method with the same name as the parameterized test method.
if (StringUtils.isBlank(factoryMethodName)) {
factoryMethodName = testMethod.getName();
return findFactoryMethodBySimpleName(testClass, testMethod, factoryMethodName);
}
// Convert local factory method name to fully-qualified method name.
if (!looksLikeAFullyQualifiedMethodName(factoryMethodName)) {
factoryMethodName = testClass.getName() + "#" + factoryMethodName;
}
// Find factory method using fully-qualified name.
Method factoryMethod = findFactoryMethodByFullyQualifiedName(testMethod, factoryMethodName);
// Ensure factory method has a valid return type and is not a test method.
Preconditions.condition(isFactoryMethod.test(factoryMethod), () -> format(
"Could not find valid factory method [%s] for test class [%s] but found the following invalid candidate: %s",
originalFactoryMethodName, testClass.getName(), factoryMethod));
return factoryMethod;
}
private static boolean looksLikeAFullyQualifiedMethodName(String factoryMethodName) {
if (factoryMethodName.contains("#")) {
return true;
}
int indexOfDot = factoryMethodName.indexOf(".");
if (indexOfDot == -1) {
return false;
}
int indexOfOpeningParenthesis = factoryMethodName.indexOf("(");
if (indexOfOpeningParenthesis > 0) {
// Exclude simple method names with parameters
return indexOfDot < indexOfOpeningParenthesis;
}
// If we get this far, we conclude the supplied factory method name "looks"
// like it was intended to be a fully-qualified method name, even if the
// syntax is invalid. We do this in order to provide better diagnostics for
// the user when a fully-qualified method name is in fact invalid.
return true;
}
private static Method findFactoryMethodByFullyQualifiedName(Method testMethod, String fullyQualifiedMethodName) {
String[] methodParts = ReflectionUtils.parseFullyQualifiedMethodName(fullyQualifiedMethodName);
String className = methodParts[0];
String methodName = methodParts[1];
String methodParameters = methodParts[2];
Class<?> clazz = loadRequiredClass(className);
// Attempt to find an exact match first.
Method factoryMethod = ReflectionUtils.findMethod(clazz, methodName, methodParameters).orElse(null);
if (factoryMethod != null) {
return factoryMethod;
}
boolean explicitParameterListSpecified = //
StringUtils.isNotBlank(methodParameters) || fullyQualifiedMethodName.endsWith("()");
// If we didn't find an exact match but an explicit parameter list was specified,
// that's a user configuration error.
Preconditions.condition(!explicitParameterListSpecified,
() -> format("Could not find factory method [%s(%s)] in class [%s]", methodName, methodParameters,
className));
// Otherwise, fall back to the same lenient search semantics that are used
// to locate a "default" local factory method.
return findFactoryMethodBySimpleName(clazz, testMethod, methodName);
}
/**
* Find the factory method by searching for all methods in the given {@code clazz}
* with the desired {@code factoryMethodName} which have return types that can be
* converted to a {@link Stream}, ignoring the {@code testMethod} itself as well
* as any {@code @Test}, {@code @TestTemplate}, or {@code @TestFactory} methods
* with the same name.
* @return the single factory method matching the search criteria
* @throws PreconditionViolationException if the factory method was not found or
* multiple competing factory methods with the same name were found
*/
private static Method findFactoryMethodBySimpleName(Class<?> clazz, Method testMethod, String factoryMethodName) {
Predicate<Method> isCandidate = candidate -> factoryMethodName.equals(candidate.getName())
&& !testMethod.equals(candidate);
List<Method> candidates = ReflectionUtils.findMethods(clazz, isCandidate);
List<Method> factoryMethods = candidates.stream().filter(isFactoryMethod).collect(toList());
Preconditions.condition(factoryMethods.size() > 0, () -> {
// If we didn't find the factory method using the isFactoryMethod Predicate, perhaps
// the specified factory method has an invalid return type or is a test method.
// In that case, we report the invalid candidates that were found.
if (candidates.size() > 0) {
return format(
"Could not find valid factory method [%s] in class [%s] but found the following invalid candidates: %s",
factoryMethodName, clazz.getName(), candidates);
}
// Otherwise, report that we didn't find anything.
return format("Could not find factory method [%s] in class [%s]", factoryMethodName, clazz.getName());
});
Preconditions.condition(factoryMethods.size() == 1,
() -> format("%d factory methods named [%s] were found in class [%s]: %s", factoryMethods.size(),
factoryMethodName, clazz.getName(), factoryMethods));
return factoryMethods.get(0);
}
private static boolean isTestMethod(Method candidate) {
return isAnnotated(candidate, Test.class) || isAnnotated(candidate, TestTemplate.class)
|| isAnnotated(candidate, TestFactory.class);
}
private static Class<?> loadRequiredClass(String className) {
return ReflectionUtils.tryToLoadClass(className).getOrThrow(
cause -> new JUnitException(format("Could not load class [%s]", className), cause));
}
private static Arguments toArguments(Object item) {
// Nothing to do except cast.
if (item instanceof Arguments) {
return (Arguments) item;
}
// Pass all multidimensional arrays "as is", in contrast to Object[].
// See https://github.com/junit-team/junit5/issues/1665
if (ReflectionUtils.isMultidimensionalArray(item)) {
return arguments(item);
}
// Special treatment for one-dimensional reference arrays.
// See https://github.com/junit-team/junit5/issues/1665
if (item instanceof Object[]) {
return arguments((Object[]) item);
}
// Pass everything else "as is".
return arguments(item);
}
}