Search in sources :

Example 6 with Diagnostic

use of javax.tools.Diagnostic in project auto by google.

the class AutoAnnotationCompilationTest method doTestMissingClass.

private void doTestMissingClass(File tempDir) {
    // Test that referring to an undefined annotation does not trigger @AutoAnnotation processing.
    // The class Erroneous references an undefined annotation @NotAutoAnnotation. If we didn't have
    // any special treatment of undefined types then we could run into a compiler bug where
    // AutoAnnotationProcessor would think that a method annotated with @NotAutoAnnotation was in
    // fact annotated with @AutoAnnotation. As it is, we do get an error about @NotAutoAnnotation
    // being undefined, and we do not get an error complaining that this supposed @AutoAnnotation
    // method is not static. We do need to have @AutoAnnotation appear somewhere so that the
    // processor will run.
    JavaFileObject erroneousJavaFileObject = JavaFileObjects.forSourceLines("com.example.annotations.Erroneous", "package com.example.annotations;", "", "import com.google.auto.value.AutoAnnotation;", "", "public class Erroneous {", "  @interface Empty {}", "  @AutoAnnotation static Empty newEmpty() {}", "  @NotAutoAnnotation Empty notNewEmpty() {}", "}");
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    JavaCompiler.CompilationTask compilationTask = javaCompiler.getTask((Writer) null, (JavaFileManager) null, diagnosticCollector, ImmutableList.of("-d", tempDir.toString()), (Iterable<String>) null, ImmutableList.of(erroneousJavaFileObject));
    compilationTask.setProcessors(ImmutableList.of(new AutoAnnotationProcessor()));
    boolean result = compilationTask.call();
    assertThat(result).isFalse();
    List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticCollector.getDiagnostics();
    assertThat(diagnostics).isNotEmpty();
    assertThat(diagnostics.get(0).getMessage(null)).contains("NotAutoAnnotation");
    assertThat(diagnostics.get(0).getMessage(null)).doesNotContain("static");
}
Also used : JavaFileObject(javax.tools.JavaFileObject) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 7 with Diagnostic

use of javax.tools.Diagnostic in project error-prone by google.

the class CompilationTestHelper method doTest.

/**
   * Performs a compilation and checks that the diagnostics and result match the expectations.
   */
// TODO(eaftan): any way to ensure that this is actually called?
public void doTest() {
    Preconditions.checkState(!sources.isEmpty(), "No source files to compile");
    List<String> allArgs = buildArguments(args);
    Result result = compile(sources, allArgs.toArray(new String[allArgs.size()]));
    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);
    } else {
        for (JavaFileObject source : sources) {
            try {
                diagnosticHelper.assertHasDiagnosticOnAllMatchingLines(source, lookForCheckNameInDiagnostic);
            } catch (IOException e) {
                throw new IOError(e);
            }
        }
        assertTrue("Unused error keys: " + diagnosticHelper.getUnusedLookupKeys(), diagnosticHelper.getUnusedLookupKeys().isEmpty());
    }
    if (expectedResult.isPresent()) {
        assertWithMessage(String.format("Expected compilation result %s, but was %s", expectedResult.get(), result)).that(result).isEqualTo(expectedResult.get());
    }
}
Also used : JavaFileObject(javax.tools.JavaFileObject) IOError(java.io.IOError) LookForCheckNameInDiagnostic(com.google.errorprone.DiagnosticTestHelper.LookForCheckNameInDiagnostic) Diagnostic(javax.tools.Diagnostic) IOException(java.io.IOException) Result(com.sun.tools.javac.main.Main.Result)

Example 8 with Diagnostic

use of javax.tools.Diagnostic in project error-prone by google.

the class ErrorProneCompilerIntegrationTest method maturityIsResetOnNextCompilation.

