-
Notifications
You must be signed in to change notification settings - Fork 66
/
EclipseTestRunner.java
301 lines (280 loc) · 10.7 KB
/
EclipseTestRunner.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
/*******************************************************************************
* Copyright (c) 2000, 2022 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anthony Dahanne <anthony.dahanne@compuware.com> - enhance ETF to be able to launch several tests in several bundles - https://bugs.eclipse.org/330613
* Lucas Bullen (Red Hat Inc.) - JUnit 5 support
*******************************************************************************/
package org.eclipse.test;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.optional.junitlauncher.TestExecutionContext;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.testing.dumps.TimeoutDumpTimer;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.wiring.BundleWiring;
/**
* A TestRunner for JUnit that supports Ant JUnitResultFormatters and running
* tests inside Eclipse. Example call: EclipseTestRunner -classname
* junit.samples.SimpleTest
* formatter=org.apache.tools.ant.taskdefs.optional.junit
* .XMLJUnitResultFormatter
*/
public class EclipseTestRunner {
/**
* No problems with this test.
*/
public static final int SUCCESS = 0;
/**
* Some tests failed.
*/
public static final int FAILURES = 1;
/**
* An error occured.
*/
public static final int ERRORS = 2;
/**
* The main entry point (the parameters are not yet consistent with the Ant
* JUnitTestRunner, but eventually they should be). Parameters
*
* <pre>
* -className=<testSuiteName>
* -testPluginName<containingpluginName>
* -formatter=<classname>(,<path>)
* </pre>
*
* Where <classname> is the formatter classname, currently ignored as only
* LegacyXmlResultFormatter is used. The path is either the path to the result
* file and should include the file extension (xml) if a single test is being
* run or should be the path to the result directory where result files should
* be created if multiple tests are being run. If no path is given, the standard
* output is used.
*/
public static void main(String[] args) throws IOException {
System.exit(run(args));
}
public static int run(String[] args) throws IOException {
String className = null;
String classesNames = null;
String testPluginName = null;
String testPluginsNames = null;
String resultPathString = null;
String timeoutString = null;
String junitReportOutput = null;
Properties props = new Properties();
int startArgs = 0;
if (args.length > 0) {
// support the JUnit task commandline syntax where
// the first argument is the name of the test class
if (!args[0].startsWith("-")) {
className = args[0];
startArgs++;
}
}
for (int i = startArgs; i < args.length; i++) {
if (args[i].toLowerCase().equals("-classname")) {
if (i < args.length - 1) {
className = args[i + 1];
}
i++;
} else if (args[i].toLowerCase().equals("-classesnames")) {
if (i < args.length - 1) {
classesNames = args[i + 1];
}
i++;
} else if (args[i].toLowerCase().equals("-testpluginname")) {
if (i < args.length - 1) {
testPluginName = args[i + 1];
}
i++;
} else if (args[i].toLowerCase().equals("-testpluginsnames")) {
if (i < args.length - 1) {
testPluginsNames = args[i + 1];
}
i++;
} else if (args[i].equals("-junitReportOutput")) {
if (i < args.length - 1) {
junitReportOutput = args[i + 1];
}
i++;
} else if (args[i].startsWith("haltOnError=")) {
System.err.println("The haltOnError option is no longer supported");
} else if (args[i].startsWith("haltOnFailure=")) {
System.err.println("The haltOnFailure option is no longer supported");
} else if (args[i].startsWith("formatter=")) {
String formatterString = args[i].substring(10);
int seperatorIndex = formatterString.indexOf(',');
resultPathString = seperatorIndex == -1 ? null : formatterString.substring(seperatorIndex + 1);
} else if (args[i].startsWith("propsfile=")) {
try (FileInputStream in = new FileInputStream(args[i].substring(10))) {
props.load(in);
}
} else if (args[i].equals("-testlistener")) {
System.err.println("The testlistener option is no longer supported");
} else if (args[i].equals("-timeout")) {
if (i < args.length - 1) {
timeoutString = args[i + 1];
}
i++;
}
}
// Add/overlay system properties on the properties from the Ant project
props.putAll(System.getProperties());
if (timeoutString == null || timeoutString.isEmpty()) {
System.err.println("INFO: optional timeout was not specified.");
} else {
String timeoutScreenOutputDir = null;
if (junitReportOutput == null || junitReportOutput.isEmpty()) {
timeoutScreenOutputDir = "timeoutScreens";
} else {
timeoutScreenOutputDir = junitReportOutput + "/timeoutScreens";
}
System.err.println("INFO: timeoutScreenOutputDir: " + timeoutScreenOutputDir);
System.err.println("INFO: timeout: " + timeoutString);
startStackDumpTimeoutTimer(timeoutString, new File(timeoutScreenOutputDir));
}
if (testPluginsNames != null && classesNames != null) {
// we have several plugins to look tests for, let's parse their
// names
String[] testPlugins = testPluginsNames.split(",");
String[] suiteClasses = classesNames.split(",");
int returnCode = 0;
int j = 0;
for (String oneClassName : suiteClasses) {
int result = runTests(props, testPlugins[j], oneClassName, resultPathString, true);
j++;
if (result != 0) {
returnCode = result;
}
}
return returnCode;
}
if (className == null) {
throw new IllegalArgumentException("Test class name not specified");
}
return runTests(props, testPluginName, className, resultPathString, false);
}
private static int runTests(Properties props, String testPluginName, String testClassName, String resultPath,
boolean multiTest) {
Thread thisThread = Thread.currentThread();
ClassLoader currentTCCL = thisThread.getContextClassLoader();
if (testPluginName == null) {
testPluginName = ClassLoaderTools.getClassPlugin(testClassName);
}
if (testPluginName == null) {
throw new IllegalArgumentException("Test class not found");
}
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
.selectors(selectClass(testClassName)).build();
AtomicBoolean executionFailed = new AtomicBoolean(false);
try {
thisThread.setContextClassLoader(ClassLoaderTools.getJUnit5Classloader(getPlatformEngines()));
Launcher launcher = LauncherFactory.create(); // DO NOT MOVE! Uses the just set context-classloader
thisThread.setContextClassLoader(ClassLoaderTools.getPluginClassLoader(testPluginName, currentTCCL));
try (LegacyXmlResultFormatter formatter = new LegacyXmlResultFormatter()) {
try (OutputStream out = getResultOutputStream(resultPath, testClassName, multiTest)) {
formatter.setDestination(out);
formatter.setContext(createExecutionContext(props));
launcher.execute(request, formatter, createExecutionListener(executionFailed));
}
} catch (IOException e) {
e.printStackTrace();
return ERRORS;
}
} finally {
thisThread.setContextClassLoader(currentTCCL);
}
return executionFailed.get() ? FAILURES : SUCCESS;
}
private static OutputStream getResultOutputStream(String resultPathString, String testClassName, boolean multiTest)
throws IOException {
if (resultPathString == null || resultPathString.isEmpty()) {
return System.out;
}
Path resultFile = Path.of(resultPathString);
if (multiTest) {
resultFile = resultFile.resolve("TEST-" + testClassName + ".xml");
} else {
if (Files.isDirectory(resultFile)) {
resultFile = resultFile.resolve("TEST-" + testClassName + ".xml");
}
}
Files.createDirectories(resultFile.getParent());
return Files.newOutputStream(resultFile);
}
private static List<String> getPlatformEngines() {
BundleContext context = FrameworkUtil.getBundle(EclipseTestRunner.class).getBundleContext();
return Arrays.stream(context.getBundles()).filter(bundle -> {
try {
BundleWiring bundleWiring = Platform.getBundle(bundle.getSymbolicName()).adapt(BundleWiring.class);
Collection<String> listResources = bundleWiring.listResources("META-INF/services",
"org.junit.platform.engine.TestEngine", BundleWiring.LISTRESOURCES_LOCAL);
return !listResources.isEmpty();
} catch (Exception e) {
return false; // assume absent
}
}).map(Bundle::getSymbolicName).collect(Collectors.toList());
}
private static TestExecutionListener createExecutionListener(AtomicBoolean executionFailed) {
return new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult executionResult) {
if (executionResult.getStatus() == org.junit.platform.engine.TestExecutionResult.Status.FAILED) {
executionFailed.set(true);
}
}
};
}
private static TestExecutionContext createExecutionContext(Properties props) {
return new TestExecutionContext() {
@Override
public Properties getProperties() {
return props;
}
@Override
public Optional<Project> getProject() {
return Optional.empty();
}
};
}
/**
* Starts a timer that dumps interesting debugging information shortly before
* the given timeout expires.
*
* @param timeoutArg the -timeout argument from the command line
* @param outputDirectory where the test results end up
*/
private static void startStackDumpTimeoutTimer(final String timeoutArg, final File outputDirectory) {
TimeoutDumpTimer.startTimeoutDumpTimer(timeoutArg, outputDirectory);
}
}