-
Notifications
You must be signed in to change notification settings - Fork 728
/
CompilationTestHelper.java
373 lines (348 loc) · 13.9 KB
/
CompilationTestHelper.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
/*
* Copyright 2012 The Error Prone 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
*
* 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 com.google.errorprone;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.errorprone.BugCheckerInfo.canonicalName;
import static com.google.errorprone.FileObjects.forResource;
import static com.google.errorprone.FileObjects.forSourceLines;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import com.google.errorprone.DiagnosticTestHelper.LookForCheckNameInDiagnostic;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.main.Main.Result;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import javax.annotation.Nullable;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
/** Helps test Error Prone bug checkers and compilations. */
@CheckReturnValue
public class CompilationTestHelper {
private static final ImmutableList<String> DEFAULT_ARGS =
ImmutableList.of(
"-encoding",
"UTF-8",
// print stack traces for completion failures
"-XDdev",
"-parameters",
"-XDcompilePolicy=simple",
// Don't limit errors/warnings for tests to the default of 100
"-Xmaxerrs",
"500",
"-Xmaxwarns",
"500");
private final DiagnosticTestHelper diagnosticHelper;
private final BaseErrorProneJavaCompiler compiler;
private final ByteArrayOutputStream outputStream;
private final Class<?> clazz;
private final List<JavaFileObject> sources = new ArrayList<>();
private ImmutableList<String> extraArgs = ImmutableList.of();
@Nullable private ImmutableList<Class<?>> overrideClasspath;
private boolean expectNoDiagnostics = false;
private Optional<Result> expectedResult = Optional.empty();
private LookForCheckNameInDiagnostic lookForCheckNameInDiagnostic =
LookForCheckNameInDiagnostic.YES;
private boolean run = false;
private CompilationTestHelper(ScannerSupplier scannerSupplier, String checkName, Class<?> clazz) {
this.clazz = clazz;
this.diagnosticHelper = new DiagnosticTestHelper(checkName);
this.outputStream = new ByteArrayOutputStream();
this.compiler = new BaseErrorProneJavaCompiler(JavacTool.create(), scannerSupplier);
}
/**
* Returns a new {@link CompilationTestHelper}.
*
* @param scannerSupplier the {@link ScannerSupplier} to test
* @param clazz the class to use to locate file resources
*/
public static CompilationTestHelper newInstance(ScannerSupplier scannerSupplier, Class<?> clazz) {
return new CompilationTestHelper(scannerSupplier, null, clazz);
}
/**
* Returns a new {@link CompilationTestHelper}.
*
* @param checker the {@link BugChecker} to test
* @param clazz the class to use to locate file resources
*/
public static CompilationTestHelper newInstance(
Class<? extends BugChecker> checker, Class<?> clazz) {
ScannerSupplier scannerSupplier = ScannerSupplier.fromBugCheckerClasses(checker);
String checkName =
canonicalName(checker.getSimpleName(), checker.getAnnotation(BugPattern.class));
return new CompilationTestHelper(scannerSupplier, checkName, clazz);
}
/**
* Pass -proc:none unless annotation processing is explicitly enabled, to avoid picking up
* annotation processors via service loading.
*/
// TODO(cushon): test compilations should be isolated so they can't pick things up from the
// ambient classpath.
static List<String> disableImplicitProcessing(List<String> args) {
if (args.contains("-processor") || args.contains("-processorpath")) {
return args;
}
return ImmutableList.<String>builder().addAll(args).add("-proc:none").build();
}
/**
* Creates a list of arguments to pass to the compiler. Uses DEFAULT_ARGS as the base and appends
* the overridden classpath, if provided, and any extraArgs that were provided.
*/
private static ImmutableList<String> buildArguments(
@Nullable List<Class<?>> overrideClasspath, List<String> extraArgs) {
ImmutableList.Builder<String> result = ImmutableList.<String>builder().addAll(DEFAULT_ARGS);
getOverrideClasspath(overrideClasspath)
.ifPresent((Path jar) -> result.add("-cp").add(jar.toString()));
return result.addAll(disableImplicitProcessing(extraArgs)).build();
}
private static Optional<Path> getOverrideClasspath(@Nullable List<Class<?>> overrideClasspath) {
if (overrideClasspath == null) {
return Optional.empty();
}
try {
Path tempJarFile = Files.createTempFile(/* prefix= */ null, /* suffix= */ ".jar");
try (OutputStream os = Files.newOutputStream(tempJarFile);
JarOutputStream jos = new JarOutputStream(os)) {
for (Class<?> clazz : overrideClasspath) {
String entryPath = clazz.getName().replace('.', '/') + ".class";
jos.putNextEntry(new JarEntry(entryPath));
try (InputStream is = clazz.getClassLoader().getResourceAsStream(entryPath)) {
ByteStreams.copy(is, jos);
}
}
}
return Optional.of(tempJarFile);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* Adds a source file to the test compilation, from the string content of the file.
*
* <p>The diagnostics expected from compiling the file are inferred from the file contents. For
* each line of the test file that contains the bug marker pattern "// BUG: Diagnostic contains:
* foo", we expect to see a diagnostic on that line containing "foo". For each line of the test
* file that does <i>not</i> contain the bug marker pattern, we expect no diagnostic to be
* generated. You can also use "// BUG: Diagnostic matches: X" in tandem with {@code
* expectErrorMessage("X", "foo")} to allow you to programmatically construct the error message.
*
* @param path a path for the source file
* @param lines the content of the source file
*/
// TODO(eaftan): We could eliminate this path parameter and just infer the path from the
// package and class name
@CanIgnoreReturnValue
public CompilationTestHelper addSourceLines(String path, String... lines) {
this.sources.add(forSourceLines(path, lines));
return this;
}
/**
* Adds a source file to the test compilation, from an existing resource file.
*
* <p>See {@link #addSourceLines} for how expected diagnostics should be specified.
*
* @param path the path to the source file
*/
@CanIgnoreReturnValue
public CompilationTestHelper addSourceFile(String path) {
this.sources.add(forResource(clazz, path));
return this;
}
/**
* Sets the classpath for the test compilation, overriding the default of using the runtime
* classpath of the test execution. This is useful to verify correct behavior when the classpath
* is incomplete.
*
* @param classes the class(es) to use as the classpath
*/
@CanIgnoreReturnValue
public CompilationTestHelper withClasspath(Class<?>... classes) {
this.overrideClasspath = ImmutableList.copyOf(classes);
return this;
}
@CanIgnoreReturnValue
public CompilationTestHelper addModules(String... modules) {
return setArgs(
stream(modules)
.map(m -> String.format("--add-exports=%s=ALL-UNNAMED", m))
.collect(toImmutableList()));
}
/**
* Sets custom command-line arguments for the compilation. These will be appended to the default
* compilation arguments.
*/
@CanIgnoreReturnValue
public CompilationTestHelper setArgs(String... args) {
return setArgs(asList(args));
}
/**
* Sets custom command-line arguments for the compilation. These will be appended to the default
* compilation arguments.
*/
@CanIgnoreReturnValue
public CompilationTestHelper setArgs(List<String> args) {
checkState(
extraArgs.isEmpty(),
"Extra args already set: old value: %s, new value: %s",
extraArgs,
args);
this.extraArgs = ImmutableList.copyOf(args);
return this;
}
/**
* Tells the compilation helper to expect that no diagnostics will be generated, even if the
* source file contains bug markers. Useful for testing that a check is actually disabled when the
* proper command-line argument is passed.
*/
@CanIgnoreReturnValue
public CompilationTestHelper expectNoDiagnostics() {
this.expectNoDiagnostics = true;
return this;
}
/**
* By default, the compilation helper will only inspect diagnostics generated by the check being
* tested. This behaviour can be disabled to test the interaction between Error Prone checks and
* javac diagnostics.
*/
@CanIgnoreReturnValue
public CompilationTestHelper matchAllDiagnostics() {
this.lookForCheckNameInDiagnostic = LookForCheckNameInDiagnostic.NO;
return this;
}
/**
* Tells the compilation helper to expect a specific result from the compilation, e.g. success or
* failure.
*/
@CanIgnoreReturnValue
public CompilationTestHelper expectResult(Result result) {
expectedResult = Optional.of(result);
return this;
}
/**
* Expects an error message matching {@code matcher} at the line below a comment matching the key.
* For example, given the source
*
* <pre>
* // BUG: Diagnostic matches: X
* a = b + c;
* </pre>
*
* ... you can use {@code expectErrorMessage("X", Predicates.containsPattern("Can't add b to
* c"));}
*
* <p>Error message keys that don't match any diagnostics will cause test to fail.
*/
@CanIgnoreReturnValue
public CompilationTestHelper expectErrorMessage(String key, Predicate<? super String> matcher) {
diagnosticHelper.expectErrorMessage(key, matcher);
return this;
}
/** Performs a compilation and checks that the diagnostics and result match the expectations. */
public void doTest() {
checkState(!sources.isEmpty(), "No source files to compile");
checkState(!run, "doTest should only be called once");
this.run = true;
Result result = compile();
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticHelper.getDiagnostics()) {
if (diagnostic.getCode().contains("error.prone.crash")) {
fail(diagnostic.getMessage(Locale.ENGLISH));
}
}
if (expectNoDiagnostics) {
List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticHelper.getDiagnostics();
assertWithMessage(
String.format(
"Expected no diagnostics produced, but found %d: %s",
diagnostics.size(), diagnostics))
.that(diagnostics.size())
.isEqualTo(0);
assertWithMessage(
String.format(
"Expected compilation result to be "
+ expectedResult.orElse(Result.OK)
+ ", but was %s. No diagnostics were emitted."
+ " OutputStream from Compiler follows.\n\n%s",
result,
outputStream))
.that(result)
.isEqualTo(expectedResult.orElse(Result.OK));
} else {
for (JavaFileObject source : sources) {
try {
diagnosticHelper.assertHasDiagnosticOnAllMatchingLines(
source, lookForCheckNameInDiagnostic);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
assertWithMessage("Unused error keys: " + diagnosticHelper.getUnusedLookupKeys())
.that(diagnosticHelper.getUnusedLookupKeys().isEmpty())
.isTrue();
}
expectedResult.ifPresent(
expected ->
assertWithMessage(
String.format(
"Expected compilation result %s, but was %s\n%s\n%s",
expected,
result,
Joiner.on('\n').join(diagnosticHelper.getDiagnostics()),
outputStream))
.that(result)
.isEqualTo(expected));
}
private Result compile() {
List<String> processedArgs = buildArguments(overrideClasspath, extraArgs);
return compiler
.getTask(
new PrintWriter(
new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8)),
/* autoFlush= */ true),
FileManagers.testFileManager(),
diagnosticHelper.collector,
/* options= */ ImmutableList.copyOf(processedArgs),
/* classes= */ ImmutableList.of(),
sources)
.call()
? Result.OK
: Result.ERROR;
}
}