@Test
public void maturityIsResetOnNextCompilation() throws Exception {
    String[] testFile = { "public class Test {", "  public Test() {", "    if (true);", "  }", "}" };
    String[] args = { "-Xep:EmptyIf" };
    Result exitCode = compiler.compile(args, Arrays.asList(compiler.fileManager().forSourceLines("Test.java", testFile)));
    outputStream.flush();
    Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher = hasItem(diagnosticMessage(containsString("[EmptyIf]")));
    assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
    assertTrue("Error should be found. " + diagnosticHelper.describe(), matcher.matches(diagnosticHelper.getDiagnostics()));
    diagnosticHelper.clearDiagnostics();
    exitCode = compiler.compile(Arrays.asList(compiler.fileManager().forSourceLines("Test.java", testFile)));
    outputStream.flush();
    assertThat(outputStream.toString(), exitCode, is(Result.OK));
    assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Diagnostic(javax.tools.Diagnostic) Matchers.containsString(org.hamcrest.Matchers.containsString) Result(com.sun.tools.javac.main.Main.Result) Test(org.junit.Test)

Example 9 with Diagnostic

use of javax.tools.Diagnostic in project error-prone by google.

the class ErrorProneJavacPluginTest method hello.

@Test
public void hello() throws IOException {
    FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
    Path source = fileSystem.getPath("Test.java");
    Files.write(source, ImmutableList.of("import java.util.HashSet;", "import java.util.Set;", "class Test {", "  public static void main(String[] args) {", "    Set<Short> s = new HashSet<>();", "    for (short i = 0; i < 100; i++) {", "      s.add(i);", "      s.remove(i - 1);", "    }", "    System.out.println(s.size());", "  }", "}"), UTF_8);
    JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    JavacTask task = JavacTool.create().getTask(null, fileManager, diagnosticCollector, ImmutableList.of("-Xplugin:ErrorProne"), ImmutableList.of(), fileManager.getJavaFileObjects(source));
    assertThat(task.call()).isFalse();
    Diagnostic<? extends JavaFileObject> diagnostic = diagnosticCollector.getDiagnostics().stream().filter(d -> d.getKind() == Diagnostic.Kind.ERROR).collect(onlyElement());
    assertThat(diagnostic.getMessage(ENGLISH)).contains("[CollectionIncompatibleType]");
}
Also used : Path(java.nio.file.Path) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) Context(com.sun.tools.javac.util.Context) Configuration(com.google.common.jimfs.Configuration) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) JavacTask(com.sun.source.util.JavacTask) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) RunWith(org.junit.runner.RunWith) IOException(java.io.IOException) Test(org.junit.Test) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) FileSystem(java.nio.file.FileSystem) MoreCollectors.onlyElement(com.google.common.collect.MoreCollectors.onlyElement) JavaFileObject(javax.tools.JavaFileObject) ImmutableList(com.google.common.collect.ImmutableList) JavacTool(com.sun.tools.javac.api.JavacTool) Jimfs(com.google.common.jimfs.Jimfs) Diagnostic(javax.tools.Diagnostic) Context(com.sun.tools.javac.util.Context) ENGLISH(java.util.Locale.ENGLISH) Path(java.nio.file.Path) DiagnosticCollector(javax.tools.DiagnosticCollector) JavaFileObject(javax.tools.JavaFileObject) FileSystem(java.nio.file.FileSystem) DiagnosticCollector(javax.tools.DiagnosticCollector) JavacTask(com.sun.source.util.JavacTask) Test(org.junit.Test)

Example 10 with Diagnostic

use of javax.tools.Diagnostic in project error-prone by google.

the class ErrorProneCompilerIntegrationTest method fileWithError.

@Test
public void fileWithError() throws Exception {
    Result exitCode = compiler.compile(compiler.fileManager().forResources(BadShiftAmount.class, "testdata/BadShiftAmountPositiveCases.java"));
    assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
    Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher = hasItem(diagnosticMessage(containsString("[BadShiftAmount]")));
    assertTrue("Error should be found. " + diagnosticHelper.describe(), matcher.matches(diagnosticHelper.getDiagnostics()));
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Diagnostic(javax.tools.Diagnostic) BadShiftAmount(com.google.errorprone.bugpatterns.BadShiftAmount) Result(com.sun.tools.javac.main.Main.Result) Test(org.junit.Test)

Aggregations

Diagnostic (javax.tools.Diagnostic)31 JavaFileObject (javax.tools.JavaFileObject)30 Test (org.junit.Test)13 JavaCompiler (javax.tools.JavaCompiler)11 Result (com.sun.tools.javac.main.Main.Result)10 DiagnosticCollector (javax.tools.DiagnosticCollector)9 File (java.io.File)7 IOException (java.io.IOException)7 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)7 PrintWriter (java.io.PrintWriter)6 Matchers.containsString (org.hamcrest.Matchers.containsString)6 ArrayList (java.util.ArrayList)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 DiagnosticListener (javax.tools.DiagnosticListener)4 ImmutableList (com.google.common.collect.ImmutableList)3 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)2 JavacTask (com.sun.source.util.JavacTask)2 OutputStreamWriter (java.io.OutputStreamWriter)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2