Use text blocks

This commit is contained in:
Stephan Schroevers
2024-12-26 11:39:54 +01:00
parent 3f566f8028
commit 2437c66793
75 changed files with 11080 additions and 10482 deletions

View File

@@ -19,9 +19,11 @@ final class BugPatternExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerWithoutAnnotation.java", "TestCheckerWithoutAnnotation.java",
"import com.google.errorprone.bugpatterns.BugChecker;", """
"", import com.google.errorprone.bugpatterns.BugChecker;
"public final class TestCheckerWithoutAnnotation extends BugChecker {}");
public final class TestCheckerWithoutAnnotation extends BugChecker {}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -31,14 +33,16 @@ final class BugPatternExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"MinimalBugChecker.java", "MinimalBugChecker.java",
"package pkg;", """
"", package pkg;
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.BugPattern.SeverityLevel;", import com.google.errorprone.BugPattern;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.BugPattern.SeverityLevel;
"", import com.google.errorprone.bugpatterns.BugChecker;
"@BugPattern(summary = \"MinimalBugChecker summary\", severity = SeverityLevel.ERROR)",
"public final class MinimalBugChecker extends BugChecker {}"); @BugPattern(summary = "MinimalBugChecker summary", severity = SeverityLevel.ERROR)
public final class MinimalBugChecker extends BugChecker {}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -62,25 +66,27 @@ final class BugPatternExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"CompleteBugChecker.java", "CompleteBugChecker.java",
"package pkg;", """
"", package pkg;
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.BugPattern.SeverityLevel;", import com.google.errorprone.BugPattern;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.BugPattern.SeverityLevel;
"import org.junit.jupiter.api.Test;", import com.google.errorprone.bugpatterns.BugChecker;
"", import org.junit.jupiter.api.Test;
"@BugPattern(",
" name = \"OtherName\",", @BugPattern(
" summary = \"CompleteBugChecker summary\",", name = "OtherName",
" linkType = BugPattern.LinkType.CUSTOM,", summary = "CompleteBugChecker summary",
" link = \"https://error-prone.picnic.tech\",", linkType = BugPattern.LinkType.CUSTOM,
" explanation = \"Example explanation\",", link = "https://error-prone.picnic.tech",
" severity = SeverityLevel.SUGGESTION,", explanation = "Example explanation",
" altNames = \"Check\",", severity = SeverityLevel.SUGGESTION,
" tags = BugPattern.StandardTags.SIMPLIFICATION,", altNames = "Check",
" disableable = false,", tags = BugPattern.StandardTags.SIMPLIFICATION,
" suppressionAnnotations = {BugPattern.class, Test.class})", disableable = false,
"public final class CompleteBugChecker extends BugChecker {}"); suppressionAnnotations = {BugPattern.class, Test.class})
public final class CompleteBugChecker extends BugChecker {}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -104,17 +110,19 @@ final class BugPatternExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"UndocumentedSuppressionBugPattern.java", "UndocumentedSuppressionBugPattern.java",
"package pkg;", """
"", package pkg;
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.BugPattern.SeverityLevel;", import com.google.errorprone.BugPattern;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.BugPattern.SeverityLevel;
"", import com.google.errorprone.bugpatterns.BugChecker;
"@BugPattern(",
" summary = \"UndocumentedSuppressionBugPattern summary\",", @BugPattern(
" severity = SeverityLevel.WARNING,", summary = "UndocumentedSuppressionBugPattern summary",
" documentSuppression = false)", severity = SeverityLevel.WARNING,
"public final class UndocumentedSuppressionBugPattern extends BugChecker {}"); documentSuppression = false)
public final class UndocumentedSuppressionBugPattern extends BugChecker {}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,

View File

@@ -18,9 +18,11 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerWithoutAnnotation.java", "TestCheckerWithoutAnnotation.java",
"import com.google.errorprone.bugpatterns.BugChecker;", """
"", import com.google.errorprone.bugpatterns.BugChecker;
"public final class TestCheckerWithoutAnnotation extends BugChecker {}");
public final class TestCheckerWithoutAnnotation extends BugChecker {}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -30,22 +32,24 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerTest.java", "TestCheckerTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class TestCheckerTest {",
" private static class TestChecker extends BugChecker {}", final class TestCheckerTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .addSourceLines(\"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\");", CompilationTestHelper.newInstance(TestChecker.class, getClass())
"", .addSourceLines("A.java", "// BUG: Diagnostic contains:", "class A {}");
" BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())",
" .addInputLines(\"A.java\", \"class A {}\")", BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\");", .addInputLines("A.java", "class A {}")
" }", .addOutputLines("A.java", "class A { /* This is a change. */ }");
"}"); }
}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -55,22 +59,24 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerTest.java", "TestCheckerTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class TestCheckerTest {",
" void m() {", final class TestCheckerTest {
" CompilationTestHelper.newInstance((Class<BugChecker>) null, getClass())", void m() {
" .addSourceLines(\"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\")", CompilationTestHelper.newInstance((Class<BugChecker>) null, getClass())
" .doTest();", .addSourceLines("A.java", "// BUG: Diagnostic contains:", "class A {}")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance((Class<BugChecker>) null, getClass())",
" .addInputLines(\"A.java\", \"class A {}\")", BugCheckerRefactoringTestHelper.newInstance((Class<BugChecker>) null, getClass())
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\")", .addInputLines("A.java", "class A {}")
" .doTest();", .addOutputLines("A.java", "class A { /* This is a change. */ }")
" }", .doTest();
"}"); }
}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -80,28 +86,30 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerTest.java", "TestCheckerTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class TestCheckerTest {",
" private static class TestChecker extends BugChecker {}", final class TestCheckerTest {
"", private static class TestChecker extends BugChecker {}
" @SuppressWarnings(\"unchecked\")",
" void m() {", @SuppressWarnings("unchecked")
" @SuppressWarnings(\"rawtypes\")", void m() {
" Class bugChecker = TestChecker.class;", @SuppressWarnings("rawtypes")
"", Class bugChecker = TestChecker.class;
" CompilationTestHelper.newInstance(bugChecker, getClass())",
" .addSourceLines(\"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\")", CompilationTestHelper.newInstance(bugChecker, getClass())
" .doTest();", .addSourceLines("A.java", "// BUG: Diagnostic contains:", "class A {}")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(bugChecker, getClass())",
" .addInputLines(\"A.java\", \"class A {}\")", BugCheckerRefactoringTestHelper.newInstance(bugChecker, getClass())
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\")", .addInputLines("A.java", "class A {}")
" .doTest();", .addOutputLines("A.java", "class A { /* This is a change. */ }")
" }", .doTest();
"}"); }
}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -111,27 +119,29 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerTest.java", "TestCheckerTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"import com.google.errorprone.scanner.ScannerSupplier;", import com.google.errorprone.bugpatterns.BugChecker;
"", import com.google.errorprone.scanner.ScannerSupplier;
"final class TestCheckerTest {",
" private static class TestChecker extends BugChecker {}", final class TestCheckerTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(", void m() {
" ScannerSupplier.fromBugCheckerClasses(TestChecker.class), getClass())", CompilationTestHelper.newInstance(
" .addSourceLines(\"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\")", ScannerSupplier.fromBugCheckerClasses(TestChecker.class), getClass())
" .doTest();", .addSourceLines("A.java", "// BUG: Diagnostic contains:", "class A {}")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(",
" ScannerSupplier.fromBugCheckerClasses(TestChecker.class), getClass())", BugCheckerRefactoringTestHelper.newInstance(
" .addInputLines(\"A.java\", \"class A {}\")", ScannerSupplier.fromBugCheckerClasses(TestChecker.class), getClass())
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\")", .addInputLines("A.java", "class A {}")
" .doTest();", .addOutputLines("A.java", "class A { /* This is a change. */ }")
" }", .doTest();
"}"); }
}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -141,29 +151,31 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerTest.java", "TestCheckerTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class TestCheckerTest {",
" private static class TestChecker extends BugChecker {}", final class TestCheckerTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .addSourceLines(toString() + \"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\")", CompilationTestHelper.newInstance(TestChecker.class, getClass())
" .addSourceLines(\"B.java\", \"// BUG: Diagnostic contains:\", \"class B {}\", toString())", .addSourceLines(toString() + "A.java", "// BUG: Diagnostic contains:", "class A {}")
" .doTest();", .addSourceLines("B.java", "// BUG: Diagnostic contains:", "class B {}", toString())
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())",
" .addInputLines(toString() + \"A.java\", \"class A {}\")", BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\")", .addInputLines(toString() + "A.java", "class A {}")
" .addInputLines(\"B.java\", \"class B {}\", toString())", .addOutputLines("A.java", "class A { /* This is a change. */ }")
" .addOutputLines(\"B.java\", \"class B { /* This is a change. */ }\")", .addInputLines("B.java", "class B {}", toString())
" .addInputLines(\"C.java\", \"class C {}\")", .addOutputLines("B.java", "class B { /* This is a change. */ }")
" .addOutputLines(\"C.java\", \"class C { /* This is a change. */ }\", toString())", .addInputLines("C.java", "class C {}")
" .doTest();", .addOutputLines("C.java", "class C { /* This is a change. */ }", toString())
" }", .doTest();
"}"); }
}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -173,26 +185,28 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerTest.java", "TestCheckerTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class TestCheckerTest {",
" private static class TestChecker extends BugChecker {}", final class TestCheckerTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper testHelper =", void m() {
" CompilationTestHelper.newInstance(TestChecker.class, getClass())", CompilationTestHelper testHelper =
" .addSourceLines(\"A.java\", \"class A {}\");", CompilationTestHelper.newInstance(TestChecker.class, getClass())
" testHelper.doTest();", .addSourceLines("A.java", "class A {}");
"", testHelper.doTest();
" BugCheckerRefactoringTestHelper.ExpectOutput expectedOutput =",
" BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())", BugCheckerRefactoringTestHelper.ExpectOutput expectedOutput =
" .addInputLines(\"A.java\", \"class A {}\");", BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())
" expectedOutput.addOutputLines(\"A.java\", \"class A {}\").doTest();", .addInputLines("A.java", "class A {}");
" expectedOutput.expectUnchanged().doTest();", expectedOutput.addOutputLines("A.java", "class A {}").doTest();
" }", expectedOutput.expectUnchanged().doTest();
"}"); }
}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -202,19 +216,21 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerTest.java", "TestCheckerTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class TestCheckerTest {",
" private static class TestChecker extends BugChecker {}", final class TestCheckerTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(TestChecker.class, getClass()).doTest();", void m() {
"", CompilationTestHelper.newInstance(TestChecker.class, getClass()).doTest();
" BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass()).doTest();",
" }", BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass()).doTest();
"}"); }
}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -224,26 +240,28 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"TestCheckerTest.java", "TestCheckerTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class TestCheckerTest {",
" private static class TestChecker extends BugChecker {}", final class TestCheckerTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .addSourceLines(\"A.java\", \"class A {}\")", CompilationTestHelper.newInstance(TestChecker.class, getClass())
" .doTest();", .addSourceLines("A.java", "class A {}")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())",
" .addInputLines(\"A.java\", \"class A {}\")", BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())
" .addOutputLines(\"A.java\", \"class A {}\")", .addInputLines("A.java", "class A {}")
" .addInputLines(\"B.java\", \"class B {}\")", .addOutputLines("A.java", "class A {}")
" .expectUnchanged()", .addInputLines("B.java", "class B {}")
" .doTest();", .expectUnchanged()
" }", .doTest();
"}"); }
}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -253,18 +271,20 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"SingleFileCompilationTestHelperTest.java", "SingleFileCompilationTestHelperTest.java",
"import com.google.errorprone.CompilationTestHelper;", """
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class SingleFileCompilationTestHelperTest {",
" private static class TestChecker extends BugChecker {}", final class SingleFileCompilationTestHelperTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .addSourceLines(\"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\")", CompilationTestHelper.newInstance(TestChecker.class, getClass())
" .doTest();", .addSourceLines("A.java", "// BUG: Diagnostic contains:", "class A {}")
" }", .doTest();
"}"); }
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -285,19 +305,21 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"SingleFileCompilationTestHelperWithSetArgsTest.java", "SingleFileCompilationTestHelperWithSetArgsTest.java",
"import com.google.errorprone.CompilationTestHelper;", """
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class SingleFileCompilationTestHelperWithSetArgsTest {",
" private static class TestChecker extends BugChecker {}", final class SingleFileCompilationTestHelperWithSetArgsTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .setArgs(\"-XepAllSuggestionsAsWarnings\")", CompilationTestHelper.newInstance(TestChecker.class, getClass())
" .addSourceLines(\"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\")", .setArgs("-XepAllSuggestionsAsWarnings")
" .doTest();", .addSourceLines("A.java", "// BUG: Diagnostic contains:", "class A {}")
" }", .doTest();
"}"); }
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -318,19 +340,21 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"MultiFileCompilationTestHelperTest.java", "MultiFileCompilationTestHelperTest.java",
"import com.google.errorprone.CompilationTestHelper;", """
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class MultiFileCompilationTestHelperTest {",
" private static class TestChecker extends BugChecker {}", final class MultiFileCompilationTestHelperTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .addSourceLines(\"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\")", CompilationTestHelper.newInstance(TestChecker.class, getClass())
" .addSourceLines(\"B.java\", \"// BUG: Diagnostic contains:\", \"class B {}\")", .addSourceLines("A.java", "// BUG: Diagnostic contains:", "class A {}")
" .doTest();", .addSourceLines("B.java", "// BUG: Diagnostic contains:", "class B {}")
" }", .doTest();
"}"); }
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -353,19 +377,21 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"SingleFileBugCheckerRefactoringTestHelperTest.java", "SingleFileBugCheckerRefactoringTestHelperTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class SingleFileBugCheckerRefactoringTestHelperTest {",
" private static class TestChecker extends BugChecker {}", final class SingleFileBugCheckerRefactoringTestHelperTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .addInputLines(\"A.java\", \"class A {}\")", BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\")", .addInputLines("A.java", "class A {}")
" .doTest();", .addOutputLines("A.java", "class A { /* This is a change. */ }")
" }", .doTest();
"}"); }
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -387,23 +413,25 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"SingleFileBugCheckerRefactoringTestHelperWithSetArgsFixChooserAndCustomTestModeTest.java", "SingleFileBugCheckerRefactoringTestHelperWithSetArgsFixChooserAndCustomTestModeTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;", import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class SingleFileBugCheckerRefactoringTestHelperWithSetArgsFixChooserAndCustomTestModeTest {",
" private static class TestChecker extends BugChecker {}", final class SingleFileBugCheckerRefactoringTestHelperWithSetArgsFixChooserAndCustomTestModeTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .setArgs(\"-XepAllSuggestionsAsWarnings\")", BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())
" .setFixChooser(FixChoosers.SECOND)", .setArgs("-XepAllSuggestionsAsWarnings")
" .addInputLines(\"A.java\", \"class A {}\")", .setFixChooser(FixChoosers.SECOND)
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\")", .addInputLines("A.java", "class A {}")
" .doTest(TestMode.TEXT_MATCH);", .addOutputLines("A.java", "class A { /* This is a change. */ }")
" }", .doTest(TestMode.TEXT_MATCH);
"}"); }
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -425,21 +453,23 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"MultiFileBugCheckerRefactoringTestHelperTest.java", "MultiFileBugCheckerRefactoringTestHelperTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class MultiFileBugCheckerRefactoringTestHelperTest {",
" private static class TestChecker extends BugChecker {}", final class MultiFileBugCheckerRefactoringTestHelperTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .addInputLines(\"A.java\", \"class A {}\")", BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\")", .addInputLines("A.java", "class A {}")
" .addInputLines(\"B.java\", \"class B {}\")", .addOutputLines("A.java", "class A { /* This is a change. */ }")
" .addOutputLines(\"B.java\", \"class B { /* This is a change. */ }\")", .addInputLines("B.java", "class B {}")
" .doTest();", .addOutputLines("B.java", "class B { /* This is a change. */ }")
" }", .doTest();
"}"); }
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -462,24 +492,26 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"CompilationAndBugCheckerRefactoringTestHelpersTest.java", "CompilationAndBugCheckerRefactoringTestHelpersTest.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class CompilationAndBugCheckerRefactoringTestHelpersTest {",
" private static class TestChecker extends BugChecker {}", final class CompilationAndBugCheckerRefactoringTestHelpersTest {
"", private static class TestChecker extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(TestChecker.class, getClass())", void m() {
" .addSourceLines(\"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\")", CompilationTestHelper.newInstance(TestChecker.class, getClass())
" .doTest();", .addSourceLines("A.java", "// BUG: Diagnostic contains:", "class A {}")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())",
" .addInputLines(\"A.java\", \"class A {}\")", BugCheckerRefactoringTestHelper.newInstance(TestChecker.class, getClass())
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\")", .addInputLines("A.java", "class A {}")
" .doTest();", .addOutputLines("A.java", "class A { /* This is a change. */ }")
" }", .doTest();
"}"); }
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -506,28 +538,30 @@ final class BugPatternTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"CompilationAndBugCheckerRefactoringTestHelpersWithCustomCheckerPackageAndNamesTest.java", "CompilationAndBugCheckerRefactoringTestHelpersWithCustomCheckerPackageAndNamesTest.java",
"package pkg;", """
"", package pkg;
"import com.google.errorprone.BugCheckerRefactoringTestHelper;",
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"", import com.google.errorprone.bugpatterns.BugChecker;
"final class CompilationAndBugCheckerRefactoringTestHelpersWithCustomCheckerPackageAndNamesTest {",
" private static class CustomTestChecker extends BugChecker {}", final class CompilationAndBugCheckerRefactoringTestHelpersWithCustomCheckerPackageAndNamesTest {
"", private static class CustomTestChecker extends BugChecker {}
" private static class CustomTestChecker2 extends BugChecker {}",
"", private static class CustomTestChecker2 extends BugChecker {}
" void m() {",
" CompilationTestHelper.newInstance(CustomTestChecker.class, getClass())", void m() {
" .addSourceLines(\"A.java\", \"// BUG: Diagnostic contains:\", \"class A {}\")", CompilationTestHelper.newInstance(CustomTestChecker.class, getClass())
" .doTest();", .addSourceLines("A.java", "// BUG: Diagnostic contains:", "class A {}")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(CustomTestChecker2.class, getClass())",
" .addInputLines(\"A.java\", \"class A {}\")", BugCheckerRefactoringTestHelper.newInstance(CustomTestChecker2.class, getClass())
" .addOutputLines(\"A.java\", \"class A { /* This is a change. */ }\")", .addInputLines("A.java", "class A {}")
" .doTest();", .addOutputLines("A.java", "class A { /* This is a change. */ }")
" }", .doTest();
"}"); }
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,

View File

@@ -62,7 +62,11 @@ final class DocumentationGeneratorTaskListenerTest {
assertThatThrownBy( assertThatThrownBy(
() -> () ->
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, "A.java", "class A {}")) outputDirectory,
"A.java",
"""
class A {}
"""))
.hasRootCauseInstanceOf(FileSystemException.class) .hasRootCauseInstanceOf(FileSystemException.class)
.hasCauseInstanceOf(IllegalStateException.class) .hasCauseInstanceOf(IllegalStateException.class)
.hasMessageEndingWith("Error while creating directory with path '%s'", outputDirectory); .hasMessageEndingWith("Error while creating directory with path '%s'", outputDirectory);
@@ -72,7 +76,12 @@ final class DocumentationGeneratorTaskListenerTest {
// post-processing by GJF; TBD.) // post-processing by GJF; TBD.)
@Test @Test
void noClassNoOutput(@TempDir Path outputDirectory) { void noClassNoOutput(@TempDir Path outputDirectory) {
Compilation.compileWithDocumentationGenerator(outputDirectory, "A.java", "package pkg;"); Compilation.compileWithDocumentationGenerator(
outputDirectory,
"A.java",
"""
package pkg;
""");
assertThat(outputDirectory).isEmptyDirectory(); assertThat(outputDirectory).isEmptyDirectory();
} }
@@ -83,7 +92,11 @@ final class DocumentationGeneratorTaskListenerTest {
assertThatThrownBy( assertThatThrownBy(
() -> () ->
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
actualOutputDirectory, "A.java", "package pkg;")) actualOutputDirectory,
"A.java",
"""
package pkg;
"""))
.isInstanceOf(IllegalArgumentException.class) .isInstanceOf(IllegalArgumentException.class)
.hasMessage("Precisely one path must be provided"); .hasMessage("Precisely one path must be provided");
} }
@@ -93,7 +106,9 @@ final class DocumentationGeneratorTaskListenerTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"DocumentationGeneratorTaskListenerTestClass.java", "DocumentationGeneratorTaskListenerTestClass.java",
"class DocumentationGeneratorTaskListenerTestClass {}"); """
class DocumentationGeneratorTaskListenerTestClass {}
""");
assertThat( assertThat(
outputDirectory.resolve( outputDirectory.resolve(

View File

@@ -16,7 +16,11 @@ final class RefasterRuleCollectionTestExtractorTest {
@Test @Test
void noRefasterRuleTest(@TempDir Path outputDirectory) { void noRefasterRuleTest(@TempDir Path outputDirectory) {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, "NoRefasterRuleTest.java", "public final class NoRefasterRuleTest {}"); outputDirectory,
"NoRefasterRuleTest.java",
"""
public final class NoRefasterRuleTest {}
""");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory(); assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
} }
@@ -28,9 +32,11 @@ final class RefasterRuleCollectionTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"InvalidTestClassNameInput.java", "InvalidTestClassNameInput.java",
"import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;", """
"", import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;
"final class InvalidTestClassName implements RefasterRuleCollectionTestCase {}"))
final class InvalidTestClassName implements RefasterRuleCollectionTestCase {}
"""))
.cause() .cause()
.isInstanceOf(VerifyException.class) .isInstanceOf(VerifyException.class)
.hasMessage( .hasMessage(
@@ -44,9 +50,11 @@ final class RefasterRuleCollectionTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"InvalidFileNameTest.java", "InvalidFileNameTest.java",
"import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;", """
"", import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;
"final class InvalidFileNameTest implements RefasterRuleCollectionTestCase {}"))
final class InvalidFileNameTest implements RefasterRuleCollectionTestCase {}
"""))
.cause() .cause()
.isInstanceOf(VerifyException.class) .isInstanceOf(VerifyException.class)
.hasMessage( .hasMessage(
@@ -58,9 +66,11 @@ final class RefasterRuleCollectionTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"EmptyRefasterRuleCollectionTestInput.java", "EmptyRefasterRuleCollectionTestInput.java",
"import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;", """
"", import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;
"final class EmptyRefasterRuleCollectionTest implements RefasterRuleCollectionTestCase {}");
final class EmptyRefasterRuleCollectionTest implements RefasterRuleCollectionTestCase {}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -77,13 +87,15 @@ final class RefasterRuleCollectionTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"SingletonRefasterRuleCollectionTestOutput.java", "SingletonRefasterRuleCollectionTestOutput.java",
"import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;", """
"", import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;
"final class SingletonRefasterRuleCollectionTest implements RefasterRuleCollectionTestCase {",
" int testMyRule() {", final class SingletonRefasterRuleCollectionTest implements RefasterRuleCollectionTestCase {
" return 42;", int testMyRule() {
" }", return 42;
"}"); }
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,
@@ -106,31 +118,33 @@ final class RefasterRuleCollectionTestExtractorTest {
Compilation.compileWithDocumentationGenerator( Compilation.compileWithDocumentationGenerator(
outputDirectory, outputDirectory,
"pkg/ComplexRefasterRuleCollectionTestInput.java", "pkg/ComplexRefasterRuleCollectionTestInput.java",
"package pkg;", """
"", package pkg;
"import com.google.common.collect.ImmutableSet;",
"import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;", import com.google.common.collect.ImmutableSet;
"", import tech.picnic.errorprone.refaster.test.RefasterRuleCollectionTestCase;
"final class ComplexRefasterRuleCollectionTest implements RefasterRuleCollectionTestCase {",
" private static final String IGNORED_CONSTANT = \"constant\";", final class ComplexRefasterRuleCollectionTest implements RefasterRuleCollectionTestCase {
"", private static final String IGNORED_CONSTANT = "constant";
" @Override",
" public ImmutableSet<Object> elidedTypesAndStaticImports() {", @Override
" return ImmutableSet.of();", public ImmutableSet<Object> elidedTypesAndStaticImports() {
" }", return ImmutableSet.of();
"", }
" /** Javadoc. */",
" String testFirstRule() {", /** Javadoc. */
" return \"Don't panic\";", String testFirstRule() {
" }", return "Don't panic";
"", }
" // Comment.",
" String testSecondRule() {", // Comment.
" return \"Carry a towel\";", String testSecondRule() {
" }", return "Carry a towel";
"", }
" void testEmptyRule() {}",
"}"); void testEmptyRule() {}
}
""");
verifyGeneratedFileContent( verifyGeneratedFileContent(
outputDirectory, outputDirectory,

View File

@@ -13,99 +13,101 @@ final class AmbiguousJsonCreatorTest {
"X", m -> m.contains("`JsonCreator.Mode` should be set for single-argument creators")) "X", m -> m.contains("`JsonCreator.Mode` should be set for single-argument creators"))
.addSourceLines( .addSourceLines(
"Container.java", "Container.java",
"import com.fasterxml.jackson.annotation.JsonCreator;", """
"import com.fasterxml.jackson.annotation.JsonValue;", import com.fasterxml.jackson.annotation.JsonCreator;
"", import com.fasterxml.jackson.annotation.JsonValue;
"interface Container {",
" enum A {", interface Container {
" FOO(1);", enum A {
"", FOO(1);
" private final int i;",
"", private final int i;
" A(int i) {",
" this.i = i;", A(int i) {
" }", this.i = i;
"", }
" // BUG: Diagnostic matches: X",
" @JsonCreator", // BUG: Diagnostic matches: X
" public static A of(int i) {", @JsonCreator
" return FOO;", public static A of(int i) {
" }", return FOO;
" }", }
"", }
" enum B {",
" FOO(1);", enum B {
"", FOO(1);
" private final int i;",
"", private final int i;
" B(int i) {",
" this.i = i;", B(int i) {
" }", this.i = i;
"", }
" @JsonCreator(mode = JsonCreator.Mode.DELEGATING)",
" public static B of(int i) {", @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
" return FOO;", public static B of(int i) {
" }", return FOO;
" }", }
"", }
" enum C {",
" FOO(1, \"s\");", enum C {
"", FOO(1, "s");
" @JsonValue private final int i;",
" private final String s;", @JsonValue private final int i;
"", private final String s;
" C(int i, String s) {",
" this.i = i;", C(int i, String s) {
" this.s = s;", this.i = i;
" }", this.s = s;
"", }
" // BUG: Diagnostic matches: X",
" @JsonCreator", // BUG: Diagnostic matches: X
" public static C of(int i) {", @JsonCreator
" return FOO;", public static C of(int i) {
" }", return FOO;
" }", }
"", }
" enum D {",
" FOO(1, \"s\");", enum D {
"", FOO(1, "s");
" private final int i;",
" private final String s;", private final int i;
"", private final String s;
" D(int i, String s) {",
" this.i = i;", D(int i, String s) {
" this.s = s;", this.i = i;
" }", this.s = s;
"", }
" @JsonCreator",
" public static D of(int i, String s) {", @JsonCreator
" return FOO;", public static D of(int i, String s) {
" }", return FOO;
" }", }
"", }
" enum E {",
" FOO;", enum E {
"", FOO;
" // BUG: Diagnostic matches: X",
" @JsonCreator", // BUG: Diagnostic matches: X
" public static E of(String s) {", @JsonCreator
" return FOO;", public static E of(String s) {
" }", return FOO;
" }", }
"", }
" class F {",
" private final String s;", class F {
"", private final String s;
" F(String s) {",
" this.s = s;", F(String s) {
" }", this.s = s;
"", }
" @JsonCreator",
" public static F of(String s) {", @JsonCreator
" return new F(s);", public static F of(String s) {
" }", return new F(s);
" }", }
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -114,28 +116,32 @@ final class AmbiguousJsonCreatorTest {
BugCheckerRefactoringTestHelper.newInstance(AmbiguousJsonCreator.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(AmbiguousJsonCreator.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.fasterxml.jackson.annotation.JsonCreator;", """
"", import com.fasterxml.jackson.annotation.JsonCreator;
"enum A {",
" FOO;", enum A {
"", FOO;
" @JsonCreator",
" public static A of(String s) {", @JsonCreator
" return FOO;", public static A of(String s) {
" }", return FOO;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.fasterxml.jackson.annotation.JsonCreator;", """
"", import com.fasterxml.jackson.annotation.JsonCreator;
"enum A {",
" FOO;", enum A {
"", FOO;
" @JsonCreator(mode = JsonCreator.Mode.DELEGATING)",
" public static A of(String s) {", @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
" return FOO;", public static A of(String s) {
" }", return FOO;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,22 +11,24 @@ final class AssertJIsNullTest {
CompilationTestHelper.newInstance(AssertJIsNull.class, getClass()) CompilationTestHelper.newInstance(AssertJIsNull.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static org.assertj.core.api.Assertions.assertThat;", """
"", import static org.assertj.core.api.Assertions.assertThat;
"class A {",
" void m() {", class A {
" assertThat(1).isEqualTo(1);", void m() {
" // BUG: Diagnostic contains:", assertThat(1).isEqualTo(1);
" assertThat(1).isEqualTo(null);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(1).isEqualTo(null);
" assertThat(\"foo\").isEqualTo(null);", // BUG: Diagnostic contains:
" isEqualTo(null);", assertThat("foo").isEqualTo(null);
" }", isEqualTo(null);
"", }
" private boolean isEqualTo(Object value) {",
" return value.equals(\"bar\");", private boolean isEqualTo(Object value) {
" }", return value.equals("bar");
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -35,24 +37,28 @@ final class AssertJIsNullTest {
BugCheckerRefactoringTestHelper.newInstance(AssertJIsNull.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(AssertJIsNull.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static org.assertj.core.api.Assertions.assertThat;", """
"", import static org.assertj.core.api.Assertions.assertThat;
"class A {",
" void m() {", class A {
" assertThat(1).isEqualTo(null);", void m() {
" assertThat(\"foo\").isEqualTo(null);", assertThat(1).isEqualTo(null);
" }", assertThat("foo").isEqualTo(null);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static org.assertj.core.api.Assertions.assertThat;", """
"", import static org.assertj.core.api.Assertions.assertThat;
"class A {",
" void m() {", class A {
" assertThat(1).isNull();", void m() {
" assertThat(\"foo\").isNull();", assertThat(1).isNull();
" }", assertThat("foo").isNull();
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,56 +11,58 @@ final class AutowiredConstructorTest {
CompilationTestHelper.newInstance(AutowiredConstructor.class, getClass()) CompilationTestHelper.newInstance(AutowiredConstructor.class, getClass())
.addSourceLines( .addSourceLines(
"Container.java", "Container.java",
"import com.google.errorprone.annotations.Immutable;", """
"import java.util.List;", import com.google.errorprone.annotations.Immutable;
"import org.springframework.beans.factory.annotation.Autowired;", import java.util.List;
"", import org.springframework.beans.factory.annotation.Autowired;
"interface Container {",
" @Immutable", interface Container {
" class A {", @Immutable
" A() {}", class A {
" }", A() {}
"", }
" class B {",
" @Autowired", class B {
" void setProperty(Object o) {}", @Autowired
" }", void setProperty(Object o) {}
"", }
" class C {",
" // BUG: Diagnostic contains:", class C {
" @Autowired", // BUG: Diagnostic contains:
" C() {}", @Autowired
" }", C() {}
"", }
" class D {",
" // BUG: Diagnostic contains:", class D {
" @Autowired", // BUG: Diagnostic contains:
" D(String x) {}", @Autowired
" }", D(String x) {}
"", }
" class E {",
" @Autowired", class E {
" E() {}", @Autowired
"", E() {}
" E(String x) {}",
" }", E(String x) {}
"", }
" class F {",
" F() {}", class F {
"", F() {}
" @Autowired",
" F(String x) {}", @Autowired
" }", F(String x) {}
"", }
" class G {",
" @Autowired private Object o;", class G {
" }", @Autowired private Object o;
"", }
" class H {",
" @SafeVarargs", class H {
" H(List<String>... lists) {}", @SafeVarargs
" }", H(List<String>... lists) {}
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -69,34 +71,38 @@ final class AutowiredConstructorTest {
BugCheckerRefactoringTestHelper.newInstance(AutowiredConstructor.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(AutowiredConstructor.class, getClass())
.addInputLines( .addInputLines(
"Container.java", "Container.java",
"import org.springframework.beans.factory.annotation.Autowired;", """
"", import org.springframework.beans.factory.annotation.Autowired;
"interface Container {",
" class A {", interface Container {
" @Autowired", class A {
" @Deprecated", @Autowired
" A() {}", @Deprecated
" }", A() {}
"", }
" class B {",
" @Autowired", class B {
" B(String x) {}", @Autowired
" }", B(String x) {}
"}") }
}
""")
.addOutputLines( .addOutputLines(
"Container.java", "Container.java",
"import org.springframework.beans.factory.annotation.Autowired;", """
"", import org.springframework.beans.factory.annotation.Autowired;
"interface Container {",
" class A {", interface Container {
" @Deprecated", class A {
" A() {}", @Deprecated
" }", A() {}
"", }
" class B {",
" B(String x) {}", class B {
" }", B(String x) {}
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,128 +11,130 @@ final class CanonicalAnnotationSyntaxTest {
CompilationTestHelper.newInstance(CanonicalAnnotationSyntax.class, getClass()) CompilationTestHelper.newInstance(CanonicalAnnotationSyntax.class, getClass())
.addSourceLines( .addSourceLines(
"pkg/A.java", "pkg/A.java",
"package pkg;", """
"", package pkg;
"import pkg.A.Foo;",
"", import pkg.A.Foo;
"interface A {",
" @interface Foo {", interface A {
" int[] value() default {};", @interface Foo {
"", int[] value() default {};
" int[] value2() default {};",
" }", int[] value2() default {};
"", }
" @pkg.A.Foo",
" A minimal1();", @pkg.A.Foo
"", A minimal1();
" @A.Foo",
" A minimal2();", @A.Foo
"", A minimal2();
" @Foo",
" A minimal3();", @Foo
"", A minimal3();
" // BUG: Diagnostic contains:",
" @pkg.A.Foo()", // BUG: Diagnostic contains:
" A functional1();", @pkg.A.Foo()
"", A functional1();
" // BUG: Diagnostic contains:",
" @A.Foo()", // BUG: Diagnostic contains:
" A functional2();", @A.Foo()
"", A functional2();
" // BUG: Diagnostic contains:",
" @Foo()", // BUG: Diagnostic contains:
" A functional3();", @Foo()
"", A functional3();
" @pkg.A.Foo(1)",
" A simple1();", @pkg.A.Foo(1)
"", A simple1();
" @A.Foo(1)",
" A simple2();", @A.Foo(1)
"", A simple2();
" @Foo(1)",
" A simple3();", @Foo(1)
"", A simple3();
" // BUG: Diagnostic contains:",
" @pkg.A.Foo({1})", // BUG: Diagnostic contains:
" A singleton1();", @pkg.A.Foo({1})
"", A singleton1();
" // BUG: Diagnostic contains:",
" @A.Foo({1})", // BUG: Diagnostic contains:
" A singleton2();", @A.Foo({1})
"", A singleton2();
" // BUG: Diagnostic contains:",
" @Foo({1})", // BUG: Diagnostic contains:
" A singleton3();", @Foo({1})
"", A singleton3();
" // BUG: Diagnostic contains:",
" @pkg.A.Foo(value = 1)", // BUG: Diagnostic contains:
" A verbose1();", @pkg.A.Foo(value = 1)
"", A verbose1();
" // BUG: Diagnostic contains:",
" @A.Foo(value = 1)", // BUG: Diagnostic contains:
" A verbose2();", @A.Foo(value = 1)
"", A verbose2();
" // BUG: Diagnostic contains:",
" @Foo(value = 1)", // BUG: Diagnostic contains:
" A verbose3();", @Foo(value = 1)
"", A verbose3();
" @pkg.A.Foo(value2 = 2)",
" A custom1();", @pkg.A.Foo(value2 = 2)
"", A custom1();
" @A.Foo(value2 = 2)",
" A custom2();", @A.Foo(value2 = 2)
"", A custom2();
" @Foo(value2 = 2)",
" A custom3();", @Foo(value2 = 2)
"", A custom3();
" // BUG: Diagnostic contains:",
" @pkg.A.Foo(value2 = {2})", // BUG: Diagnostic contains:
" A customSingleton1();", @pkg.A.Foo(value2 = {2})
"", A customSingleton1();
" // BUG: Diagnostic contains:",
" @A.Foo(value2 = {2})", // BUG: Diagnostic contains:
" A customSingleton2();", @A.Foo(value2 = {2})
"", A customSingleton2();
" // BUG: Diagnostic contains:",
" @Foo(value2 = {2})", // BUG: Diagnostic contains:
" A customSingleton3();", @Foo(value2 = {2})
"", A customSingleton3();
" @pkg.A.Foo(value2 = {2, 2})",
" A customPair1();", @pkg.A.Foo(value2 = {2, 2})
"", A customPair1();
" @A.Foo(value2 = {2, 2})",
" A customPair2();", @A.Foo(value2 = {2, 2})
"", A customPair2();
" @Foo(value2 = {2, 2})",
" A customPair3();", @Foo(value2 = {2, 2})
"", A customPair3();
" @pkg.A.Foo(value = 1, value2 = 2)",
" A extended1();", @pkg.A.Foo(value = 1, value2 = 2)
"", A extended1();
" @A.Foo(value = 1, value2 = 2)",
" A extended2();", @A.Foo(value = 1, value2 = 2)
"", A extended2();
" @Foo(value = 1, value2 = 2)",
" A extended3();", @Foo(value = 1, value2 = 2)
"", A extended3();
" // BUG: Diagnostic contains:",
" @pkg.A.Foo({", // BUG: Diagnostic contains:
" 1, 1,", @pkg.A.Foo({
" })", 1, 1,
" A trailingComma1();", })
"", A trailingComma1();
" // BUG: Diagnostic contains:",
" @A.Foo({", // BUG: Diagnostic contains:
" 1, 1,", @A.Foo({
" })", 1, 1,
" A trailingComma2();", })
"", A trailingComma2();
" // BUG: Diagnostic contains:",
" @Foo({", // BUG: Diagnostic contains:
" 1, 1,", @Foo({
" })", 1, 1,
" A trailingComma3();", })
"}") A trailingComma3();
}
""")
.doTest(); .doTest();
} }
@@ -141,139 +143,143 @@ final class CanonicalAnnotationSyntaxTest {
BugCheckerRefactoringTestHelper.newInstance(CanonicalAnnotationSyntax.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(CanonicalAnnotationSyntax.class, getClass())
.addInputLines( .addInputLines(
"pkg/A.java", "pkg/A.java",
"package pkg;", """
"", package pkg;
"import pkg.A.Foo;",
"", import pkg.A.Foo;
"interface A {",
" @interface Foo {", interface A {
" String[] value() default {};", @interface Foo {
"", String[] value() default {};
" int[] value2() default {};",
" }", int[] value2() default {};
"", }
" @pkg.A.Foo()",
" A functional1();", @pkg.A.Foo()
"", A functional1();
" @A.Foo()",
" A functional2();", @A.Foo()
"", A functional2();
" @Foo()",
" A functional3();", @Foo()
"", A functional3();
" @pkg.A.Foo(value = \"foo\")",
" A verbose1();", @pkg.A.Foo(value = "foo")
"", A verbose1();
" @A.Foo(value = \"a'b\")",
" A verbose2();", @A.Foo(value = "a'b")
"", A verbose2();
" @Foo(value = \"a\" + \"\\nb\")",
" A verbose3();", @Foo(value = "a" + "\\nb")
"", A verbose3();
" @pkg.A.Foo(value = {\"foo\"})",
" A moreVerbose1();", @pkg.A.Foo(value = {"foo"})
"", A moreVerbose1();
" @A.Foo(value = {\"a'b\"})",
" A moreVerbose2();", @A.Foo(value = {"a'b"})
"", A moreVerbose2();
" @Foo(value = {\"a\" + \"\\nb\"})",
" A moreVerbose3();", @Foo(value = {"a" + "\\nb"})
"", A moreVerbose3();
" @pkg.A.Foo(",
" value = {\"foo\", \"bar\"},", @pkg.A.Foo(
" value2 = {2})", value = {"foo", "bar"},
" A extended1();", value2 = {2})
"", A extended1();
" @A.Foo(",
" value = {\"a'b\", \"c'd\"},", @A.Foo(
" value2 = {2})", value = {"a'b", "c'd"},
" A extended2();", value2 = {2})
"", A extended2();
" @Foo(",
" value = {\"a\" + \"\\nb\", \"c\" + \"\\nd\"},", @Foo(
" value2 = {2})", value = {"a" + "\\nb", "c" + "\\nd"},
" A extended3();", value2 = {2})
"", A extended3();
" @pkg.A.Foo({",
" \"foo\", \"bar\",", @pkg.A.Foo({
" })", "foo", "bar",
" A trailingComma1();", })
"", A trailingComma1();
" @A.Foo({",
" \"a'b\", \"c'd\",", @A.Foo({
" })", "a'b", "c'd",
" A trailingComma2();", })
"", A trailingComma2();
" @Foo({",
" \"a\" + \"\\nb\",", @Foo({
" \"c\" + \"\\nd\",", "a" + "\\nb",
" })", "c" + "\\nd",
" A trailingComma3();", })
"}") A trailingComma3();
}
""")
.addOutputLines( .addOutputLines(
"pkg/A.java", "pkg/A.java",
"package pkg;", """
"", package pkg;
"import pkg.A.Foo;",
"", import pkg.A.Foo;
"interface A {",
" @interface Foo {", interface A {
" String[] value() default {};", @interface Foo {
"", String[] value() default {};
" int[] value2() default {};",
" }", int[] value2() default {};
"", }
" @pkg.A.Foo",
" A functional1();", @pkg.A.Foo
"", A functional1();
" @A.Foo",
" A functional2();", @A.Foo
"", A functional2();
" @Foo",
" A functional3();", @Foo
"", A functional3();
" @pkg.A.Foo(\"foo\")",
" A verbose1();", @pkg.A.Foo("foo")
"", A verbose1();
" @A.Foo(\"a'b\")",
" A verbose2();", @A.Foo("a'b")
"", A verbose2();
" @Foo(\"a\" + \"\\nb\")",
" A verbose3();", @Foo("a" + "\\nb")
"", A verbose3();
" @pkg.A.Foo(\"foo\")",
" A moreVerbose1();", @pkg.A.Foo("foo")
"", A moreVerbose1();
" @A.Foo(\"a'b\")",
" A moreVerbose2();", @A.Foo("a'b")
"", A moreVerbose2();
" @Foo(\"a\" + \"\\nb\")",
" A moreVerbose3();", @Foo("a" + "\\nb")
"", A moreVerbose3();
" @pkg.A.Foo(",
" value = {\"foo\", \"bar\"},", @pkg.A.Foo(
" value2 = 2)", value = {"foo", "bar"},
" A extended1();", value2 = 2)
"", A extended1();
" @A.Foo(",
" value = {\"a'b\", \"c'd\"},", @A.Foo(
" value2 = 2)", value = {"a'b", "c'd"},
" A extended2();", value2 = 2)
"", A extended2();
" @Foo(",
" value = {\"a\" + \"\\nb\", \"c\" + \"\\nd\"},", @Foo(
" value2 = 2)", value = {"a" + "\\nb", "c" + "\\nd"},
" A extended3();", value2 = 2)
"", A extended3();
" @pkg.A.Foo({\"foo\", \"bar\"})",
" A trailingComma1();", @pkg.A.Foo({"foo", "bar"})
"", A trailingComma1();
" @A.Foo({\"a'b\", \"c'd\"})",
" A trailingComma2();", @A.Foo({"a'b", "c'd"})
"", A trailingComma2();
" @Foo({\"a\" + \"\\nb\", \"c\" + \"\\nd\"})",
" A trailingComma3();", @Foo({"a" + "\\nb", "c" + "\\nd"})
"}") A trailingComma3();
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -14,35 +14,37 @@ final class CanonicalClassNameUsageTest {
"--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED") "--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED")
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;", """
"", import static com.google.errorprone.matchers.Matchers.instanceMethod;
"import com.google.errorprone.VisitorState;",
"import tech.picnic.errorprone.utils.MoreTypes;", import com.google.errorprone.VisitorState;
"", import tech.picnic.errorprone.utils.MoreTypes;
"class A {",
" void m(VisitorState state) {", class A {
" String a = A.class.getName();", void m(VisitorState state) {
" String b = getClass().getName();", String a = A.class.getName();
" A.class.getName().toString();", String b = getClass().getName();
" System.out.println(A.class.getName());", A.class.getName().toString();
" methodInUnnamedPackage(A.class.getName());", System.out.println(A.class.getName());
" instanceMethod().onExactClass(A.class.getCanonicalName());", methodInUnnamedPackage(A.class.getName());
" MoreTypes.type(A.class.getCanonicalName());", instanceMethod().onExactClass(A.class.getCanonicalName());
" MoreTypes.type(A.class.getCanonicalName() + \".SubType\");", MoreTypes.type(A.class.getCanonicalName());
" instanceMethod().onExactClass(new Object() {}.getClass().getName());", MoreTypes.type(A.class.getCanonicalName() + ".SubType");
" instanceMethod().onExactClass(methodInUnnamedPackage(A.class.getName()));", instanceMethod().onExactClass(new Object() {}.getClass().getName());
" // BUG: Diagnostic contains:", instanceMethod().onExactClass(methodInUnnamedPackage(A.class.getName()));
" instanceMethod().onExactClass(A.class.getName());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", instanceMethod().onExactClass(A.class.getName());
" MoreTypes.type(A.class.getName());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", MoreTypes.type(A.class.getName());
" state.binaryNameFromClassname(A.class.getName() + \".SubType\");", // BUG: Diagnostic contains:
" }", state.binaryNameFromClassname(A.class.getName() + ".SubType");
"", }
" String methodInUnnamedPackage(String str) {",
" return str;", String methodInUnnamedPackage(String str) {
" }", return str;
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -51,32 +53,36 @@ final class CanonicalClassNameUsageTest {
BugCheckerRefactoringTestHelper.newInstance(CanonicalClassNameUsage.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(CanonicalClassNameUsage.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;", """
"", import static com.google.errorprone.matchers.Matchers.instanceMethod;
"import com.google.errorprone.BugPattern;",
"import tech.picnic.errorprone.utils.MoreTypes;", import com.google.errorprone.BugPattern;
"", import tech.picnic.errorprone.utils.MoreTypes;
"class A {",
" void m() {", class A {
" instanceMethod().onDescendantOfAny(A.class.getName(), BugPattern.LinkType.class.getName());", void m() {
" MoreTypes.type(String.class.getName());", instanceMethod().onDescendantOfAny(A.class.getName(), BugPattern.LinkType.class.getName());
" }", MoreTypes.type(String.class.getName());
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;", """
"", import static com.google.errorprone.matchers.Matchers.instanceMethod;
"import com.google.errorprone.BugPattern;",
"import tech.picnic.errorprone.utils.MoreTypes;", import com.google.errorprone.BugPattern;
"", import tech.picnic.errorprone.utils.MoreTypes;
"class A {",
" void m() {", class A {
" instanceMethod()", void m() {
" .onDescendantOfAny(", instanceMethod()
" A.class.getCanonicalName(), BugPattern.LinkType.class.getCanonicalName());", .onDescendantOfAny(
" MoreTypes.type(String.class.getCanonicalName());", A.class.getCanonicalName(), BugPattern.LinkType.class.getCanonicalName());
" }", MoreTypes.type(String.class.getCanonicalName());
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,37 +11,39 @@ final class ClassCastLambdaUsageTest {
CompilationTestHelper.newInstance(ClassCastLambdaUsage.class, getClass()) CompilationTestHelper.newInstance(ClassCastLambdaUsage.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableSet;", """
"import java.util.stream.IntStream;", import com.google.common.collect.ImmutableSet;
"import java.util.stream.Stream;", import java.util.stream.IntStream;
"", import java.util.stream.Stream;
"class A {",
" <T> void m() {", class A {
" Number localVariable = 0;", <T> void m() {
"", Number localVariable = 0;
" Stream.of(0).map(i -> i);",
" Stream.of(1).map(i -> i + 1);", Stream.of(0).map(i -> i);
" Stream.of(2).map(Integer.class::cast);", Stream.of(1).map(i -> i + 1);
" Stream.of(3).map(i -> (Integer) 2);", Stream.of(2).map(Integer.class::cast);
" Stream.of(4).map(i -> (Integer) localVariable);", Stream.of(3).map(i -> (Integer) 2);
" // XXX: Ideally this case is also flagged. Pick this up in the context of merging the", Stream.of(4).map(i -> (Integer) localVariable);
" // `ClassCastLambdaUsage` and `MethodReferenceUsage` checks, or introduce a separate check that", // XXX: Ideally this case is also flagged. Pick this up in the context of merging the
" // simplifies unnecessary block lambda expressions.", // `ClassCastLambdaUsage` and `MethodReferenceUsage` checks, or introduce a separate check that
" Stream.of(5)", // simplifies unnecessary block lambda expressions.
" .map(", Stream.of(5)
" i -> {", .map(
" return (Integer) i;", i -> {
" });", return (Integer) i;
" Stream.<ImmutableSet>of(ImmutableSet.of(6)).map(s -> (ImmutableSet<Number>) s);", });
" Stream.of(ImmutableSet.of(7)).map(s -> (ImmutableSet<?>) s);", Stream.<ImmutableSet>of(ImmutableSet.of(6)).map(s -> (ImmutableSet<Number>) s);
" Stream.of(8).reduce((a, b) -> (Integer) a);", Stream.of(ImmutableSet.of(7)).map(s -> (ImmutableSet<?>) s);
" IntStream.of(9).mapToObj(i -> (char) i);", Stream.of(8).reduce((a, b) -> (Integer) a);
" Stream.of(10).map(i -> (T) i);", IntStream.of(9).mapToObj(i -> (char) i);
"", Stream.of(10).map(i -> (T) i);
" // BUG: Diagnostic contains:",
" Stream.of(11).map(i -> (Integer) i);", // BUG: Diagnostic contains:
" }", Stream.of(11).map(i -> (Integer) i);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -50,22 +52,26 @@ final class ClassCastLambdaUsageTest {
BugCheckerRefactoringTestHelper.newInstance(ClassCastLambdaUsage.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(ClassCastLambdaUsage.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import java.util.stream.Stream;", """
"", import java.util.stream.Stream;
"class A {",
" void m() {", class A {
" Stream.of(1).map(i -> (Integer) i);", void m() {
" }", Stream.of(1).map(i -> (Integer) i);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import java.util.stream.Stream;", """
"", import java.util.stream.Stream;
"class A {",
" void m() {", class A {
" Stream.of(1).map(Integer.class::cast);", void m() {
" }", Stream.of(1).map(Integer.class::cast);
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -13,50 +13,52 @@ final class CollectorMutabilityTest {
CompilationTestHelper.newInstance(CollectorMutability.class, getClass()) CompilationTestHelper.newInstance(CollectorMutability.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;", """
"import static com.google.common.collect.ImmutableMap.toImmutableMap;", import static com.google.common.collect.ImmutableList.toImmutableList;
"import static com.google.common.collect.ImmutableSet.toImmutableSet;", import static com.google.common.collect.ImmutableMap.toImmutableMap;
"import static java.util.stream.Collectors.toCollection;", import static com.google.common.collect.ImmutableSet.toImmutableSet;
"import static java.util.stream.Collectors.toList;", import static java.util.stream.Collectors.toCollection;
"import static java.util.stream.Collectors.toMap;", import static java.util.stream.Collectors.toList;
"import static java.util.stream.Collectors.toSet;", import static java.util.stream.Collectors.toMap;
"", import static java.util.stream.Collectors.toSet;
"import java.util.ArrayList;",
"import java.util.HashMap;", import java.util.ArrayList;
"import java.util.HashSet;", import java.util.HashMap;
"import java.util.stream.Collectors;", import java.util.HashSet;
"import java.util.stream.Stream;", import java.util.stream.Collectors;
"import reactor.core.publisher.Flux;", import java.util.stream.Stream;
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" // BUG: Diagnostic contains:", void m() {
" Flux.just(1).collect(Collectors.toList());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).collect(Collectors.toList());
" Flux.just(2).collect(toList());", // BUG: Diagnostic contains:
" Flux.just(3).collect(toImmutableList());", Flux.just(2).collect(toList());
" Flux.just(4).collect(toCollection(ArrayList::new));", Flux.just(3).collect(toImmutableList());
"", Flux.just(4).collect(toCollection(ArrayList::new));
" // BUG: Diagnostic contains:",
" Flux.just(\"foo\").collect(Collectors.toMap(String::getBytes, String::length));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just("foo").collect(Collectors.toMap(String::getBytes, String::length));
" Flux.just(\"bar\").collect(toMap(String::getBytes, String::length));", // BUG: Diagnostic contains:
" Flux.just(\"baz\").collect(toImmutableMap(String::getBytes, String::length));", Flux.just("bar").collect(toMap(String::getBytes, String::length));
" // BUG: Diagnostic contains:", Flux.just("baz").collect(toImmutableMap(String::getBytes, String::length));
" Flux.just(\"qux\").collect(toMap(String::getBytes, String::length, (a, b) -> a));", // BUG: Diagnostic contains:
" Flux.just(\"quux\").collect(toImmutableMap(String::getBytes, String::length, (a, b) -> a));", Flux.just("qux").collect(toMap(String::getBytes, String::length, (a, b) -> a));
" Flux.just(\"quuz\").collect(toMap(String::getBytes, String::length, (a, b) -> a, HashMap::new));", Flux.just("quux").collect(toImmutableMap(String::getBytes, String::length, (a, b) -> a));
"", Flux.just("quuz").collect(toMap(String::getBytes, String::length, (a, b) -> a, HashMap::new));
" // BUG: Diagnostic contains:",
" Stream.of(1).collect(Collectors.toSet());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Stream.of(1).collect(Collectors.toSet());
" Stream.of(2).collect(toSet());", // BUG: Diagnostic contains:
" Stream.of(3).collect(toImmutableSet());", Stream.of(2).collect(toSet());
" Stream.of(4).collect(toCollection(HashSet::new));", Stream.of(3).collect(toImmutableSet());
"", Stream.of(4).collect(toCollection(HashSet::new));
" Flux.just(\"foo\").collect(Collectors.joining());",
" }", Flux.just("foo").collect(Collectors.joining());
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -66,14 +68,16 @@ final class CollectorMutabilityTest {
.withClasspath() .withClasspath()
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.stream.Collectors;", """
"import java.util.stream.Stream;", import java.util.stream.Collectors;
"", import java.util.stream.Stream;
"class A {",
" void m() {", class A {
" Stream.empty().collect(Collectors.toList());", void m() {
" }", Stream.empty().collect(Collectors.toList());
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -82,55 +86,59 @@ final class CollectorMutabilityTest {
BugCheckerRefactoringTestHelper.newInstance(CollectorMutability.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(CollectorMutability.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static java.util.stream.Collectors.toList;", """
"import static java.util.stream.Collectors.toMap;", import static java.util.stream.Collectors.toList;
"import static java.util.stream.Collectors.toSet;", import static java.util.stream.Collectors.toMap;
"", import static java.util.stream.Collectors.toSet;
"import java.util.stream.Collectors;",
"import java.util.stream.Stream;", import java.util.stream.Collectors;
"import reactor.core.publisher.Flux;", import java.util.stream.Stream;
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Flux.just(1).collect(Collectors.toList());", void m() {
" Flux.just(2).collect(toList());", Flux.just(1).collect(Collectors.toList());
"", Flux.just(2).collect(toList());
" Stream.of(\"foo\").collect(Collectors.toMap(String::getBytes, String::length));",
" Stream.of(\"bar\").collect(toMap(String::getBytes, String::length));", Stream.of("foo").collect(Collectors.toMap(String::getBytes, String::length));
" Flux.just(\"baz\").collect(Collectors.toMap(String::getBytes, String::length, (a, b) -> b));", Stream.of("bar").collect(toMap(String::getBytes, String::length));
" Flux.just(\"qux\").collect(toMap(String::getBytes, String::length, (a, b) -> b));", Flux.just("baz").collect(Collectors.toMap(String::getBytes, String::length, (a, b) -> b));
"", Flux.just("qux").collect(toMap(String::getBytes, String::length, (a, b) -> b));
" Stream.of(1).collect(Collectors.toSet());",
" Stream.of(2).collect(toSet());", Stream.of(1).collect(Collectors.toSet());
" }", Stream.of(2).collect(toSet());
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;", """
"import static com.google.common.collect.ImmutableMap.toImmutableMap;", import static com.google.common.collect.ImmutableList.toImmutableList;
"import static com.google.common.collect.ImmutableSet.toImmutableSet;", import static com.google.common.collect.ImmutableMap.toImmutableMap;
"import static java.util.stream.Collectors.toList;", import static com.google.common.collect.ImmutableSet.toImmutableSet;
"import static java.util.stream.Collectors.toMap;", import static java.util.stream.Collectors.toList;
"import static java.util.stream.Collectors.toSet;", import static java.util.stream.Collectors.toMap;
"", import static java.util.stream.Collectors.toSet;
"import java.util.stream.Collectors;",
"import java.util.stream.Stream;", import java.util.stream.Collectors;
"import reactor.core.publisher.Flux;", import java.util.stream.Stream;
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Flux.just(1).collect(toImmutableList());", void m() {
" Flux.just(2).collect(toImmutableList());", Flux.just(1).collect(toImmutableList());
"", Flux.just(2).collect(toImmutableList());
" Stream.of(\"foo\").collect(toImmutableMap(String::getBytes, String::length));",
" Stream.of(\"bar\").collect(toImmutableMap(String::getBytes, String::length));", Stream.of("foo").collect(toImmutableMap(String::getBytes, String::length));
" Flux.just(\"baz\").collect(toImmutableMap(String::getBytes, String::length, (a, b) -> b));", Stream.of("bar").collect(toImmutableMap(String::getBytes, String::length));
" Flux.just(\"qux\").collect(toImmutableMap(String::getBytes, String::length, (a, b) -> b));", Flux.just("baz").collect(toImmutableMap(String::getBytes, String::length, (a, b) -> b));
"", Flux.just("qux").collect(toImmutableMap(String::getBytes, String::length, (a, b) -> b));
" Stream.of(1).collect(toImmutableSet());",
" Stream.of(2).collect(toImmutableSet());", Stream.of(1).collect(toImmutableSet());
" }", Stream.of(2).collect(toImmutableSet());
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -140,73 +148,77 @@ final class CollectorMutabilityTest {
.setFixChooser(SECOND) .setFixChooser(SECOND)
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static java.util.stream.Collectors.toList;", """
"import static java.util.stream.Collectors.toMap;", import static java.util.stream.Collectors.toList;
"import static java.util.stream.Collectors.toSet;", import static java.util.stream.Collectors.toMap;
"", import static java.util.stream.Collectors.toSet;
"import java.util.stream.Collectors;",
"import java.util.stream.Stream;", import java.util.stream.Collectors;
"import reactor.core.publisher.Flux;", import java.util.stream.Stream;
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Flux.just(1).collect(Collectors.toList());", void m() {
" Flux.just(2).collect(toList());", Flux.just(1).collect(Collectors.toList());
"", Flux.just(2).collect(toList());
" Stream.of(\"foo\").collect(Collectors.toMap(String::getBytes, String::length));",
" Stream.of(\"bar\").collect(toMap(String::getBytes, String::length));", Stream.of("foo").collect(Collectors.toMap(String::getBytes, String::length));
" Flux.just(\"baz\").collect(Collectors.toMap(String::getBytes, String::length, (a, b) -> b));", Stream.of("bar").collect(toMap(String::getBytes, String::length));
" Flux.just(\"qux\").collect(toMap(String::getBytes, String::length, (a, b) -> b));", Flux.just("baz").collect(Collectors.toMap(String::getBytes, String::length, (a, b) -> b));
"", Flux.just("qux").collect(toMap(String::getBytes, String::length, (a, b) -> b));
" Stream.of(1).collect(Collectors.toSet());",
" Stream.of(2).collect(toSet());", Stream.of(1).collect(Collectors.toSet());
" }", Stream.of(2).collect(toSet());
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static java.util.stream.Collectors.toCollection;", """
"import static java.util.stream.Collectors.toList;", import static java.util.stream.Collectors.toCollection;
"import static java.util.stream.Collectors.toMap;", import static java.util.stream.Collectors.toList;
"import static java.util.stream.Collectors.toSet;", import static java.util.stream.Collectors.toMap;
"", import static java.util.stream.Collectors.toSet;
"import java.util.ArrayList;",
"import java.util.HashMap;", import java.util.ArrayList;
"import java.util.HashSet;", import java.util.HashMap;
"import java.util.stream.Collectors;", import java.util.HashSet;
"import java.util.stream.Stream;", import java.util.stream.Collectors;
"import reactor.core.publisher.Flux;", import java.util.stream.Stream;
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Flux.just(1).collect(toCollection(ArrayList::new));", void m() {
" Flux.just(2).collect(toCollection(ArrayList::new));", Flux.just(1).collect(toCollection(ArrayList::new));
"", Flux.just(2).collect(toCollection(ArrayList::new));
" Stream.of(\"foo\")",
" .collect(", Stream.of("foo")
" Collectors.toMap(", .collect(
" String::getBytes,", Collectors.toMap(
" String::length,", String::getBytes,
" (a, b) -> {", String::length,
" throw new IllegalStateException();", (a, b) -> {
" },", throw new IllegalStateException();
" HashMap::new));", },
" Stream.of(\"bar\")", HashMap::new));
" .collect(", Stream.of("bar")
" toMap(", .collect(
" String::getBytes,", toMap(
" String::length,", String::getBytes,
" (a, b) -> {", String::length,
" throw new IllegalStateException();", (a, b) -> {
" },", throw new IllegalStateException();
" HashMap::new));", },
" Flux.just(\"baz\")", HashMap::new));
" .collect(Collectors.toMap(String::getBytes, String::length, (a, b) -> b, HashMap::new));", Flux.just("baz")
" Flux.just(\"qux\").collect(toMap(String::getBytes, String::length, (a, b) -> b, HashMap::new));", .collect(Collectors.toMap(String::getBytes, String::length, (a, b) -> b, HashMap::new));
"", Flux.just("qux").collect(toMap(String::getBytes, String::length, (a, b) -> b, HashMap::new));
" Stream.of(1).collect(toCollection(HashSet::new));",
" Stream.of(2).collect(toCollection(HashSet::new));", Stream.of(1).collect(toCollection(HashSet::new));
" }", Stream.of(2).collect(toCollection(HashSet::new));
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,30 +11,32 @@ final class ConstantNamingTest {
CompilationTestHelper.newInstance(ConstantNaming.class, getClass()) CompilationTestHelper.newInstance(ConstantNaming.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" private static final long serialVersionUID = 1L;", class A {
" private static final int FOO = 1;", private static final long serialVersionUID = 1L;
" // BUG: Diagnostic contains: consider renaming to 'BAR', though note that this is not a private", private static final int FOO = 1;
" // constant", // BUG: Diagnostic contains: consider renaming to 'BAR', though note that this is not a private
" static final int bar = 2;", // constant
" // BUG: Diagnostic contains:", static final int bar = 2;
" private static final int baz = 3;", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains: consider renaming to 'QUX_QUUX', though note that a variable with", private static final int baz = 3;
" // this name is already declared", // BUG: Diagnostic contains: consider renaming to 'QUX_QUUX', though note that a variable with
" private static final int qux_QUUX = 4;", // this name is already declared
" // BUG: Diagnostic contains: consider renaming to 'QUUZ', though note that a variable with", private static final int qux_QUUX = 4;
" // this name is already declared", // BUG: Diagnostic contains: consider renaming to 'QUUZ', though note that a variable with
" private static final int quuz = 3;", // this name is already declared
"", private static final int quuz = 3;
" private final int foo = 4;",
" private final Runnable QUX_QUUX =", private final int foo = 4;
" new Runnable() {", private final Runnable QUX_QUUX =
" private static final int QUUZ = 1;", new Runnable() {
"", private static final int QUUZ = 1;
" @Override",
" public void run() {}", @Override
" };", public void run() {}
"}") };
}
""")
.doTest(); .doTest();
} }
@@ -44,13 +46,15 @@ final class ConstantNamingTest {
.setArgs("-XepOpt:CanonicalConstantNaming:ExemptedNames=foo,baz") .setArgs("-XepOpt:CanonicalConstantNaming:ExemptedNames=foo,baz")
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" private static final long serialVersionUID = 1L;", class A {
" private static final int foo = 1;", private static final long serialVersionUID = 1L;
" // BUG: Diagnostic contains:", private static final int foo = 1;
" private static final int bar = 2;", // BUG: Diagnostic contains:
" private static final int baz = 3;", private static final int bar = 2;
"}") private static final int baz = 3;
}
""")
.doTest(); .doTest();
} }
@@ -59,20 +63,24 @@ final class ConstantNamingTest {
BugCheckerRefactoringTestHelper.newInstance(ConstantNaming.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(ConstantNaming.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"class A {", """
" static final int foo = 1;", class A {
" private static final int bar = 2;", static final int foo = 1;
" private static final int baz = 3;", private static final int bar = 2;
" private static final int BAZ = 4;", private static final int baz = 3;
"}") private static final int BAZ = 4;
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"class A {", """
" static final int foo = 1;", class A {
" private static final int BAR = 2;", static final int foo = 1;
" private static final int baz = 3;", private static final int BAR = 2;
" private static final int BAZ = 4;", private static final int baz = 3;
"}") private static final int BAZ = 4;
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,184 +11,186 @@ final class DirectReturnTest {
CompilationTestHelper.newInstance(DirectReturn.class, getClass()) CompilationTestHelper.newInstance(DirectReturn.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static org.mockito.Mockito.mock;", """
"import static org.mockito.Mockito.spy;", import static org.mockito.Mockito.mock;
"", import static org.mockito.Mockito.spy;
"import java.util.function.Supplier;",
"", import java.util.function.Supplier;
"class A {",
" private String field;", class A {
"", private String field;
" void emptyMethod() {}",
"", void emptyMethod() {}
" void voidMethod() {",
" toString();", void voidMethod() {
" return;", toString();
" }", return;
"", }
" String directReturnOfParam(String param) {",
" return param;", String directReturnOfParam(String param) {
" }", return param;
"", }
" String assignmentToField() {",
" field = toString();", String assignmentToField() {
" return field;", field = toString();
" }", return field;
"", }
" Object redundantAssignmentToParam(String param) {",
" // BUG: Diagnostic contains:", Object redundantAssignmentToParam(String param) {
" param = toString();", // BUG: Diagnostic contains:
" return param;", param = toString();
" }", return param;
"", }
" String redundantMockAssignmentToParam(String param) {",
" // BUG: Diagnostic contains:", String redundantMockAssignmentToParam(String param) {
" param = mock();", // BUG: Diagnostic contains:
" return param;", param = mock();
" }", return param;
"", }
" Object redundantMockWithExplicitTypeAssignmentToParam(String param) {",
" // BUG: Diagnostic contains:", Object redundantMockWithExplicitTypeAssignmentToParam(String param) {
" param = mock(String.class);", // BUG: Diagnostic contains:
" return param;", param = mock(String.class);
" }", return param;
"", }
" Object salientMockAssignmentToParam(String param) {",
" param = mock();", Object salientMockAssignmentToParam(String param) {
" return param;", param = mock();
" }", return param;
"", }
" String redundantAssignmentToLocalVariable() {",
" String variable = null;", String redundantAssignmentToLocalVariable() {
" // BUG: Diagnostic contains:", String variable = null;
" variable = toString();", // BUG: Diagnostic contains:
" return variable;", variable = toString();
" }", return variable;
"", }
" String unusedAssignmentToLocalVariable(String param) {",
" String variable = null;", String unusedAssignmentToLocalVariable(String param) {
" variable = toString();", String variable = null;
" return param;", variable = toString();
" }", return param;
"", }
" String redundantVariableDeclaration() {",
" // BUG: Diagnostic contains:", String redundantVariableDeclaration() {
" String variable = toString();", // BUG: Diagnostic contains:
" return variable;", String variable = toString();
" }", return variable;
"", }
" String redundantSpyVariableDeclaration() {",
" // BUG: Diagnostic contains:", String redundantSpyVariableDeclaration() {
" String variable = spy();", // BUG: Diagnostic contains:
" return variable;", String variable = spy();
" }", return variable;
"", }
" Object redundantSpyWithExplicitTypeVariableDeclaration() {",
" // BUG: Diagnostic contains:", Object redundantSpyWithExplicitTypeVariableDeclaration() {
" String variable = spy(String.class);", // BUG: Diagnostic contains:
" return variable;", String variable = spy(String.class);
" }", return variable;
"", }
" Object salientSpyTypeVariableDeclaration() {",
" String variable = spy(\"name\");", Object salientSpyTypeVariableDeclaration() {
" return variable;", String variable = spy("name");
" }", return variable;
"", }
" String unusedVariableDeclaration(String param) {",
" String variable = toString();", String unusedVariableDeclaration(String param) {
" return param;", String variable = toString();
" }", return param;
"", }
" String assignmentToAnnotatedVariable() {",
" @SuppressWarnings(\"HereBeDragons\")", String assignmentToAnnotatedVariable() {
" String variable = toString();", @SuppressWarnings("HereBeDragons")
" return variable;", String variable = toString();
" }", return variable;
"", }
" String complexReturnStatement() {",
" String variable = toString();", String complexReturnStatement() {
" return variable + toString();", String variable = toString();
" }", return variable + toString();
"", }
" String assignmentInsideIfClause() {",
" String variable = null;", String assignmentInsideIfClause() {
" if (true) {", String variable = null;
" variable = toString();", if (true) {
" }", variable = toString();
" return variable;", }
" }", return variable;
"", }
" String redundantAssignmentInsideElseClause() {",
" String variable = toString();", String redundantAssignmentInsideElseClause() {
" if (true) {", String variable = toString();
" return variable;", if (true) {
" } else {", return variable;
" // BUG: Diagnostic contains:", } else {
" variable = \"foo\";", // BUG: Diagnostic contains:
" return variable;", variable = "foo";
" }", return variable;
" }", }
"", }
" Supplier<String> redundantAssignmentInsideLambda() {",
" return () -> {", Supplier<String> redundantAssignmentInsideLambda() {
" // BUG: Diagnostic contains:", return () -> {
" String variable = toString();", // BUG: Diagnostic contains:
" return variable;", String variable = toString();
" };", return variable;
" }", };
"", }
" String redundantAssignmentInsideTryBlock(AutoCloseable closeable) throws Exception {",
" try (closeable) {", String redundantAssignmentInsideTryBlock(AutoCloseable closeable) throws Exception {
" // BUG: Diagnostic contains:", try (closeable) {
" String variable = toString();", // BUG: Diagnostic contains:
" return variable;", String variable = toString();
" }", return variable;
" }", }
"", }
" String redundantAssignmentsInsideTryAndFinallyBlocks() {",
" String variable = toString();", String redundantAssignmentsInsideTryAndFinallyBlocks() {
" try {", String variable = toString();
" // BUG: Diagnostic contains:", try {
" variable = \"foo\";", // BUG: Diagnostic contains:
" return variable;", variable = "foo";
" } finally {", return variable;
" String variable2 = toString();", } finally {
" if (true) {", String variable2 = toString();
" // BUG: Diagnostic contains:", if (true) {
" String variable3 = toString();", // BUG: Diagnostic contains:
" return variable3;", String variable3 = toString();
" }", return variable3;
" return variable2;", }
" }", return variable2;
" }", }
"", }
" String assignmentUsedInsideFinallyBlock() {",
" String variable = toString();", String assignmentUsedInsideFinallyBlock() {
" try {", String variable = toString();
" variable = \"foo\";", try {
" return variable;", variable = "foo";
" } finally {", return variable;
" String variable2 = toString();", } finally {
" return variable + variable2;", String variable2 = toString();
" }", return variable + variable2;
" }", }
"", }
" String redundantAssignmentToVariableUsedInsideUnexecutedFinallyBlock(AutoCloseable closeable)",
" throws Exception {", String redundantAssignmentToVariableUsedInsideUnexecutedFinallyBlock(AutoCloseable closeable)
" String variable = toString();", throws Exception {
" try (closeable) {", String variable = toString();
" if (true) {", try (closeable) {
" // BUG: Diagnostic contains:", if (true) {
" variable = \"foo\";", // BUG: Diagnostic contains:
" return variable;", variable = "foo";
" }", return variable;
" }", }
" try {", }
" } finally {", try {
" return variable;", } finally {
" }", return variable;
" }", }
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -197,30 +199,34 @@ final class DirectReturnTest {
BugCheckerRefactoringTestHelper.newInstance(DirectReturn.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(DirectReturn.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"class A {", """
" String m1() {", class A {
" String variable = null;", String m1() {
" variable = toString();", String variable = null;
" return variable;", variable = toString();
" }", return variable;
"", }
" String m2() {",
" String variable = toString();", String m2() {
" return variable;", String variable = toString();
" }", return variable;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"class A {", """
" String m1() {", class A {
" String variable = null;", String m1() {
" return toString();", String variable = null;
" }", return toString();
"", }
" String m2() {",
" return toString();", String m2() {
" }", return toString();
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,54 +11,58 @@ final class EmptyMethodTest {
CompilationTestHelper.newInstance(EmptyMethod.class, getClass()) CompilationTestHelper.newInstance(EmptyMethod.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" Object m1() {", class A {
" return null;", Object m1() {
" }", return null;
"", }
" void m2() {",
" System.out.println(42);", void m2() {
" }", System.out.println(42);
"", }
" void m3() {}",
"", void m3() {}
" // BUG: Diagnostic contains:",
" static void m4() {}", // BUG: Diagnostic contains:
"", static void m4() {}
" interface F {",
" void fun();", interface F {
" }", void fun();
"", }
" final class MyTestClass {",
" void helperMethod() {}", final class MyTestClass {
" }", void helperMethod() {}
"}") }
}
""")
.addSourceLines( .addSourceLines(
"B.java", "B.java",
"import org.aspectj.lang.annotation.Pointcut;", """
"", import org.aspectj.lang.annotation.Pointcut;
"final class B implements A.F {",
" @Override", final class B implements A.F {
" public void fun() {}", @Override
"", public void fun() {}
" // BUG: Diagnostic contains:",
" void m3() {}", // BUG: Diagnostic contains:
"", void m3() {}
" /** Javadoc. */",
" // BUG: Diagnostic contains:", /** Javadoc. */
" void m4() {}", // BUG: Diagnostic contains:
"", void m4() {}
" void m5() {",
" // Single-line comment.", void m5() {
" }", // Single-line comment.
"", }
" void m6() {",
" /* Multi-line comment. */", void m6() {
" }", /* Multi-line comment. */
"", }
" @Pointcut",
" void m7() {}", @Pointcut
"}") void m7() {}
}
""")
.doTest(); .doTest();
} }
@@ -67,22 +71,26 @@ final class EmptyMethodTest {
BugCheckerRefactoringTestHelper.newInstance(EmptyMethod.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(EmptyMethod.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"final class A {", """
" void instanceMethod() {}", final class A {
"", void instanceMethod() {}
" static void staticMethod() {}",
"", static void staticMethod() {}
" static void staticMethodWithComment() {",
" /* Foo. */", static void staticMethodWithComment() {
" }", /* Foo. */
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"final class A {", """
" static void staticMethodWithComment() {", final class A {
" /* Foo. */", static void staticMethodWithComment() {
" }", /* Foo. */
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -19,62 +19,64 @@ final class EmptyMonoZipTest {
"Invoking `Mono#zipWith` on `Mono#empty()` or a `Mono<Void>` is a no-op")) "Invoking `Mono#zipWith` on `Mono#empty()` or a `Mono<Void>` is a no-op"))
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static reactor.core.publisher.Mono.zip;", """
"", import static reactor.core.publisher.Mono.zip;
"import reactor.core.publisher.Flux;",
"import reactor.core.publisher.Mono;", import reactor.core.publisher.Flux;
"", import reactor.core.publisher.Mono;
"class A {",
" void m() {", class A {
" Flux.just(1).zip(Mono.empty(), Flux.just(2));", void m() {
"", Flux.just(1).zip(Mono.empty(), Flux.just(2));
" Mono<Void> voidMono = Mono.empty();",
" Mono<Integer> integerMono = Mono.empty();", Mono<Void> voidMono = Mono.empty();
"", Mono<Integer> integerMono = Mono.empty();
" zip(Mono.just(1), Mono.just(2));",
" Mono.zip(Mono.just(1), Mono.just(2));", zip(Mono.just(1), Mono.just(2));
" Mono.zip(Mono.just(1), Mono.just(2), Mono.just(3));", Mono.zip(Mono.just(1), Mono.just(2));
" Mono.zip(integerMono, integerMono);", Mono.zip(Mono.just(1), Mono.just(2), Mono.just(3));
"", Mono.zip(integerMono, integerMono);
" // BUG: Diagnostic matches: ARGUMENT",
" zip(Mono.empty(), Mono.empty());", // BUG: Diagnostic matches: ARGUMENT
" // BUG: Diagnostic matches: ARGUMENT", zip(Mono.empty(), Mono.empty());
" Mono.zip(Mono.empty(), Mono.empty());", // BUG: Diagnostic matches: ARGUMENT
" // BUG: Diagnostic matches: ARGUMENT", Mono.zip(Mono.empty(), Mono.empty());
" Mono.zip(voidMono, Mono.just(1));", // BUG: Diagnostic matches: ARGUMENT
" // BUG: Diagnostic matches: ARGUMENT", Mono.zip(voidMono, Mono.just(1));
" Mono.zip(voidMono, voidMono);", // BUG: Diagnostic matches: ARGUMENT
" // BUG: Diagnostic matches: ARGUMENT", Mono.zip(voidMono, voidMono);
" Mono.zip(Mono.just(1).then(), Mono.just(2));", // BUG: Diagnostic matches: ARGUMENT
" // BUG: Diagnostic matches: ARGUMENT", Mono.zip(Mono.just(1).then(), Mono.just(2));
" Mono.zip(Mono.just(1), Mono.just(2), voidMono);", // BUG: Diagnostic matches: ARGUMENT
"", Mono.zip(Mono.just(1), Mono.just(2), voidMono);
" Mono.just(1).zipWith(Mono.just(2));",
" Mono.just(1).zipWith(integerMono);", Mono.just(1).zipWith(Mono.just(2));
" Mono.just(1).zipWith(integerMono, (a, b) -> a + b);", Mono.just(1).zipWith(integerMono);
"", Mono.just(1).zipWith(integerMono, (a, b) -> a + b);
" // BUG: Diagnostic matches: ARGUMENT",
" Mono.just(1).zipWith(Mono.empty());", // BUG: Diagnostic matches: ARGUMENT
" // BUG: Diagnostic matches: ARGUMENT", Mono.just(1).zipWith(Mono.empty());
" Mono.just(1).zipWith(voidMono);", // BUG: Diagnostic matches: ARGUMENT
" // BUG: Diagnostic matches: RECEIVER", Mono.just(1).zipWith(voidMono);
" Mono.empty().zipWith(Mono.just(1));", // BUG: Diagnostic matches: RECEIVER
" // BUG: Diagnostic matches: RECEIVER", Mono.empty().zipWith(Mono.just(1));
" voidMono.zipWith(Mono.just(1));", // BUG: Diagnostic matches: RECEIVER
" }", voidMono.zipWith(Mono.just(1));
"", }
" abstract class MyMono extends Mono<Object> {",
" void m() {", abstract class MyMono extends Mono<Object> {
" zip(Mono.just(1), Mono.just(2));", void m() {
" // BUG: Diagnostic matches: ARGUMENT", zip(Mono.just(1), Mono.just(2));
" zip(Mono.empty(), Mono.empty());", // BUG: Diagnostic matches: ARGUMENT
"", zip(Mono.empty(), Mono.empty());
" zipWith(Mono.just(1));",
" // BUG: Diagnostic matches: ARGUMENT", zipWith(Mono.just(1));
" zipWith(Mono.empty());", // BUG: Diagnostic matches: ARGUMENT
" }", zipWith(Mono.empty());
" }", }
"}") }
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -11,78 +11,80 @@ final class ExplicitArgumentEnumerationTest {
CompilationTestHelper.newInstance(ExplicitArgumentEnumeration.class, getClass()) CompilationTestHelper.newInstance(ExplicitArgumentEnumeration.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static org.assertj.core.api.Assertions.assertThat;", """
"", import static org.assertj.core.api.Assertions.assertThat;
"import com.google.common.collect.ImmutableList;",
"import com.google.errorprone.CompilationTestHelper;", import com.google.common.collect.ImmutableList;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"import org.jooq.impl.DSL;", import com.google.errorprone.bugpatterns.BugChecker;
"import reactor.core.publisher.Flux;", import org.jooq.impl.DSL;
"import reactor.test.StepVerifier;", import reactor.core.publisher.Flux;
"", import reactor.test.StepVerifier;
"class A {",
" // BUG: Diagnostic contains:", class A {
" private final int value = unaryMethod(ImmutableList.of(1, 2));", // BUG: Diagnostic contains:
"", private final int value = unaryMethod(ImmutableList.of(1, 2));
" void m() {",
" ImmutableList<String> list = ImmutableList.of();", void m() {
" assertThat(ImmutableList.of()).containsAnyElementsOf(list);", ImmutableList<String> list = ImmutableList.of();
"", assertThat(ImmutableList.of()).containsAnyElementsOf(list);
" ImmutableList.<ImmutableList<String>>builder().add(ImmutableList.of());",
"", ImmutableList.<ImmutableList<String>>builder().add(ImmutableList.of());
" DSL.row(ImmutableList.of(1, 2));",
"", DSL.row(ImmutableList.of(1, 2));
" // BUG: Diagnostic contains:",
" unaryMethod(ImmutableList.of(1, 2));", // BUG: Diagnostic contains:
" unaryMethodWithLessVisibleOverload(ImmutableList.of(1, 2));", unaryMethod(ImmutableList.of(1, 2));
" binaryMethod(ImmutableList.of(1, 2), 3);", unaryMethodWithLessVisibleOverload(ImmutableList.of(1, 2));
"", binaryMethod(ImmutableList.of(1, 2), 3);
" ImmutableList.builder()",
" // BUG: Diagnostic contains:", ImmutableList.builder()
" .addAll(ImmutableList.of())", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", .addAll(ImmutableList.of())
" .addAll(ImmutableList.copyOf(new String[0]))", // BUG: Diagnostic contains:
" .addAll(ImmutableList.copyOf(ImmutableList.of()))", .addAll(ImmutableList.copyOf(new String[0]))
" .build();", .addAll(ImmutableList.copyOf(ImmutableList.of()))
"", .build();
" assertThat(ImmutableList.of(1))",
" // BUG: Diagnostic contains:", assertThat(ImmutableList.of(1))
" .containsAnyElementsOf(ImmutableList.of(1))", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", .containsAnyElementsOf(ImmutableList.of(1))
" .isSubsetOf(ImmutableList.of(1));", // BUG: Diagnostic contains:
"", .isSubsetOf(ImmutableList.of(1));
" Flux.just(1, 2)",
" .as(StepVerifier::create)", Flux.just(1, 2)
" // BUG: Diagnostic contains:", .as(StepVerifier::create)
" .expectNextSequence(ImmutableList.of(1, 2))", // BUG: Diagnostic contains:
" .verifyComplete();", .expectNextSequence(ImmutableList.of(1, 2))
"", .verifyComplete();
" CompilationTestHelper.newInstance(BugChecker.class, getClass())",
" // BUG: Diagnostic contains:", CompilationTestHelper.newInstance(BugChecker.class, getClass())
" .setArgs(ImmutableList.of(\"foo\"))", // BUG: Diagnostic contains:
" .withClasspath();", .setArgs(ImmutableList.of("foo"))
" }", .withClasspath();
"", }
" private int unaryMethod(ImmutableList<Integer> args) {",
" return 0;", private int unaryMethod(ImmutableList<Integer> args) {
" }", return 0;
"", }
" private int unaryMethod(Integer... args) {",
" return unaryMethod(ImmutableList.copyOf(args));", private int unaryMethod(Integer... args) {
" }", return unaryMethod(ImmutableList.copyOf(args));
"", }
" void unaryMethodWithLessVisibleOverload(ImmutableList<Integer> args) {}",
"", void unaryMethodWithLessVisibleOverload(ImmutableList<Integer> args) {}
" private void unaryMethodWithLessVisibleOverload(Integer... args) {",
" unaryMethodWithLessVisibleOverload(ImmutableList.copyOf(args));", private void unaryMethodWithLessVisibleOverload(Integer... args) {
" }", unaryMethodWithLessVisibleOverload(ImmutableList.copyOf(args));
"", }
" private void binaryMethod(ImmutableList<Integer> args, int extraArg) {}",
"", private void binaryMethod(ImmutableList<Integer> args, int extraArg) {}
" private void binaryMethod(Integer... args) {",
" binaryMethod(ImmutableList.copyOf(args), 0);", private void binaryMethod(Integer... args) {
" }", binaryMethod(ImmutableList.copyOf(args), 0);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -91,85 +93,89 @@ final class ExplicitArgumentEnumerationTest {
BugCheckerRefactoringTestHelper.newInstance(ExplicitArgumentEnumeration.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(ExplicitArgumentEnumeration.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static org.assertj.core.api.Assertions.assertThat;", """
"", import static org.assertj.core.api.Assertions.assertThat;
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableMultiset;", import com.google.common.collect.ImmutableList;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableMultiset;
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", import com.google.common.collect.ImmutableSet;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"import java.util.Arrays;", import com.google.errorprone.bugpatterns.BugChecker;
"import java.util.List;", import java.util.Arrays;
"import java.util.Set;", import java.util.List;
"import reactor.core.publisher.Flux;", import java.util.Set;
"import reactor.test.StepVerifier;", import reactor.core.publisher.Flux;
"", import reactor.test.StepVerifier;
"class A {",
" void m() {", class A {
" ImmutableList.builder().addAll(ImmutableList.of()).build();", void m() {
"", ImmutableList.builder().addAll(ImmutableList.of()).build();
" assertThat(ImmutableList.of()).containsAnyElementsOf(ImmutableMultiset.of());",
" assertThat(ImmutableList.of()).containsAll(ImmutableSet.of());", assertThat(ImmutableList.of()).containsAnyElementsOf(ImmutableMultiset.of());
" assertThat(ImmutableList.of()).containsExactlyElementsOf(List.of());", assertThat(ImmutableList.of()).containsAll(ImmutableSet.of());
" assertThat(ImmutableList.of()).containsExactlyInAnyOrderElementsOf(Set.of());", assertThat(ImmutableList.of()).containsExactlyElementsOf(List.of());
" assertThat(ImmutableList.of()).containsSequence(Arrays.asList());", assertThat(ImmutableList.of()).containsExactlyInAnyOrderElementsOf(Set.of());
" assertThat(ImmutableList.of()).containsSubsequence(ImmutableList.of(1));", assertThat(ImmutableList.of()).containsSequence(Arrays.asList());
" assertThat(ImmutableList.of()).doesNotContainAnyElementsOf(ImmutableMultiset.of(2));", assertThat(ImmutableList.of()).containsSubsequence(ImmutableList.of(1));
" assertThat(ImmutableList.of()).doesNotContainSequence(ImmutableSet.of(3));", assertThat(ImmutableList.of()).doesNotContainAnyElementsOf(ImmutableMultiset.of(2));
" assertThat(ImmutableList.of()).doesNotContainSubsequence(List.of(4));", assertThat(ImmutableList.of()).doesNotContainSequence(ImmutableSet.of(3));
" assertThat(ImmutableList.of()).hasSameElementsAs(Set.of(5));", assertThat(ImmutableList.of()).doesNotContainSubsequence(List.of(4));
" assertThat(ImmutableList.of()).isSubsetOf(Arrays.asList(6));", assertThat(ImmutableList.of()).hasSameElementsAs(Set.of(5));
"", assertThat(ImmutableList.of()).isSubsetOf(Arrays.asList(6));
" Flux.empty()",
" .as(StepVerifier::create)", Flux.empty()
" .expectNextSequence(ImmutableList.of(1, 2))", .as(StepVerifier::create)
" .verifyComplete();", .expectNextSequence(ImmutableList.of(1, 2))
"", .verifyComplete();
" BugCheckerRefactoringTestHelper.newInstance(BugChecker.class, getClass())",
" .setArgs(ImmutableList.of(\"foo\", \"bar\"));", BugCheckerRefactoringTestHelper.newInstance(BugChecker.class, getClass())
" CompilationTestHelper.newInstance(BugChecker.class, getClass())", .setArgs(ImmutableList.of("foo", "bar"));
" .setArgs(ImmutableList.of(\"foo\", \"bar\"));", CompilationTestHelper.newInstance(BugChecker.class, getClass())
" }", .setArgs(ImmutableList.of("foo", "bar"));
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static org.assertj.core.api.Assertions.assertThat;", """
"", import static org.assertj.core.api.Assertions.assertThat;
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableMultiset;", import com.google.common.collect.ImmutableList;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableMultiset;
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", import com.google.common.collect.ImmutableSet;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.bugpatterns.BugChecker;", import com.google.errorprone.CompilationTestHelper;
"import java.util.Arrays;", import com.google.errorprone.bugpatterns.BugChecker;
"import java.util.List;", import java.util.Arrays;
"import java.util.Set;", import java.util.List;
"import reactor.core.publisher.Flux;", import java.util.Set;
"import reactor.test.StepVerifier;", import reactor.core.publisher.Flux;
"", import reactor.test.StepVerifier;
"class A {",
" void m() {", class A {
" ImmutableList.builder().add().build();", void m() {
"", ImmutableList.builder().add().build();
" assertThat(ImmutableList.of()).containsAnyOf();",
" assertThat(ImmutableList.of()).contains();", assertThat(ImmutableList.of()).containsAnyOf();
" assertThat(ImmutableList.of()).containsExactly();", assertThat(ImmutableList.of()).contains();
" assertThat(ImmutableList.of()).containsExactlyInAnyOrder();", assertThat(ImmutableList.of()).containsExactly();
" assertThat(ImmutableList.of()).containsSequence();", assertThat(ImmutableList.of()).containsExactlyInAnyOrder();
" assertThat(ImmutableList.of()).containsSubsequence(1);", assertThat(ImmutableList.of()).containsSequence();
" assertThat(ImmutableList.of()).doesNotContain(2);", assertThat(ImmutableList.of()).containsSubsequence(1);
" assertThat(ImmutableList.of()).doesNotContainSequence(3);", assertThat(ImmutableList.of()).doesNotContain(2);
" assertThat(ImmutableList.of()).doesNotContainSubsequence(4);", assertThat(ImmutableList.of()).doesNotContainSequence(3);
" assertThat(ImmutableList.of()).containsOnly(5);", assertThat(ImmutableList.of()).doesNotContainSubsequence(4);
" assertThat(ImmutableList.of()).isSubsetOf(6);", assertThat(ImmutableList.of()).containsOnly(5);
"", assertThat(ImmutableList.of()).isSubsetOf(6);
" Flux.empty().as(StepVerifier::create).expectNext(1, 2).verifyComplete();",
"", Flux.empty().as(StepVerifier::create).expectNext(1, 2).verifyComplete();
" BugCheckerRefactoringTestHelper.newInstance(BugChecker.class, getClass()).setArgs(\"foo\", \"bar\");",
" CompilationTestHelper.newInstance(BugChecker.class, getClass()).setArgs(\"foo\", \"bar\");", BugCheckerRefactoringTestHelper.newInstance(BugChecker.class, getClass()).setArgs("foo", "bar");
" }", CompilationTestHelper.newInstance(BugChecker.class, getClass()).setArgs("foo", "bar");
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -9,76 +9,78 @@ final class ExplicitEnumOrderingTest {
CompilationTestHelper.newInstance(ExplicitEnumOrdering.class, getClass()) CompilationTestHelper.newInstance(ExplicitEnumOrdering.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static java.lang.annotation.RetentionPolicy.CLASS;", """
"import static java.lang.annotation.RetentionPolicy.RUNTIME;", import static java.lang.annotation.RetentionPolicy.CLASS;
"import static java.lang.annotation.RetentionPolicy.SOURCE;", import static java.lang.annotation.RetentionPolicy.RUNTIME;
"import static java.time.chrono.IsoEra.BCE;", import static java.lang.annotation.RetentionPolicy.SOURCE;
"import static java.time.chrono.IsoEra.CE;", import static java.time.chrono.IsoEra.BCE;
"", import static java.time.chrono.IsoEra.CE;
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.Ordering;", import com.google.common.collect.ImmutableList;
"import java.lang.annotation.RetentionPolicy;", import com.google.common.collect.Ordering;
"import java.time.chrono.IsoEra;", import java.lang.annotation.RetentionPolicy;
"", import java.time.chrono.IsoEra;
"class A {",
" {", class A {
" // The `List`-accepting overload is currently ignored.", {
" Ordering.explicit(ImmutableList.of(RetentionPolicy.SOURCE, RetentionPolicy.CLASS));", // The `List`-accepting overload is currently ignored.
"", Ordering.explicit(ImmutableList.of(RetentionPolicy.SOURCE, RetentionPolicy.CLASS));
" Ordering.explicit(IsoEra.BCE, IsoEra.CE);",
" // BUG: Diagnostic contains: IsoEra.CE", Ordering.explicit(IsoEra.BCE, IsoEra.CE);
" Ordering.explicit(IsoEra.BCE);", // BUG: Diagnostic contains: IsoEra.CE
" // BUG: Diagnostic contains: IsoEra.BCE", Ordering.explicit(IsoEra.BCE);
" Ordering.explicit(IsoEra.CE);", // BUG: Diagnostic contains: IsoEra.BCE
"", Ordering.explicit(IsoEra.CE);
" Ordering.explicit(RetentionPolicy.SOURCE, RetentionPolicy.CLASS, RetentionPolicy.RUNTIME);",
" // BUG: Diagnostic contains: RetentionPolicy.CLASS, RetentionPolicy.RUNTIME", Ordering.explicit(RetentionPolicy.SOURCE, RetentionPolicy.CLASS, RetentionPolicy.RUNTIME);
" Ordering.explicit(RetentionPolicy.SOURCE);", // BUG: Diagnostic contains: RetentionPolicy.CLASS, RetentionPolicy.RUNTIME
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.RUNTIME", Ordering.explicit(RetentionPolicy.SOURCE);
" Ordering.explicit(RetentionPolicy.CLASS);", // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.RUNTIME
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.CLASS", Ordering.explicit(RetentionPolicy.CLASS);
" Ordering.explicit(RetentionPolicy.RUNTIME);", // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.CLASS
" // BUG: Diagnostic contains: RetentionPolicy.RUNTIME", Ordering.explicit(RetentionPolicy.RUNTIME);
" Ordering.explicit(RetentionPolicy.SOURCE, RetentionPolicy.CLASS);", // BUG: Diagnostic contains: RetentionPolicy.RUNTIME
" // BUG: Diagnostic contains: RetentionPolicy.CLASS", Ordering.explicit(RetentionPolicy.SOURCE, RetentionPolicy.CLASS);
" Ordering.explicit(RetentionPolicy.SOURCE, RetentionPolicy.RUNTIME);", // BUG: Diagnostic contains: RetentionPolicy.CLASS
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE", Ordering.explicit(RetentionPolicy.SOURCE, RetentionPolicy.RUNTIME);
" Ordering.explicit(RetentionPolicy.CLASS, RetentionPolicy.RUNTIME);", // BUG: Diagnostic contains: RetentionPolicy.SOURCE
"", Ordering.explicit(RetentionPolicy.CLASS, RetentionPolicy.RUNTIME);
" Ordering.explicit(BCE, CE);",
" // BUG: Diagnostic contains: IsoEra.CE", Ordering.explicit(BCE, CE);
" Ordering.explicit(BCE);", // BUG: Diagnostic contains: IsoEra.CE
" // BUG: Diagnostic contains: IsoEra.BCE", Ordering.explicit(BCE);
" Ordering.explicit(CE);", // BUG: Diagnostic contains: IsoEra.BCE
"", Ordering.explicit(CE);
" Ordering.explicit(SOURCE, CLASS, RUNTIME);",
" // BUG: Diagnostic contains: RetentionPolicy.CLASS, RetentionPolicy.RUNTIME", Ordering.explicit(SOURCE, CLASS, RUNTIME);
" Ordering.explicit(SOURCE);", // BUG: Diagnostic contains: RetentionPolicy.CLASS, RetentionPolicy.RUNTIME
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.RUNTIME", Ordering.explicit(SOURCE);
" Ordering.explicit(CLASS);", // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.RUNTIME
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.CLASS", Ordering.explicit(CLASS);
" Ordering.explicit(RUNTIME);", // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.CLASS
" // BUG: Diagnostic contains: RetentionPolicy.RUNTIME", Ordering.explicit(RUNTIME);
" Ordering.explicit(SOURCE, CLASS);", // BUG: Diagnostic contains: RetentionPolicy.RUNTIME
" // BUG: Diagnostic contains: RetentionPolicy.CLASS", Ordering.explicit(SOURCE, CLASS);
" Ordering.explicit(SOURCE, RUNTIME);", // BUG: Diagnostic contains: RetentionPolicy.CLASS
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE", Ordering.explicit(SOURCE, RUNTIME);
" Ordering.explicit(CLASS, RUNTIME);", // BUG: Diagnostic contains: RetentionPolicy.SOURCE
"", Ordering.explicit(CLASS, RUNTIME);
" Ordering.explicit(RetentionPolicy.SOURCE, BCE, RetentionPolicy.CLASS, CE, RUNTIME);",
" Ordering.explicit(SOURCE, IsoEra.BCE, CLASS, IsoEra.CE, RetentionPolicy.RUNTIME);", Ordering.explicit(RetentionPolicy.SOURCE, BCE, RetentionPolicy.CLASS, CE, RUNTIME);
" // BUG: Diagnostic contains: RetentionPolicy.CLASS", Ordering.explicit(SOURCE, IsoEra.BCE, CLASS, IsoEra.CE, RetentionPolicy.RUNTIME);
" Ordering.explicit(RetentionPolicy.SOURCE, BCE, CE, RUNTIME);", // BUG: Diagnostic contains: RetentionPolicy.CLASS
" // BUG: Diagnostic contains: RetentionPolicy.CLASS", Ordering.explicit(RetentionPolicy.SOURCE, BCE, CE, RUNTIME);
" Ordering.explicit(IsoEra.BCE, SOURCE, IsoEra.CE, RetentionPolicy.RUNTIME);", // BUG: Diagnostic contains: RetentionPolicy.CLASS
" // BUG: Diagnostic contains: IsoEra.CE, RetentionPolicy.RUNTIME", Ordering.explicit(IsoEra.BCE, SOURCE, IsoEra.CE, RetentionPolicy.RUNTIME);
" Ordering.explicit(IsoEra.BCE, SOURCE, RetentionPolicy.CLASS);", // BUG: Diagnostic contains: IsoEra.CE, RetentionPolicy.RUNTIME
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, IsoEra.BCE", Ordering.explicit(IsoEra.BCE, SOURCE, RetentionPolicy.CLASS);
" Ordering.explicit(CLASS, RUNTIME, CE);", // BUG: Diagnostic contains: RetentionPolicy.SOURCE, IsoEra.BCE
"", Ordering.explicit(CLASS, RUNTIME, CE);
" Ordering.explicit(BCE, null, CE);",
" }", Ordering.explicit(BCE, null, CE);
"}") }
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -12,55 +12,57 @@ final class FluxFlatMapUsageTest {
CompilationTestHelper.newInstance(FluxFlatMapUsage.class, getClass()) CompilationTestHelper.newInstance(FluxFlatMapUsage.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.function.BiFunction;", """
"import java.util.function.Function;", import java.util.function.BiFunction;
"import reactor.core.publisher.Flux;", import java.util.function.Function;
"import reactor.core.publisher.Mono;", import reactor.core.publisher.Flux;
"", import reactor.core.publisher.Mono;
"class A {",
" void m() {", class A {
" // BUG: Diagnostic contains:", void m() {
" Flux.just(1).flatMap(Flux::just);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).flatMap(Flux::just);
" Flux.just(1).<String>flatMap(i -> Flux.just(String.valueOf(i)));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).<String>flatMap(i -> Flux.just(String.valueOf(i)));
" Flux.just(1).flatMapSequential(Flux::just);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).flatMapSequential(Flux::just);
" Flux.just(1).<String>flatMapSequential(i -> Flux.just(String.valueOf(i)));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).<String>flatMapSequential(i -> Flux.just(String.valueOf(i)));
" Flux.just(1, 2).groupBy(i -> i).flatMap(Flux::just);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1, 2).groupBy(i -> i).flatMap(Flux::just);
" Flux.just(1, 2).groupBy(i -> i).<String>flatMap(i -> Flux.just(String.valueOf(i)));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1, 2).groupBy(i -> i).<String>flatMap(i -> Flux.just(String.valueOf(i)));
" Flux.just(1, 2).groupBy(i -> i).flatMapSequential(Flux::just);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1, 2).groupBy(i -> i).flatMapSequential(Flux::just);
" Flux.just(1, 2).groupBy(i -> i).<String>flatMapSequential(i -> Flux.just(String.valueOf(i)));", // BUG: Diagnostic contains:
"", Flux.just(1, 2).groupBy(i -> i).<String>flatMapSequential(i -> Flux.just(String.valueOf(i)));
" Mono.just(1).flatMap(Mono::just);",
" Flux.just(1).concatMap(Flux::just);", Mono.just(1).flatMap(Mono::just);
"", Flux.just(1).concatMap(Flux::just);
" Flux.just(1).flatMap(Flux::just, 1);",
" Flux.just(1).flatMap(Flux::just, 1, 1);", Flux.just(1).flatMap(Flux::just, 1);
" Flux.just(1).flatMap(Flux::just, throwable -> Flux.empty(), Flux::empty);", Flux.just(1).flatMap(Flux::just, 1, 1);
"", Flux.just(1).flatMap(Flux::just, throwable -> Flux.empty(), Flux::empty);
" Flux.just(1).flatMapSequential(Flux::just, 1);",
" Flux.just(1).flatMapSequential(Flux::just, 1, 1);", Flux.just(1).flatMapSequential(Flux::just, 1);
"", Flux.just(1).flatMapSequential(Flux::just, 1, 1);
" // BUG: Diagnostic contains:",
" this.<String, Flux<String>>sink(Flux::flatMap);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", this.<String, Flux<String>>sink(Flux::flatMap);
" this.<Integer, Flux<Integer>>sink(Flux::<Integer>flatMap);", // BUG: Diagnostic contains:
"", this.<Integer, Flux<Integer>>sink(Flux::<Integer>flatMap);
" // BUG: Diagnostic contains:",
" this.<String, Flux<String>>sink(Flux::flatMapSequential);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", this.<String, Flux<String>>sink(Flux::flatMapSequential);
" this.<Integer, Flux<Integer>>sink(Flux::<Integer>flatMapSequential);", // BUG: Diagnostic contains:
"", this.<Integer, Flux<Integer>>sink(Flux::<Integer>flatMapSequential);
" this.<String, Mono<String>>sink(Mono::flatMap);",
" }", this.<String, Mono<String>>sink(Mono::flatMap);
"", }
" private <T, P> void sink(BiFunction<P, Function<T, P>, P> fun) {}",
"}") private <T, P> void sink(BiFunction<P, Function<T, P>, P> fun) {}
}
""")
.doTest(); .doTest();
} }
@@ -69,32 +71,36 @@ final class FluxFlatMapUsageTest {
BugCheckerRefactoringTestHelper.newInstance(FluxFlatMapUsage.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(FluxFlatMapUsage.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import reactor.core.publisher.Flux;", """
"", import reactor.core.publisher.Flux;
"class A {",
" private static final int MAX_CONCURRENCY = 8;", class A {
"", private static final int MAX_CONCURRENCY = 8;
" void m() {",
" Flux.just(1).flatMap(Flux::just);", void m() {
" Flux.just(1).flatMapSequential(Flux::just);", Flux.just(1).flatMap(Flux::just);
" Flux.just(1, 2).groupBy(i -> i).flatMap(Flux::just);", Flux.just(1).flatMapSequential(Flux::just);
" Flux.just(1, 2).groupBy(i -> i).flatMapSequential(Flux::just);", Flux.just(1, 2).groupBy(i -> i).flatMap(Flux::just);
" }", Flux.just(1, 2).groupBy(i -> i).flatMapSequential(Flux::just);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import reactor.core.publisher.Flux;", """
"", import reactor.core.publisher.Flux;
"class A {",
" private static final int MAX_CONCURRENCY = 8;", class A {
"", private static final int MAX_CONCURRENCY = 8;
" void m() {",
" Flux.just(1).concatMap(Flux::just);", void m() {
" Flux.just(1).concatMap(Flux::just);", Flux.just(1).concatMap(Flux::just);
" Flux.just(1, 2).groupBy(i -> i).flatMap(Flux::just, MAX_CONCURRENCY);", Flux.just(1).concatMap(Flux::just);
" Flux.just(1, 2).groupBy(i -> i).flatMapSequential(Flux::just, MAX_CONCURRENCY);", Flux.just(1, 2).groupBy(i -> i).flatMap(Flux::just, MAX_CONCURRENCY);
" }", Flux.just(1, 2).groupBy(i -> i).flatMapSequential(Flux::just, MAX_CONCURRENCY);
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -104,32 +110,36 @@ final class FluxFlatMapUsageTest {
.setFixChooser(FixChoosers.SECOND) .setFixChooser(FixChoosers.SECOND)
.addInputLines( .addInputLines(
"A.java", "A.java",
"import reactor.core.publisher.Flux;", """
"", import reactor.core.publisher.Flux;
"class A {",
" private static final int MAX_CONCURRENCY = 8;", class A {
"", private static final int MAX_CONCURRENCY = 8;
" void m() {",
" Flux.just(1).flatMap(Flux::just);", void m() {
" Flux.just(1).flatMapSequential(Flux::just);", Flux.just(1).flatMap(Flux::just);
" Flux.just(1, 2).groupBy(i -> i).flatMap(Flux::just);", Flux.just(1).flatMapSequential(Flux::just);
" Flux.just(1, 2).groupBy(i -> i).flatMapSequential(Flux::just);", Flux.just(1, 2).groupBy(i -> i).flatMap(Flux::just);
" }", Flux.just(1, 2).groupBy(i -> i).flatMapSequential(Flux::just);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import reactor.core.publisher.Flux;", """
"", import reactor.core.publisher.Flux;
"class A {",
" private static final int MAX_CONCURRENCY = 8;", class A {
"", private static final int MAX_CONCURRENCY = 8;
" void m() {",
" Flux.just(1).flatMap(Flux::just, MAX_CONCURRENCY);", void m() {
" Flux.just(1).flatMapSequential(Flux::just, MAX_CONCURRENCY);", Flux.just(1).flatMap(Flux::just, MAX_CONCURRENCY);
" Flux.just(1, 2).groupBy(i -> i).concatMap(Flux::just);", Flux.just(1).flatMapSequential(Flux::just, MAX_CONCURRENCY);
" Flux.just(1, 2).groupBy(i -> i).concatMap(Flux::just);", Flux.just(1, 2).groupBy(i -> i).concatMap(Flux::just);
" }", Flux.just(1, 2).groupBy(i -> i).concatMap(Flux::just);
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -21,36 +21,38 @@ final class FluxImplicitBlockTest {
m -> Stream.of("SuppressWarnings", "toImmutableList", "toList").allMatch(m::contains)) m -> Stream.of("SuppressWarnings", "toImmutableList", "toList").allMatch(m::contains))
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"import java.util.stream.Stream;", import com.google.common.collect.ImmutableList;
"import reactor.core.publisher.Flux;", import java.util.stream.Stream;
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" // BUG: Diagnostic matches: X", void m() {
" Flux.just(1).toIterable();", // BUG: Diagnostic matches: X
" // BUG: Diagnostic matches: X", Flux.just(1).toIterable();
" Flux.just(2).toStream();", // BUG: Diagnostic matches: X
" // BUG: Diagnostic matches: X", Flux.just(2).toStream();
" long count = Flux.just(3).toStream().count();", // BUG: Diagnostic matches: X
"", long count = Flux.just(3).toStream().count();
" Flux.just(4).toIterable(1);",
" Flux.just(5).toIterable(2, null);", Flux.just(4).toIterable(1);
" Flux.just(6).toStream(3);", Flux.just(5).toIterable(2, null);
" new Foo().toIterable();", Flux.just(6).toStream(3);
" new Foo().toStream();", new Foo().toIterable();
" }", new Foo().toStream();
"", }
" class Foo<T> {",
" Iterable<T> toIterable() {", class Foo<T> {
" return ImmutableList.of();", Iterable<T> toIterable() {
" }", return ImmutableList.of();
"", }
" Stream<T> toStream() {",
" return Stream.empty();", Stream<T> toStream() {
" }", return Stream.empty();
" }", }
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -61,16 +63,18 @@ final class FluxImplicitBlockTest {
.expectErrorMessage("X", m -> !m.contains("toImmutableList")) .expectErrorMessage("X", m -> !m.contains("toImmutableList"))
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import reactor.core.publisher.Flux;", """
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" // BUG: Diagnostic matches: X", void m() {
" Flux.just(1).toIterable();", // BUG: Diagnostic matches: X
" // BUG: Diagnostic matches: X", Flux.just(1).toIterable();
" Flux.just(2).toStream();", // BUG: Diagnostic matches: X
" }", Flux.just(2).toStream();
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -79,25 +83,29 @@ final class FluxImplicitBlockTest {
BugCheckerRefactoringTestHelper.newInstance(FluxImplicitBlock.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(FluxImplicitBlock.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import reactor.core.publisher.Flux;", """
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Flux.just(1).toIterable();", void m() {
" Flux.just(2).toStream();", Flux.just(1).toIterable();
" }", Flux.just(2).toStream();
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import reactor.core.publisher.Flux;", """
"", import reactor.core.publisher.Flux;
"class A {",
" @SuppressWarnings(\"FluxImplicitBlock\")", class A {
" void m() {", @SuppressWarnings("FluxImplicitBlock")
" Flux.just(1).toIterable();", void m() {
" Flux.just(2).toStream();", Flux.just(1).toIterable();
" }", Flux.just(2).toStream();
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -107,34 +115,38 @@ final class FluxImplicitBlockTest {
.setFixChooser(SECOND) .setFixChooser(SECOND)
.addInputLines( .addInputLines(
"A.java", "A.java",
"import reactor.core.publisher.Flux;", """
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Flux.just(1).toIterable();", void m() {
" Flux.just(2).toStream();", Flux.just(1).toIterable();
" Flux.just(3).toIterable().iterator();", Flux.just(2).toStream();
" Flux.just(4).toStream().count();", Flux.just(3).toIterable().iterator();
" Flux.just(5) /* a */./* b */ toIterable /* c */(/* d */ ) /* e */;", Flux.just(4).toStream().count();
" Flux.just(6) /* a */./* b */ toStream /* c */(/* d */ ) /* e */;", Flux.just(5) /* a */./* b */ toIterable /* c */(/* d */ ) /* e */;
" }", Flux.just(6) /* a */./* b */ toStream /* c */(/* d */ ) /* e */;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;", """
"", import static com.google.common.collect.ImmutableList.toImmutableList;
"import reactor.core.publisher.Flux;",
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Flux.just(1).collect(toImmutableList()).block();", void m() {
" Flux.just(2).collect(toImmutableList()).block().stream();", Flux.just(1).collect(toImmutableList()).block();
" Flux.just(3).collect(toImmutableList()).block().iterator();", Flux.just(2).collect(toImmutableList()).block().stream();
" Flux.just(4).collect(toImmutableList()).block().stream().count();", Flux.just(3).collect(toImmutableList()).block().iterator();
" Flux.just(5).collect(toImmutableList()).block() /* e */;", Flux.just(4).collect(toImmutableList()).block().stream().count();
" Flux.just(6).collect(toImmutableList()).block().stream() /* e */;", Flux.just(5).collect(toImmutableList()).block() /* e */;
" }", Flux.just(6).collect(toImmutableList()).block().stream() /* e */;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -144,34 +156,38 @@ final class FluxImplicitBlockTest {
.setFixChooser(THIRD) .setFixChooser(THIRD)
.addInputLines( .addInputLines(
"A.java", "A.java",
"import reactor.core.publisher.Flux;", """
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Flux.just(1).toIterable();", void m() {
" Flux.just(2).toStream();", Flux.just(1).toIterable();
" Flux.just(3).toIterable().iterator();", Flux.just(2).toStream();
" Flux.just(4).toStream().count();", Flux.just(3).toIterable().iterator();
" Flux.just(5) /* a */./* b */ toIterable /* c */(/* d */ ) /* e */;", Flux.just(4).toStream().count();
" Flux.just(6) /* a */./* b */ toStream /* c */(/* d */ ) /* e */;", Flux.just(5) /* a */./* b */ toIterable /* c */(/* d */ ) /* e */;
" }", Flux.just(6) /* a */./* b */ toStream /* c */(/* d */ ) /* e */;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static java.util.stream.Collectors.toList;", """
"", import static java.util.stream.Collectors.toList;
"import reactor.core.publisher.Flux;",
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Flux.just(1).collect(toList()).block();", void m() {
" Flux.just(2).collect(toList()).block().stream();", Flux.just(1).collect(toList()).block();
" Flux.just(3).collect(toList()).block().iterator();", Flux.just(2).collect(toList()).block().stream();
" Flux.just(4).collect(toList()).block().stream().count();", Flux.just(3).collect(toList()).block().iterator();
" Flux.just(5).collect(toList()).block() /* e */;", Flux.just(4).collect(toList()).block().stream().count();
" Flux.just(6).collect(toList()).block().stream() /* e */;", Flux.just(5).collect(toList()).block() /* e */;
" }", Flux.just(6).collect(toList()).block().stream() /* e */;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,294 +11,296 @@ final class FormatStringConcatenationTest {
CompilationTestHelper.newInstance(FormatStringConcatenation.class, getClass()) CompilationTestHelper.newInstance(FormatStringConcatenation.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static com.google.common.base.Preconditions.checkArgument;", """
"import static com.google.common.base.Preconditions.checkNotNull;", import static com.google.common.base.Preconditions.checkArgument;
"import static com.google.common.base.Preconditions.checkState;", import static com.google.common.base.Preconditions.checkNotNull;
"import static com.google.common.base.Verify.verify;", import static com.google.common.base.Preconditions.checkState;
"import static org.assertj.core.api.Assertions.assertThat;", import static com.google.common.base.Verify.verify;
"import static org.assertj.core.api.SoftAssertions.assertSoftly;", import static org.assertj.core.api.Assertions.assertThat;
"", import static org.assertj.core.api.SoftAssertions.assertSoftly;
"import java.util.Formatter;",
"import java.util.Locale;", import java.util.Formatter;
"import org.assertj.core.api.Assertions;", import java.util.Locale;
"import org.assertj.core.api.BDDAssertions;", import org.assertj.core.api.Assertions;
"import org.assertj.core.api.Fail;", import org.assertj.core.api.BDDAssertions;
"import org.assertj.core.api.ThrowableAssertAlternative;", import org.assertj.core.api.Fail;
"import org.assertj.core.api.WithAssertions;", import org.assertj.core.api.ThrowableAssertAlternative;
"import org.slf4j.Logger;", import org.assertj.core.api.WithAssertions;
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"import org.slf4j.Marker;", import org.slf4j.LoggerFactory;
"", import org.slf4j.Marker;
"class A {",
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", class A {
"", private static final Logger LOG = LoggerFactory.getLogger(A.class);
" void negative() {",
" hashCode();", void negative() {
" equals(new A());", hashCode();
" equals(toString());", equals(new A());
" equals(0);", equals(toString());
" equals(\"str\");", equals(0);
" equals(\"str\" + 0);", equals("str");
" equals(0 + 0);", equals("str" + 0);
" equals(0 - 0);", equals(0 + 0);
" equals(\"str \" + toString());", equals(0 - 0);
" }", equals("str " + toString());
"", }
" void assertj() {",
" assertThat(0).overridingErrorMessage(toString());", void assertj() {
" assertThat(0).overridingErrorMessage(\"str\");", assertThat(0).overridingErrorMessage(toString());
" assertThat(0).overridingErrorMessage(\"str \" + 0);", assertThat(0).overridingErrorMessage("str");
" assertThat(0).overridingErrorMessage(\"str %s\", 2 * 3);", assertThat(0).overridingErrorMessage("str " + 0);
" assertThat(0).overridingErrorMessage(\"str %s\", toString());", assertThat(0).overridingErrorMessage("str %s", 2 * 3);
" // BUG: Diagnostic contains:", assertThat(0).overridingErrorMessage("str %s", toString());
" assertThat(0).overridingErrorMessage(\"str \" + hashCode() / 2);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(0).overridingErrorMessage("str " + hashCode() / 2);
" assertThat(0).overridingErrorMessage((\"str \" + toString()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(0).overridingErrorMessage(("str " + toString()));
" assertThat(0).overridingErrorMessage(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(0).overridingErrorMessage("str " + toString());
" assertThat(0).overridingErrorMessage(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(0).overridingErrorMessage("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertThat(0).withFailMessage(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(0).withFailMessage("str " + toString());
" assertThat(0).withFailMessage(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(0).withFailMessage("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertSoftly(softly -> softly.fail(\"str \" + toString()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertSoftly(softly -> softly.fail("str " + toString()));
" assertSoftly(softly -> softly.fail(\"%s \" + toString(), \"arg\"));", // BUG: Diagnostic contains:
" assertSoftly(softly -> softly.fail(\"str \" + toString(), new Throwable()));", assertSoftly(softly -> softly.fail("%s " + toString(), "arg"));
"", assertSoftly(softly -> softly.fail("str " + toString(), new Throwable()));
" // BUG: Diagnostic contains:",
" assertThat(\"\").isEqualTo(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat("").isEqualTo("str " + toString());
" assertThat(\"\").isEqualTo(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat("").isEqualTo("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertThat(new Error()).hasMessage(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(new Error()).hasMessage("str " + toString());
" assertThat(new Error()).hasMessage(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(new Error()).hasMessage("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertThat(new Error()).hasMessageContaining(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(new Error()).hasMessageContaining("str " + toString());
" assertThat(new Error()).hasMessageContaining(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(new Error()).hasMessageContaining("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertThat(new Error()).hasMessageEndingWith(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(new Error()).hasMessageEndingWith("str " + toString());
" assertThat(new Error()).hasMessageEndingWith(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(new Error()).hasMessageEndingWith("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertThat(new Error()).hasMessageStartingWith(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(new Error()).hasMessageStartingWith("str " + toString());
" assertThat(new Error()).hasMessageStartingWith(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(new Error()).hasMessageStartingWith("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertThat(new Error()).hasRootCauseMessage(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(new Error()).hasRootCauseMessage("str " + toString());
" assertThat(new Error()).hasRootCauseMessage(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(new Error()).hasRootCauseMessage("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertThat(new Error()).hasStackTraceContaining(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(new Error()).hasStackTraceContaining("str " + toString());
" assertThat(new Error()).hasStackTraceContaining(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(new Error()).hasStackTraceContaining("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertThat(0).as(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(0).as("str " + toString());
" assertThat(0).as(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(0).as("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" assertThat(0).describedAs(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", assertThat(0).describedAs("str " + toString());
" assertThat(0).describedAs(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", assertThat(0).describedAs("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" ((ThrowableAssertAlternative) null).withMessage(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ((ThrowableAssertAlternative) null).withMessage("str " + toString());
" ((ThrowableAssertAlternative) null).withMessage(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", ((ThrowableAssertAlternative) null).withMessage("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" ((ThrowableAssertAlternative) null).withMessageContaining(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ((ThrowableAssertAlternative) null).withMessageContaining("str " + toString());
" ((ThrowableAssertAlternative) null).withMessageContaining(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", ((ThrowableAssertAlternative) null).withMessageContaining("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" ((ThrowableAssertAlternative) null).withMessageEndingWith(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ((ThrowableAssertAlternative) null).withMessageEndingWith("str " + toString());
" ((ThrowableAssertAlternative) null).withMessageEndingWith(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", ((ThrowableAssertAlternative) null).withMessageEndingWith("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" ((ThrowableAssertAlternative) null).withMessageStartingWith(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ((ThrowableAssertAlternative) null).withMessageStartingWith("str " + toString());
" ((ThrowableAssertAlternative) null).withMessageStartingWith(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", ((ThrowableAssertAlternative) null).withMessageStartingWith("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" ((ThrowableAssertAlternative) null).withStackTraceContaining(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ((ThrowableAssertAlternative) null).withStackTraceContaining("str " + toString());
" ((ThrowableAssertAlternative) null).withStackTraceContaining(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", ((ThrowableAssertAlternative) null).withStackTraceContaining("%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" ((WithAssertions) null).fail(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ((WithAssertions) null).fail("str " + toString());
" ((WithAssertions) null).fail(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
" ((WithAssertions) null).fail(\"str \" + toString(), new Throwable());", ((WithAssertions) null).fail("%s " + toString(), "arg");
"", ((WithAssertions) null).fail("str " + toString(), new Throwable());
" // BUG: Diagnostic contains:",
" Assertions.fail(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Assertions.fail("str " + toString());
" Assertions.fail(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
" Assertions.fail(\"str \" + toString(), new Throwable());", Assertions.fail("%s " + toString(), "arg");
"", Assertions.fail("str " + toString(), new Throwable());
" // BUG: Diagnostic contains:",
" BDDAssertions.fail(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", BDDAssertions.fail("str " + toString());
" BDDAssertions.fail(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
" BDDAssertions.fail(\"str \" + toString(), new Throwable());", BDDAssertions.fail("%s " + toString(), "arg");
"", BDDAssertions.fail("str " + toString(), new Throwable());
" // BUG: Diagnostic contains:",
" Fail.fail(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Fail.fail("str " + toString());
" Fail.fail(\"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
" Fail.fail(\"str \" + toString(), new Throwable());", Fail.fail("%s " + toString(), "arg");
" }", Fail.fail("str " + toString(), new Throwable());
"", }
" void guava() {",
" checkArgument(true);", void guava() {
" checkArgument(true, toString());", checkArgument(true);
" checkArgument(true, \"str\");", checkArgument(true, toString());
" checkArgument(true, \"str \" + 0);", checkArgument(true, "str");
" checkArgument(true, \"str %s\", 2 * 3);", checkArgument(true, "str " + 0);
" checkArgument(true, \"str %s\", toString());", checkArgument(true, "str %s", 2 * 3);
" // BUG: Diagnostic contains:", checkArgument(true, "str %s", toString());
" checkArgument(true, \"str \" + hashCode() / 2);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", checkArgument(true, "str " + hashCode() / 2);
" checkArgument(true, (\"str \" + toString()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", checkArgument(true, ("str " + toString()));
" checkArgument(true, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", checkArgument(true, "str " + toString());
" checkArgument(true, \"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", checkArgument(true, "%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" checkNotNull(true, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", checkNotNull(true, "str " + toString());
" checkNotNull(true, \"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", checkNotNull(true, "%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" checkState(true, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", checkState(true, "str " + toString());
" checkState(true, \"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", checkState(true, "%s " + toString(), "arg");
" // BUG: Diagnostic contains:",
" verify(true, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", verify(true, "str " + toString());
" verify(true, \"%s \" + toString(), \"arg\");", // BUG: Diagnostic contains:
" }", verify(true, "%s " + toString(), "arg");
"", }
" void jdk() {",
" String.format(\"str\");", void jdk() {
" String.format(\"str \" + 0);", String.format("str");
" String.format(\"str {}\", 2 * 3);", String.format("str " + 0);
" String.format(\"str {}\", toString());", String.format("str {}", 2 * 3);
" // BUG: Diagnostic contains:", String.format("str {}", toString());
" String.format(\"str \" + hashCode() / 2);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.format("str " + hashCode() / 2);
" String.format((\"str \" + toString()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.format(("str " + toString()));
" String.format(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.format("str " + toString());
" String.format(\"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", String.format("{} " + toString(), "arg");
" String.format(Locale.ROOT, \"str\");",
" String.format(Locale.ROOT, \"str \" + 0);", String.format(Locale.ROOT, "str");
" String.format(Locale.ROOT, \"str {}\", 2 * 3);", String.format(Locale.ROOT, "str " + 0);
" String.format(Locale.ROOT, \"str {}\", toString());", String.format(Locale.ROOT, "str {}", 2 * 3);
" // BUG: Diagnostic contains:", String.format(Locale.ROOT, "str {}", toString());
" String.format(Locale.ROOT, (\"str \" + toString()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.format(Locale.ROOT, ("str " + toString()));
" String.format(Locale.ROOT, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.format(Locale.ROOT, "str " + toString());
" String.format(Locale.ROOT, \"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", String.format(Locale.ROOT, "{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" new Formatter().format(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", new Formatter().format("str " + toString());
" new Formatter().format(\"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", new Formatter().format("{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" new Formatter().format(Locale.ROOT, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", new Formatter().format(Locale.ROOT, "str " + toString());
" new Formatter().format(Locale.ROOT, \"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
" }", new Formatter().format(Locale.ROOT, "{} " + toString(), "arg");
"", }
" void slf4j() {",
" LOG.debug(\"str\");", void slf4j() {
" LOG.debug(\"str \" + 0);", LOG.debug("str");
" LOG.debug(\"str {}\", 2 * 3);", LOG.debug("str " + 0);
" LOG.debug(\"str {}\", toString());", LOG.debug("str {}", 2 * 3);
" // BUG: Diagnostic contains:", LOG.debug("str {}", toString());
" LOG.debug(\"str \" + hashCode() / 2);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.debug("str " + hashCode() / 2);
" LOG.debug((\"str \" + toString()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.debug(("str " + toString()));
" LOG.debug(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.debug("str " + toString());
" LOG.debug(\"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", LOG.debug("{} " + toString(), "arg");
" LOG.debug((Marker) null, \"str\");",
" LOG.debug((Marker) null, \"str \" + 0);", LOG.debug((Marker) null, "str");
" LOG.debug((Marker) null, \"str {}\", 2 * 3);", LOG.debug((Marker) null, "str " + 0);
" LOG.debug((Marker) null, \"str {}\", toString());", LOG.debug((Marker) null, "str {}", 2 * 3);
" // BUG: Diagnostic contains:", LOG.debug((Marker) null, "str {}", toString());
" LOG.debug((Marker) null, (\"str \" + toString()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.debug((Marker) null, ("str " + toString()));
" LOG.debug((Marker) null, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.debug((Marker) null, "str " + toString());
" LOG.debug((Marker) null, \"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", LOG.debug((Marker) null, "{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" LOG.error(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.error("str " + toString());
" LOG.error(\"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", LOG.error("{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" LOG.error((Marker) null, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.error((Marker) null, "str " + toString());
" LOG.error((Marker) null, \"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", LOG.error((Marker) null, "{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" LOG.info(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.info("str " + toString());
" LOG.info(\"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", LOG.info("{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" LOG.info((Marker) null, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.info((Marker) null, "str " + toString());
" LOG.info((Marker) null, \"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", LOG.info((Marker) null, "{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" LOG.trace(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.trace("str " + toString());
" LOG.trace(\"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", LOG.trace("{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" LOG.trace((Marker) null, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.trace((Marker) null, "str " + toString());
" LOG.trace((Marker) null, \"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", LOG.trace((Marker) null, "{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" LOG.warn(\"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.warn("str " + toString());
" LOG.warn(\"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
"", LOG.warn("{} " + toString(), "arg");
" // BUG: Diagnostic contains:",
" LOG.warn((Marker) null, \"str \" + toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.warn((Marker) null, "str " + toString());
" LOG.warn((Marker) null, \"{} \" + toString(), \"arg\");", // BUG: Diagnostic contains:
" }", LOG.warn((Marker) null, "{} " + toString(), "arg");
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -307,102 +309,106 @@ final class FormatStringConcatenationTest {
BugCheckerRefactoringTestHelper.newInstance(FormatStringConcatenation.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(FormatStringConcatenation.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static com.google.common.base.Preconditions.checkArgument;", """
"import static org.assertj.core.api.Assertions.assertThat;", import static com.google.common.base.Preconditions.checkArgument;
"", import static org.assertj.core.api.Assertions.assertThat;
"import java.util.Locale;",
"import org.slf4j.Logger;", import java.util.Locale;
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"import org.slf4j.Marker;", import org.slf4j.LoggerFactory;
"", import org.slf4j.Marker;
"class A {",
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", class A {
"", private static final Logger LOG = LoggerFactory.getLogger(A.class);
" void assertj() {",
" assertThat(0).overridingErrorMessage(toString() + \" str\");", void assertj() {
" assertThat(0).overridingErrorMessage(\"str \" + toString());", assertThat(0).overridingErrorMessage(toString() + " str");
" assertThat(0).overridingErrorMessage(toString() + toString());", assertThat(0).overridingErrorMessage("str " + toString());
" assertThat(0).overridingErrorMessage(\"str \" + toString() + \" word \" + new A().hashCode());", assertThat(0).overridingErrorMessage(toString() + toString());
" assertThat(0).overridingErrorMessage(\"str \" + (toString() + \" word \") + (hashCode() / 2));", assertThat(0).overridingErrorMessage("str " + toString() + " word " + new A().hashCode());
"", assertThat(0).overridingErrorMessage("str " + (toString() + " word ") + (hashCode() / 2));
" // Flagged but not auto-fixed.",
" assertThat(0).overridingErrorMessage(\"%s \" + toString(), \"arg\");", // Flagged but not auto-fixed.
" }", assertThat(0).overridingErrorMessage("%s " + toString(), "arg");
"", }
" void guava() {",
" checkArgument(true, \"str \" + toString());", void guava() {
"", checkArgument(true, "str " + toString());
" // Flagged but not auto-fixed.",
" checkArgument(true, \"%s \" + toString(), \"arg\");", // Flagged but not auto-fixed.
" }", checkArgument(true, "%s " + toString(), "arg");
"", }
" void jdk() {",
" String.format(\"str \" + toString());", void jdk() {
" String.format(Locale.ROOT, \"str \" + toString());", String.format("str " + toString());
"", String.format(Locale.ROOT, "str " + toString());
" // Flagged but not auto-fixed.",
" String.format(\"{} \" + toString(), \"arg\");", // Flagged but not auto-fixed.
" String.format(Locale.ROOT, \"{} \" + toString(), \"arg\");", String.format("{} " + toString(), "arg");
" }", String.format(Locale.ROOT, "{} " + toString(), "arg");
"", }
" void slf4j() {",
" LOG.debug(\"str \" + toString());", void slf4j() {
" LOG.debug((Marker) null, \"str \" + toString());", LOG.debug("str " + toString());
"", LOG.debug((Marker) null, "str " + toString());
" // Flagged but not auto-fixed.",
" LOG.debug(\"{} \" + toString(), \"arg\");", // Flagged but not auto-fixed.
" LOG.debug((Marker) null, \"{} \" + toString(), \"arg\");", LOG.debug("{} " + toString(), "arg");
" }", LOG.debug((Marker) null, "{} " + toString(), "arg");
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static com.google.common.base.Preconditions.checkArgument;", """
"import static org.assertj.core.api.Assertions.assertThat;", import static com.google.common.base.Preconditions.checkArgument;
"", import static org.assertj.core.api.Assertions.assertThat;
"import java.util.Locale;",
"import org.slf4j.Logger;", import java.util.Locale;
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"import org.slf4j.Marker;", import org.slf4j.LoggerFactory;
"", import org.slf4j.Marker;
"class A {",
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", class A {
"", private static final Logger LOG = LoggerFactory.getLogger(A.class);
" void assertj() {",
" assertThat(0).overridingErrorMessage(\"%s str\", toString());", void assertj() {
" assertThat(0).overridingErrorMessage(\"str %s\", toString());", assertThat(0).overridingErrorMessage("%s str", toString());
" assertThat(0).overridingErrorMessage(\"%s%s\", toString(), toString());", assertThat(0).overridingErrorMessage("str %s", toString());
" assertThat(0).overridingErrorMessage(\"str %s word %s\", toString(), new A().hashCode());", assertThat(0).overridingErrorMessage("%s%s", toString(), toString());
" assertThat(0).overridingErrorMessage(\"str %s word %s\", toString(), hashCode() / 2);", assertThat(0).overridingErrorMessage("str %s word %s", toString(), new A().hashCode());
"", assertThat(0).overridingErrorMessage("str %s word %s", toString(), hashCode() / 2);
" // Flagged but not auto-fixed.",
" assertThat(0).overridingErrorMessage(\"%s \" + toString(), \"arg\");", // Flagged but not auto-fixed.
" }", assertThat(0).overridingErrorMessage("%s " + toString(), "arg");
"", }
" void guava() {",
" checkArgument(true, \"str %s\", toString());", void guava() {
"", checkArgument(true, "str %s", toString());
" // Flagged but not auto-fixed.",
" checkArgument(true, \"%s \" + toString(), \"arg\");", // Flagged but not auto-fixed.
" }", checkArgument(true, "%s " + toString(), "arg");
"", }
" void jdk() {",
" String.format(\"str %s\", toString());", void jdk() {
" String.format(Locale.ROOT, \"str %s\", toString());", String.format("str %s", toString());
"", String.format(Locale.ROOT, "str %s", toString());
" // Flagged but not auto-fixed.",
" String.format(\"{} \" + toString(), \"arg\");", // Flagged but not auto-fixed.
" String.format(Locale.ROOT, \"{} \" + toString(), \"arg\");", String.format("{} " + toString(), "arg");
" }", String.format(Locale.ROOT, "{} " + toString(), "arg");
"", }
" void slf4j() {",
" LOG.debug(\"str {}\", toString());", void slf4j() {
" LOG.debug((Marker) null, \"str {}\", toString());", LOG.debug("str {}", toString());
"", LOG.debug((Marker) null, "str {}", toString());
" // Flagged but not auto-fixed.",
" LOG.debug(\"{} \" + toString(), \"arg\");", // Flagged but not auto-fixed.
" LOG.debug((Marker) null, \"{} \" + toString(), \"arg\");", LOG.debug("{} " + toString(), "arg");
" }", LOG.debug((Marker) null, "{} " + toString(), "arg");
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -12,174 +12,176 @@ final class IdentityConversionTest {
CompilationTestHelper.newInstance(IdentityConversion.class, getClass()) CompilationTestHelper.newInstance(IdentityConversion.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;", """
"import static com.google.errorprone.matchers.Matchers.staticMethod;", import static com.google.errorprone.matchers.Matchers.instanceMethod;
"", import static com.google.errorprone.matchers.Matchers.staticMethod;
"import com.google.common.collect.ImmutableBiMap;",
"import com.google.common.collect.ImmutableList;", import com.google.common.collect.ImmutableBiMap;
"import com.google.common.collect.ImmutableListMultimap;", import com.google.common.collect.ImmutableList;
"import com.google.common.collect.ImmutableMap;", import com.google.common.collect.ImmutableListMultimap;
"import com.google.common.collect.ImmutableMultimap;", import com.google.common.collect.ImmutableMap;
"import com.google.common.collect.ImmutableMultiset;", import com.google.common.collect.ImmutableMultimap;
"import com.google.common.collect.ImmutableRangeMap;", import com.google.common.collect.ImmutableMultiset;
"import com.google.common.collect.ImmutableRangeSet;", import com.google.common.collect.ImmutableRangeMap;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableRangeSet;
"import com.google.common.collect.ImmutableSetMultimap;", import com.google.common.collect.ImmutableSet;
"import com.google.common.collect.ImmutableTable;", import com.google.common.collect.ImmutableSetMultimap;
"import com.google.errorprone.matchers.Matcher;", import com.google.common.collect.ImmutableTable;
"import com.google.errorprone.matchers.Matchers;", import com.google.errorprone.matchers.Matcher;
"import java.time.Instant;", import com.google.errorprone.matchers.Matchers;
"import java.time.ZonedDateTime;", import java.time.Instant;
"import reactor.adapter.rxjava.RxJava2Adapter;", import java.time.ZonedDateTime;
"import reactor.core.publisher.Flux;", import reactor.adapter.rxjava.RxJava2Adapter;
"import reactor.core.publisher.Mono;", import reactor.core.publisher.Flux;
"", import reactor.core.publisher.Mono;
"public final class A {",
" public void m() {", public final class A {
" // BUG: Diagnostic contains:", public void m() {
" Boolean b1 = Boolean.valueOf(Boolean.FALSE);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Boolean b1 = Boolean.valueOf(Boolean.FALSE);
" Boolean b2 = Boolean.valueOf(false);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Boolean b2 = Boolean.valueOf(false);
" boolean b3 = Boolean.valueOf(Boolean.FALSE);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", boolean b3 = Boolean.valueOf(Boolean.FALSE);
" boolean b4 = Boolean.valueOf(false);", // BUG: Diagnostic contains:
"", boolean b4 = Boolean.valueOf(false);
" // BUG: Diagnostic contains:",
" Byte byte1 = Byte.valueOf((Byte) Byte.MIN_VALUE);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Byte byte1 = Byte.valueOf((Byte) Byte.MIN_VALUE);
" Byte byte2 = Byte.valueOf(Byte.MIN_VALUE);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Byte byte2 = Byte.valueOf(Byte.MIN_VALUE);
" byte byte3 = Byte.valueOf((Byte) Byte.MIN_VALUE);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", byte byte3 = Byte.valueOf((Byte) Byte.MIN_VALUE);
" byte byte4 = Byte.valueOf(Byte.MIN_VALUE);", // BUG: Diagnostic contains:
"", byte byte4 = Byte.valueOf(Byte.MIN_VALUE);
" // BUG: Diagnostic contains:",
" Character c1 = Character.valueOf((Character) 'a');", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Character c1 = Character.valueOf((Character) 'a');
" Character c2 = Character.valueOf('a');", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Character c2 = Character.valueOf('a');
" char c3 = Character.valueOf((Character) 'a');", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", char c3 = Character.valueOf((Character) 'a');
" char c4 = Character.valueOf('a');", // BUG: Diagnostic contains:
"", char c4 = Character.valueOf('a');
" // BUG: Diagnostic contains:",
" Double d1 = Double.valueOf((Double) 0.0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Double d1 = Double.valueOf((Double) 0.0);
" Double d2 = Double.valueOf(0.0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Double d2 = Double.valueOf(0.0);
" double d3 = Double.valueOf((Double) 0.0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", double d3 = Double.valueOf((Double) 0.0);
" double d4 = Double.valueOf(0.0);", // BUG: Diagnostic contains:
"", double d4 = Double.valueOf(0.0);
" // BUG: Diagnostic contains:",
" Float f1 = Float.valueOf((Float) 0.0F);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Float f1 = Float.valueOf((Float) 0.0F);
" Float f2 = Float.valueOf(0.0F);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Float f2 = Float.valueOf(0.0F);
" float f3 = Float.valueOf((Float) 0.0F);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", float f3 = Float.valueOf((Float) 0.0F);
" float f4 = Float.valueOf(0.0F);", // BUG: Diagnostic contains:
"", float f4 = Float.valueOf(0.0F);
" // BUG: Diagnostic contains:",
" Integer i1 = Integer.valueOf((Integer) 1);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Integer i1 = Integer.valueOf((Integer) 1);
" Integer i2 = Integer.valueOf(1);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Integer i2 = Integer.valueOf(1);
" int i3 = Integer.valueOf((Integer) 1);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", int i3 = Integer.valueOf((Integer) 1);
" int i4 = Integer.valueOf(1);", // BUG: Diagnostic contains:
"", int i4 = Integer.valueOf(1);
" // BUG: Diagnostic contains:",
" Long l1 = Long.valueOf((Long) 1L);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Long l1 = Long.valueOf((Long) 1L);
" Long l2 = Long.valueOf(1L);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Long l2 = Long.valueOf(1L);
" long l3 = Long.valueOf((Long) 1L);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", long l3 = Long.valueOf((Long) 1L);
" long l4 = Long.valueOf(1L);", // BUG: Diagnostic contains:
"", long l4 = Long.valueOf(1L);
" Long l5 = Long.valueOf((Integer) 1);",
" Long l6 = Long.valueOf(1);", Long l5 = Long.valueOf((Integer) 1);
" // BUG: Diagnostic contains:", Long l6 = Long.valueOf(1);
" long l7 = Long.valueOf((Integer) 1);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", long l7 = Long.valueOf((Integer) 1);
" long l8 = Long.valueOf(1);", // BUG: Diagnostic contains:
"", long l8 = Long.valueOf(1);
" // BUG: Diagnostic contains:",
" Short s1 = Short.valueOf((Short) Short.MIN_VALUE);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Short s1 = Short.valueOf((Short) Short.MIN_VALUE);
" Short s2 = Short.valueOf(Short.MIN_VALUE);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Short s2 = Short.valueOf(Short.MIN_VALUE);
" short s3 = Short.valueOf((Short) Short.MIN_VALUE);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", short s3 = Short.valueOf((Short) Short.MIN_VALUE);
" short s4 = Short.valueOf(Short.MIN_VALUE);", // BUG: Diagnostic contains:
"", short s4 = Short.valueOf(Short.MIN_VALUE);
" // BUG: Diagnostic contains:",
" String boolStr = Boolean.valueOf(Boolean.FALSE).toString();", // BUG: Diagnostic contains:
" int boolHash = Boolean.valueOf(false).hashCode();", String boolStr = Boolean.valueOf(Boolean.FALSE).toString();
" // BUG: Diagnostic contains:", int boolHash = Boolean.valueOf(false).hashCode();
" int byteHash = Byte.valueOf((Byte) Byte.MIN_VALUE).hashCode();", // BUG: Diagnostic contains:
" String byteStr = Byte.valueOf(Byte.MIN_VALUE).toString();", int byteHash = Byte.valueOf((Byte) Byte.MIN_VALUE).hashCode();
"", String byteStr = Byte.valueOf(Byte.MIN_VALUE).toString();
" String str1 = String.valueOf(0);",
" // BUG: Diagnostic contains:", String str1 = String.valueOf(0);
" String str2 = String.valueOf(\"1\");", // BUG: Diagnostic contains:
"", String str2 = String.valueOf("1");
" // BUG: Diagnostic contains:",
" ImmutableBiMap<Object, Object> o1 = ImmutableBiMap.copyOf(ImmutableBiMap.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableBiMap<Object, Object> o1 = ImmutableBiMap.copyOf(ImmutableBiMap.of());
" ImmutableList<Object> o2 = ImmutableList.copyOf(ImmutableList.of());", // BUG: Diagnostic contains:
" ImmutableListMultimap<Object, Object> o3 =", ImmutableList<Object> o2 = ImmutableList.copyOf(ImmutableList.of());
" // BUG: Diagnostic contains:", ImmutableListMultimap<Object, Object> o3 =
" ImmutableListMultimap.copyOf(ImmutableListMultimap.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableListMultimap.copyOf(ImmutableListMultimap.of());
" ImmutableMap<Object, Object> o4 = ImmutableMap.copyOf(ImmutableMap.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableMap<Object, Object> o4 = ImmutableMap.copyOf(ImmutableMap.of());
" ImmutableMultimap<Object, Object> o5 = ImmutableMultimap.copyOf(ImmutableMultimap.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableMultimap<Object, Object> o5 = ImmutableMultimap.copyOf(ImmutableMultimap.of());
" ImmutableMultiset<Object> o6 = ImmutableMultiset.copyOf(ImmutableMultiset.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableMultiset<Object> o6 = ImmutableMultiset.copyOf(ImmutableMultiset.of());
" ImmutableRangeMap<String, Object> o7 = ImmutableRangeMap.copyOf(ImmutableRangeMap.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableRangeMap<String, Object> o7 = ImmutableRangeMap.copyOf(ImmutableRangeMap.of());
" ImmutableRangeSet<String> o8 = ImmutableRangeSet.copyOf(ImmutableRangeSet.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableRangeSet<String> o8 = ImmutableRangeSet.copyOf(ImmutableRangeSet.of());
" ImmutableSet<Object> o9 = ImmutableSet.copyOf(ImmutableSet.of());", // BUG: Diagnostic contains:
" ImmutableSetMultimap<Object, Object> o10 =", ImmutableSet<Object> o9 = ImmutableSet.copyOf(ImmutableSet.of());
" // BUG: Diagnostic contains:", ImmutableSetMultimap<Object, Object> o10 =
" ImmutableSetMultimap.copyOf(ImmutableSetMultimap.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableSetMultimap.copyOf(ImmutableSetMultimap.of());
" ImmutableTable<Object, Object, Object> o11 = ImmutableTable.copyOf(ImmutableTable.of());", // BUG: Diagnostic contains:
"", ImmutableTable<Object, Object, Object> o11 = ImmutableTable.copyOf(ImmutableTable.of());
" Instant instant1 = Instant.from(ZonedDateTime.now());",
" // BUG: Diagnostic contains:", Instant instant1 = Instant.from(ZonedDateTime.now());
" Instant instant2 = Instant.from(Instant.now());", // BUG: Diagnostic contains:
"", Instant instant2 = Instant.from(Instant.now());
" // BUG: Diagnostic contains:",
" Matcher allOf1 = Matchers.allOf(instanceMethod());", // BUG: Diagnostic contains:
" Matcher allOf2 = Matchers.allOf(instanceMethod(), staticMethod());", Matcher allOf1 = Matchers.allOf(instanceMethod());
" // BUG: Diagnostic contains:", Matcher allOf2 = Matchers.allOf(instanceMethod(), staticMethod());
" Matcher anyOf1 = Matchers.anyOf(staticMethod());", // BUG: Diagnostic contains:
" Matcher anyOf2 = Matchers.anyOf(instanceMethod(), staticMethod());", Matcher anyOf1 = Matchers.anyOf(staticMethod());
"", Matcher anyOf2 = Matchers.anyOf(instanceMethod(), staticMethod());
" // BUG: Diagnostic contains:",
" Flux<Integer> flux1 = Flux.just(1).flatMap(e -> RxJava2Adapter.fluxToFlowable(Flux.just(2)));", // BUG: Diagnostic contains:
"", Flux<Integer> flux1 = Flux.just(1).flatMap(e -> RxJava2Adapter.fluxToFlowable(Flux.just(2)));
" // BUG: Diagnostic contains:",
" Flux<Integer> flux2 = Flux.concat(Flux.just(1));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux<Integer> flux2 = Flux.concat(Flux.just(1));
" Flux<Integer> flux3 = Flux.firstWithSignal(Flux.just(1));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux<Integer> flux3 = Flux.firstWithSignal(Flux.just(1));
" Flux<Integer> flux4 = Flux.from(Flux.just(1));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux<Integer> flux4 = Flux.from(Flux.just(1));
" Flux<Integer> flux5 = Flux.merge(Flux.just(1));", // BUG: Diagnostic contains:
"", Flux<Integer> flux5 = Flux.merge(Flux.just(1));
" // BUG: Diagnostic contains:",
" Mono<Integer> mono1 = Mono.from(Mono.just(1));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Mono<Integer> mono1 = Mono.from(Mono.just(1));
" Mono<Integer> mono2 = Mono.fromDirect(Mono.just(1));", // BUG: Diagnostic contains:
" }", Mono<Integer> mono2 = Mono.fromDirect(Mono.just(1));
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -188,104 +190,108 @@ final class IdentityConversionTest {
BugCheckerRefactoringTestHelper.newInstance(IdentityConversion.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(IdentityConversion.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static com.google.errorprone.matchers.Matchers.staticMethod;", """
"import static org.mockito.Mockito.when;", import static com.google.errorprone.matchers.Matchers.staticMethod;
"", import static org.mockito.Mockito.when;
"import com.google.common.collect.ImmutableCollection;",
"import com.google.common.collect.ImmutableList;", import com.google.common.collect.ImmutableCollection;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import com.google.errorprone.matchers.Matcher;", import com.google.common.collect.ImmutableSet;
"import com.google.errorprone.matchers.Matchers;", import com.google.errorprone.matchers.Matcher;
"import java.util.ArrayList;", import com.google.errorprone.matchers.Matchers;
"import java.util.Collection;", import java.util.ArrayList;
"import org.reactivestreams.Publisher;", import java.util.Collection;
"import reactor.adapter.rxjava.RxJava2Adapter;", import org.reactivestreams.Publisher;
"import reactor.core.publisher.Flux;", import reactor.adapter.rxjava.RxJava2Adapter;
"import reactor.core.publisher.Mono;", import reactor.core.publisher.Flux;
"", import reactor.core.publisher.Mono;
"public final class A {",
" public void m() {", public final class A {
" ImmutableSet<Object> set1 = ImmutableSet.copyOf(ImmutableSet.of());", public void m() {
" ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());", ImmutableSet<Object> set1 = ImmutableSet.copyOf(ImmutableSet.of());
"", ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());
" ImmutableCollection<Integer> list1 = ImmutableList.copyOf(ImmutableList.of(1));",
" ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));", ImmutableCollection<Integer> list1 = ImmutableList.copyOf(ImmutableList.of(1));
"", ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));
" Collection<Integer> c1 = ImmutableSet.copyOf(ImmutableSet.of(1));",
" Collection<Integer> c2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));", Collection<Integer> c1 = ImmutableSet.copyOf(ImmutableSet.of(1));
"", Collection<Integer> c2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));
" Flux<Integer> f1 = Flux.just(1).flatMap(e -> RxJava2Adapter.fluxToFlowable(Flux.just(2)));",
" Flux<Integer> f2 = Flux.concat(Flux.just(3));", Flux<Integer> f1 = Flux.just(1).flatMap(e -> RxJava2Adapter.fluxToFlowable(Flux.just(2)));
" Publisher<Integer> f3 = Flux.firstWithSignal(Flux.just(4));", Flux<Integer> f2 = Flux.concat(Flux.just(3));
" Publisher<Integer> f4 = Flux.from(Flux.just(5));", Publisher<Integer> f3 = Flux.firstWithSignal(Flux.just(4));
" Publisher<Integer> f5 = Flux.merge(Flux.just(6));", Publisher<Integer> f4 = Flux.from(Flux.just(5));
"", Publisher<Integer> f5 = Flux.merge(Flux.just(6));
" Mono<Integer> m1 = Mono.from(Mono.just(7));",
" Publisher<Integer> m2 = Mono.fromDirect(Mono.just(8));", Mono<Integer> m1 = Mono.from(Mono.just(7));
"", Publisher<Integer> m2 = Mono.fromDirect(Mono.just(8));
" bar(Flux.concat(Flux.just(9)));",
" bar(Mono.from(Mono.just(10)));", bar(Flux.concat(Flux.just(9)));
"", bar(Mono.from(Mono.just(10)));
" Object o1 = ImmutableSet.copyOf(ImmutableList.of());",
" Object o2 = ImmutableSet.copyOf(ImmutableSet.of());", Object o1 = ImmutableSet.copyOf(ImmutableList.of());
"", Object o2 = ImmutableSet.copyOf(ImmutableSet.of());
" Matcher matcher = Matchers.allOf(staticMethod());",
"", Matcher matcher = Matchers.allOf(staticMethod());
" when(\"foo\".contains(\"f\")).thenAnswer(inv -> ImmutableSet.copyOf(ImmutableList.of(1)));",
" }", when("foo".contains("f")).thenAnswer(inv -> ImmutableSet.copyOf(ImmutableList.of(1)));
"", }
" void bar(Publisher<Integer> publisher) {}",
"}") void bar(Publisher<Integer> publisher) {}
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static com.google.errorprone.matchers.Matchers.staticMethod;", """
"import static org.mockito.Mockito.when;", import static com.google.errorprone.matchers.Matchers.staticMethod;
"", import static org.mockito.Mockito.when;
"import com.google.common.collect.ImmutableCollection;",
"import com.google.common.collect.ImmutableList;", import com.google.common.collect.ImmutableCollection;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import com.google.errorprone.matchers.Matcher;", import com.google.common.collect.ImmutableSet;
"import com.google.errorprone.matchers.Matchers;", import com.google.errorprone.matchers.Matcher;
"import java.util.ArrayList;", import com.google.errorprone.matchers.Matchers;
"import java.util.Collection;", import java.util.ArrayList;
"import org.reactivestreams.Publisher;", import java.util.Collection;
"import reactor.adapter.rxjava.RxJava2Adapter;", import org.reactivestreams.Publisher;
"import reactor.core.publisher.Flux;", import reactor.adapter.rxjava.RxJava2Adapter;
"import reactor.core.publisher.Mono;", import reactor.core.publisher.Flux;
"", import reactor.core.publisher.Mono;
"public final class A {",
" public void m() {", public final class A {
" ImmutableSet<Object> set1 = ImmutableSet.of();", public void m() {
" ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());", ImmutableSet<Object> set1 = ImmutableSet.of();
"", ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());
" ImmutableCollection<Integer> list1 = ImmutableList.of(1);",
" ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));", ImmutableCollection<Integer> list1 = ImmutableList.of(1);
"", ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));
" Collection<Integer> c1 = ImmutableSet.of(1);",
" Collection<Integer> c2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));", Collection<Integer> c1 = ImmutableSet.of(1);
"", Collection<Integer> c2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));
" Flux<Integer> f1 = Flux.just(1).flatMap(e -> Flux.just(2));",
" Flux<Integer> f2 = Flux.just(3);", Flux<Integer> f1 = Flux.just(1).flatMap(e -> Flux.just(2));
" Publisher<Integer> f3 = Flux.just(4);", Flux<Integer> f2 = Flux.just(3);
" Publisher<Integer> f4 = Flux.just(5);", Publisher<Integer> f3 = Flux.just(4);
" Publisher<Integer> f5 = Flux.just(6);", Publisher<Integer> f4 = Flux.just(5);
"", Publisher<Integer> f5 = Flux.just(6);
" Mono<Integer> m1 = Mono.just(7);",
" Publisher<Integer> m2 = Mono.just(8);", Mono<Integer> m1 = Mono.just(7);
"", Publisher<Integer> m2 = Mono.just(8);
" bar(Flux.just(9));",
" bar(Mono.just(10));", bar(Flux.just(9));
"", bar(Mono.just(10));
" Object o1 = ImmutableSet.copyOf(ImmutableList.of());",
" Object o2 = ImmutableSet.of();", Object o1 = ImmutableSet.copyOf(ImmutableList.of());
"", Object o2 = ImmutableSet.of();
" Matcher matcher = staticMethod();",
"", Matcher matcher = staticMethod();
" when(\"foo\".contains(\"f\")).thenAnswer(inv -> ImmutableSet.copyOf(ImmutableList.of(1)));",
" }", when("foo".contains("f")).thenAnswer(inv -> ImmutableSet.copyOf(ImmutableList.of(1)));
"", }
" void bar(Publisher<Integer> publisher) {}",
"}") void bar(Publisher<Integer> publisher) {}
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -295,38 +301,42 @@ final class IdentityConversionTest {
.setFixChooser(FixChoosers.SECOND) .setFixChooser(FixChoosers.SECOND)
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableCollection;", """
"import com.google.common.collect.ImmutableList;", import com.google.common.collect.ImmutableCollection;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import java.util.ArrayList;", import com.google.common.collect.ImmutableSet;
"", import java.util.ArrayList;
"public final class A {",
" public void m() {", public final class A {
" ImmutableSet<Object> set1 = ImmutableSet.copyOf(ImmutableSet.of());", public void m() {
" ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());", ImmutableSet<Object> set1 = ImmutableSet.copyOf(ImmutableSet.of());
"", ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());
" ImmutableCollection<Integer> list1 = ImmutableList.copyOf(ImmutableList.of(1));",
" ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));", ImmutableCollection<Integer> list1 = ImmutableList.copyOf(ImmutableList.of(1));
" }", ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableCollection;", """
"import com.google.common.collect.ImmutableList;", import com.google.common.collect.ImmutableCollection;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import java.util.ArrayList;", import com.google.common.collect.ImmutableSet;
"", import java.util.ArrayList;
"public final class A {",
" public void m() {", public final class A {
" @SuppressWarnings(\"IdentityConversion\")", public void m() {
" ImmutableSet<Object> set1 = ImmutableSet.copyOf(ImmutableSet.of());", @SuppressWarnings("IdentityConversion")
" ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());", ImmutableSet<Object> set1 = ImmutableSet.copyOf(ImmutableSet.of());
"", ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());
" @SuppressWarnings(\"IdentityConversion\")",
" ImmutableCollection<Integer> list1 = ImmutableList.copyOf(ImmutableList.of(1));", @SuppressWarnings("IdentityConversion")
" ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));", ImmutableCollection<Integer> list1 = ImmutableList.copyOf(ImmutableList.of(1));
" }", ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,94 +11,96 @@ final class ImmutablesSortedSetComparatorTest {
CompilationTestHelper.newInstance(ImmutablesSortedSetComparator.class, getClass()) CompilationTestHelper.newInstance(ImmutablesSortedSetComparator.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ContiguousSet;", """
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ContiguousSet;
"import com.google.common.collect.ImmutableSortedSet;", import com.google.common.collect.ImmutableSet;
"import java.util.NavigableSet;", import com.google.common.collect.ImmutableSortedSet;
"import java.util.Set;", import java.util.NavigableSet;
"import java.util.SortedSet;", import java.util.Set;
"import java.util.TreeSet;", import java.util.SortedSet;
"import org.immutables.value.Value;", import java.util.TreeSet;
"", import org.immutables.value.Value;
"interface A {",
" @Value.Immutable", interface A {
" interface ImmutableInterface {", @Value.Immutable
" Set<String> set();", interface ImmutableInterface {
"", Set<String> set();
" // BUG: Diagnostic contains:",
" SortedSet<String> sortedSet();", // BUG: Diagnostic contains:
"", SortedSet<String> sortedSet();
" @Value.NaturalOrder",
" SortedSet<String> sortedSet2();", @Value.NaturalOrder
" }", SortedSet<String> sortedSet2();
"", }
" @Value.Modifiable",
" interface ModifiableInterfaceWithDefaults {", @Value.Modifiable
" @Value.Default", interface ModifiableInterfaceWithDefaults {
" default Set<Integer> set() {", @Value.Default
" return new TreeSet<>();", default Set<Integer> set() {
" }", return new TreeSet<>();
"", }
" @Value.Default",
" // BUG: Diagnostic contains:", @Value.Default
" default NavigableSet<Integer> navigableSet() {", // BUG: Diagnostic contains:
" return new TreeSet<>();", default NavigableSet<Integer> navigableSet() {
" }", return new TreeSet<>();
"", }
" @Value.Default",
" @Value.ReverseOrder", @Value.Default
" default NavigableSet<Integer> navigableSet2() {", @Value.ReverseOrder
" return new TreeSet<>();", default NavigableSet<Integer> navigableSet2() {
" }", return new TreeSet<>();
"", }
" default NavigableSet<Integer> nonPropertyNavigableSet() {",
" return new TreeSet<>();", default NavigableSet<Integer> nonPropertyNavigableSet() {
" }", return new TreeSet<>();
" }", }
"", }
" interface NonImmutablesInterface {",
" SortedSet<String> sortedSet();", interface NonImmutablesInterface {
" }", SortedSet<String> sortedSet();
"", }
" @Value.Immutable",
" abstract class AbstractImmutableWithDefaults {", @Value.Immutable
" @Value.Default", abstract class AbstractImmutableWithDefaults {
" ImmutableSet<Integer> immutableSet() {", @Value.Default
" return ImmutableSet.of();", ImmutableSet<Integer> immutableSet() {
" }", return ImmutableSet.of();
"", }
" @Value.Default",
" // BUG: Diagnostic contains:", @Value.Default
" ImmutableSortedSet<String> immutableSortedSet() {", // BUG: Diagnostic contains:
" return ImmutableSortedSet.of();", ImmutableSortedSet<String> immutableSortedSet() {
" }", return ImmutableSortedSet.of();
"", }
" @Value.Default",
" @Value.NaturalOrder", @Value.Default
" ImmutableSortedSet<String> immutableSortedSet2() {", @Value.NaturalOrder
" return ImmutableSortedSet.of();", ImmutableSortedSet<String> immutableSortedSet2() {
" }", return ImmutableSortedSet.of();
"", }
" ImmutableSortedSet<String> nonPropertyImmutableSortedSet() {",
" return ImmutableSortedSet.of();", ImmutableSortedSet<String> nonPropertyImmutableSortedSet() {
" }", return ImmutableSortedSet.of();
" }", }
"", }
" @Value.Modifiable",
" abstract class AbstractModifiable {", @Value.Modifiable
" abstract ImmutableSet<Integer> immutableSet();", abstract class AbstractModifiable {
"", abstract ImmutableSet<Integer> immutableSet();
" // BUG: Diagnostic contains:",
" abstract ContiguousSet<Integer> contiguousSet();", // BUG: Diagnostic contains:
"", abstract ContiguousSet<Integer> contiguousSet();
" @Value.ReverseOrder",
" abstract ContiguousSet<Integer> contiguousSet2();", @Value.ReverseOrder
" }", abstract ContiguousSet<Integer> contiguousSet2();
"", }
" abstract class AbstractNonImmutables {",
" abstract SortedSet<Integer> sortedSet();", abstract class AbstractNonImmutables {
" }", abstract SortedSet<Integer> sortedSet();
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -107,36 +109,40 @@ final class ImmutablesSortedSetComparatorTest {
BugCheckerRefactoringTestHelper.newInstance(ImmutablesSortedSetComparator.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(ImmutablesSortedSetComparator.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableSortedSet;", """
"import java.util.SortedSet;", import com.google.common.collect.ImmutableSortedSet;
"import org.immutables.value.Value;", import java.util.SortedSet;
"", import org.immutables.value.Value;
"@Value.Immutable",
"abstract class A {", @Value.Immutable
" abstract ImmutableSortedSet<String> sortedSet();", abstract class A {
"", abstract ImmutableSortedSet<String> sortedSet();
" @Value.Modifiable",
" interface B {", @Value.Modifiable
" SortedSet<String> sortedSet();", interface B {
" }", SortedSet<String> sortedSet();
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableSortedSet;", """
"import java.util.SortedSet;", import com.google.common.collect.ImmutableSortedSet;
"import org.immutables.value.Value;", import java.util.SortedSet;
"", import org.immutables.value.Value;
"@Value.Immutable",
"abstract class A {", @Value.Immutable
" @Value.NaturalOrder", abstract class A {
" abstract ImmutableSortedSet<String> sortedSet();", @Value.NaturalOrder
"", abstract ImmutableSortedSet<String> sortedSet();
" @Value.Modifiable",
" interface B {", @Value.Modifiable
" @Value.NaturalOrder", interface B {
" SortedSet<String> sortedSet();", @Value.NaturalOrder
" }", SortedSet<String> sortedSet();
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -145,33 +151,37 @@ final class ImmutablesSortedSetComparatorTest {
BugCheckerRefactoringTestHelper.newInstance(ImmutablesSortedSetComparator.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(ImmutablesSortedSetComparator.class, getClass())
.addInputLines( .addInputLines(
"MySpringService.java", "MySpringService.java",
"import com.google.common.collect.ImmutableSortedSet;", """
"import org.springframework.beans.factory.annotation.Value;", import com.google.common.collect.ImmutableSortedSet;
"", import org.springframework.beans.factory.annotation.Value;
"class MySpringService {",
" MySpringService(@Value(\"${someProperty}\") String prop) {}", class MySpringService {
" ;", MySpringService(@Value("${someProperty}") String prop) {}
"", ;
" @org.immutables.value.Value.Immutable",
" interface A {", @org.immutables.value.Value.Immutable
" ImmutableSortedSet<String> sortedSet();", interface A {
" }", ImmutableSortedSet<String> sortedSet();
"}") }
}
""")
.addOutputLines( .addOutputLines(
"MySpringService.java", "MySpringService.java",
"import com.google.common.collect.ImmutableSortedSet;", """
"import org.springframework.beans.factory.annotation.Value;", import com.google.common.collect.ImmutableSortedSet;
"", import org.springframework.beans.factory.annotation.Value;
"class MySpringService {",
" MySpringService(@Value(\"${someProperty}\") String prop) {}", class MySpringService {
" ;", MySpringService(@Value("${someProperty}") String prop) {}
"", ;
" @org.immutables.value.Value.Immutable",
" interface A {", @org.immutables.value.Value.Immutable
" @org.immutables.value.Value.NaturalOrder", interface A {
" ImmutableSortedSet<String> sortedSet();", @org.immutables.value.Value.NaturalOrder
" }", ImmutableSortedSet<String> sortedSet();
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,32 +11,34 @@ final class IsInstanceLambdaUsageTest {
CompilationTestHelper.newInstance(IsInstanceLambdaUsage.class, getClass()) CompilationTestHelper.newInstance(IsInstanceLambdaUsage.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.stream.Stream;", """
"import reactor.core.publisher.Flux;", import java.util.stream.Stream;
"", import reactor.core.publisher.Flux;
"class A {",
" void m() {", class A {
" Integer localVariable = 0;", void m() {
"", Integer localVariable = 0;
" Stream.of(0).map(i -> i);",
" Stream.of(1).map(i -> i + 1);", Stream.of(0).map(i -> i);
" Stream.of(2).filter(Integer.class::isInstance);", Stream.of(1).map(i -> i + 1);
" Stream.of(3).filter(i -> i.getClass() instanceof Class);", Stream.of(2).filter(Integer.class::isInstance);
" Stream.of(4).filter(i -> localVariable instanceof Integer);", Stream.of(3).filter(i -> i.getClass() instanceof Class);
" // XXX: Ideally this case is also flagged. Pick this up in the context of merging the", Stream.of(4).filter(i -> localVariable instanceof Integer);
" // `IsInstanceLambdaUsage` and `MethodReferenceUsage` checks, or introduce a separate check that", // XXX: Ideally this case is also flagged. Pick this up in the context of merging the
" // simplifies unnecessary block lambda expressions.", // `IsInstanceLambdaUsage` and `MethodReferenceUsage` checks, or introduce a separate check that
" Stream.of(5)", // simplifies unnecessary block lambda expressions.
" .filter(", Stream.of(5)
" i -> {", .filter(
" return i instanceof Integer;", i -> {
" });", return i instanceof Integer;
" Flux.just(6, \"foo\").distinctUntilChanged(v -> v, (a, b) -> a instanceof Integer);", });
"", Flux.just(6, "foo").distinctUntilChanged(v -> v, (a, b) -> a instanceof Integer);
" // BUG: Diagnostic contains:",
" Stream.of(7).filter(i -> i instanceof Integer);", // BUG: Diagnostic contains:
" }", Stream.of(7).filter(i -> i instanceof Integer);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -45,22 +47,26 @@ final class IsInstanceLambdaUsageTest {
BugCheckerRefactoringTestHelper.newInstance(IsInstanceLambdaUsage.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(IsInstanceLambdaUsage.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import java.util.stream.Stream;", """
"", import java.util.stream.Stream;
"class A {",
" void m() {", class A {
" Stream.of(1).filter(i -> i instanceof Integer);", void m() {
" }", Stream.of(1).filter(i -> i instanceof Integer);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import java.util.stream.Stream;", """
"", import java.util.stream.Stream;
"class A {",
" void m() {", class A {
" Stream.of(1).filter(Integer.class::isInstance);", void m() {
" }", Stream.of(1).filter(Integer.class::isInstance);
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,83 +11,85 @@ final class JUnitClassModifiersTest {
CompilationTestHelper.newInstance(JUnitClassModifiers.class, getClass()) CompilationTestHelper.newInstance(JUnitClassModifiers.class, getClass())
.addSourceLines( .addSourceLines(
"Container.java", "Container.java",
"import org.junit.jupiter.api.Test;", """
"import org.junit.jupiter.params.ParameterizedTest;", import org.junit.jupiter.api.Test;
"import org.springframework.boot.test.context.TestConfiguration;", import org.junit.jupiter.params.ParameterizedTest;
"import org.springframework.context.annotation.Configuration;", import org.springframework.boot.test.context.TestConfiguration;
"", import org.springframework.context.annotation.Configuration;
"class Container {",
" final class FinalAndPackagePrivate {", class Container {
" @Test", final class FinalAndPackagePrivate {
" void foo() {}", @Test
" }", void foo() {}
"", }
" final class FinalAndPackagePrivateWithCustomTestMethod {",
" @ParameterizedTest", final class FinalAndPackagePrivateWithCustomTestMethod {
" void foo() {}", @ParameterizedTest
" }", void foo() {}
"", }
" public abstract class Abstract {",
" @Test", public abstract class Abstract {
" void foo() {}", @Test
" }", void foo() {}
"", }
" @Configuration",
" class WithConfigurationAnnotation {", @Configuration
" @Test", class WithConfigurationAnnotation {
" void foo() {}", @Test
" }", void foo() {}
"", }
" @TestConfiguration",
" class WithConfigurationMetaAnnotation {", @TestConfiguration
" @Test", class WithConfigurationMetaAnnotation {
" void foo() {}", @Test
" }", void foo() {}
"", }
" // BUG: Diagnostic contains:",
" private final class Private {", // BUG: Diagnostic contains:
" @Test", private final class Private {
" void foo() {}", @Test
" }", void foo() {}
"", }
" // BUG: Diagnostic contains:",
" protected final class Protected {", // BUG: Diagnostic contains:
" @Test", protected final class Protected {
" void foo() {}", @Test
" }", void foo() {}
"", }
" // BUG: Diagnostic contains:",
" public final class Public {", // BUG: Diagnostic contains:
" @Test", public final class Public {
" void foo() {}", @Test
" }", void foo() {}
"", }
" // BUG: Diagnostic contains:",
" class NonFinal {", // BUG: Diagnostic contains:
" @Test", class NonFinal {
" void foo() {}", @Test
" }", void foo() {}
"", }
" // BUG: Diagnostic contains:",
" class NonFinalWithCustomTestMethod {", // BUG: Diagnostic contains:
" @ParameterizedTest", class NonFinalWithCustomTestMethod {
" void foo() {}", @ParameterizedTest
" }", void foo() {}
"", }
" @Configuration",
" // BUG: Diagnostic contains:", @Configuration
" public class PublicWithConfigurationAnnotation {", // BUG: Diagnostic contains:
" @Test", public class PublicWithConfigurationAnnotation {
" void foo() {}", @Test
" }", void foo() {}
"", }
" @TestConfiguration",
" // BUG: Diagnostic contains:", @TestConfiguration
" protected class ProtectedWithConfigurationMetaAnnotation {", // BUG: Diagnostic contains:
" @Test", protected class ProtectedWithConfigurationMetaAnnotation {
" void foo() {}", @Test
" }", void foo() {}
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -96,34 +98,38 @@ final class JUnitClassModifiersTest {
BugCheckerRefactoringTestHelper.newInstance(JUnitClassModifiers.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(JUnitClassModifiers.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import org.junit.jupiter.api.Test;", """
"import org.springframework.context.annotation.Configuration;", import org.junit.jupiter.api.Test;
"", import org.springframework.context.annotation.Configuration;
"public class A {",
" @Test", public class A {
" void foo() {}", @Test
"", void foo() {}
" @Configuration",
" private static class B {", @Configuration
" @Test", private static class B {
" void bar() {}", @Test
" }", void bar() {}
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import org.junit.jupiter.api.Test;", """
"import org.springframework.context.annotation.Configuration;", import org.junit.jupiter.api.Test;
"", import org.springframework.context.annotation.Configuration;
"final class A {",
" @Test", final class A {
" void foo() {}", @Test
"", void foo() {}
" @Configuration",
" static class B {", @Configuration
" @Test", static class B {
" void bar() {}", @Test
" }", void bar() {}
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,332 +11,338 @@ final class JUnitMethodDeclarationTest {
CompilationTestHelper.newInstance(JUnitMethodDeclaration.class, getClass()) CompilationTestHelper.newInstance(JUnitMethodDeclaration.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static org.junit.jupiter.params.provider.Arguments.*;", """
"", import static org.junit.jupiter.params.provider.Arguments.*;
"import org.junit.jupiter.api.AfterAll;",
"import org.junit.jupiter.api.AfterEach;", import org.junit.jupiter.api.AfterAll;
"import org.junit.jupiter.api.BeforeAll;", import org.junit.jupiter.api.AfterEach;
"import org.junit.jupiter.api.BeforeEach;", import org.junit.jupiter.api.BeforeAll;
"import org.junit.jupiter.api.Test;", import org.junit.jupiter.api.BeforeEach;
"import org.junit.jupiter.params.ParameterizedTest;", import org.junit.jupiter.api.Test;
"", import org.junit.jupiter.params.ParameterizedTest;
"class A {",
" {", class A {
" arguments();", {
" }", arguments();
"", }
" @BeforeAll",
" void setUp1() {}", @BeforeAll
"", void setUp1() {}
" @BeforeAll",
" // BUG: Diagnostic contains:", @BeforeAll
" public void setUp2() {}", // BUG: Diagnostic contains:
"", public void setUp2() {}
" @BeforeAll",
" // BUG: Diagnostic contains:", @BeforeAll
" protected void setUp3() {}", // BUG: Diagnostic contains:
"", protected void setUp3() {}
" @BeforeAll",
" // BUG: Diagnostic contains:", @BeforeAll
" private void setUp4() {}", // BUG: Diagnostic contains:
"", private void setUp4() {}
" @BeforeEach",
" void setup5() {}", @BeforeEach
"", void setup5() {}
" @BeforeEach",
" // BUG: Diagnostic contains:", @BeforeEach
" public void setUp6() {}", // BUG: Diagnostic contains:
"", public void setUp6() {}
" @BeforeEach",
" // BUG: Diagnostic contains:", @BeforeEach
" protected void setUp7() {}", // BUG: Diagnostic contains:
"", protected void setUp7() {}
" @BeforeEach",
" // BUG: Diagnostic contains:", @BeforeEach
" private void setUp8() {}", // BUG: Diagnostic contains:
"", private void setUp8() {}
" @AfterEach",
" void tearDown1() {}", @AfterEach
"", void tearDown1() {}
" @AfterEach",
" // BUG: Diagnostic contains:", @AfterEach
" public void tearDown2() {}", // BUG: Diagnostic contains:
"", public void tearDown2() {}
" @AfterEach",
" // BUG: Diagnostic contains:", @AfterEach
" protected void tearDown3() {}", // BUG: Diagnostic contains:
"", protected void tearDown3() {}
" @AfterEach",
" // BUG: Diagnostic contains:", @AfterEach
" private void tearDown4() {}", // BUG: Diagnostic contains:
"", private void tearDown4() {}
" @AfterAll",
" void tearDown5() {}", @AfterAll
"", void tearDown5() {}
" @AfterAll",
" // BUG: Diagnostic contains:", @AfterAll
" public void tearDown6() {}", // BUG: Diagnostic contains:
"", public void tearDown6() {}
" @AfterAll",
" // BUG: Diagnostic contains:", @AfterAll
" protected void tearDown7() {}", // BUG: Diagnostic contains:
"", protected void tearDown7() {}
" @AfterAll",
" // BUG: Diagnostic contains:", @AfterAll
" private void tearDown8() {}", // BUG: Diagnostic contains:
"", private void tearDown8() {}
" @Test",
" void test() {}", @Test
"", void test() {}
" @Test",
" void method1() {}", @Test
"", void method1() {}
" @Test",
" // BUG: Diagnostic contains:", @Test
" void testMethod2() {}", // BUG: Diagnostic contains:
"", void testMethod2() {}
" @Test",
" // BUG: Diagnostic contains:", @Test
" public void method3() {}", // BUG: Diagnostic contains:
"", public void method3() {}
" @Test",
" // BUG: Diagnostic contains:", @Test
" protected void method4() {}", // BUG: Diagnostic contains:
"", protected void method4() {}
" @Test",
" // BUG: Diagnostic contains:", @Test
" private void method5() {}", // BUG: Diagnostic contains:
"", private void method5() {}
" @ParameterizedTest",
" void method6() {}", @ParameterizedTest
"", void method6() {}
" @ParameterizedTest",
" // BUG: Diagnostic contains:", @ParameterizedTest
" void testMethod7() {}", // BUG: Diagnostic contains:
"", void testMethod7() {}
" @ParameterizedTest",
" // BUG: Diagnostic contains:", @ParameterizedTest
" public void method8() {}", // BUG: Diagnostic contains:
"", public void method8() {}
" @ParameterizedTest",
" // BUG: Diagnostic contains:", @ParameterizedTest
" protected void method9() {}", // BUG: Diagnostic contains:
"", protected void method9() {}
" @ParameterizedTest",
" // BUG: Diagnostic contains:", @ParameterizedTest
" private void method10() {}", // BUG: Diagnostic contains:
"", private void method10() {}
" @BeforeEach",
" @BeforeAll", @BeforeEach
" @AfterEach", @BeforeAll
" @AfterAll", @AfterEach
" void testNonTestMethod1() {}", @AfterAll
"", void testNonTestMethod1() {}
" public void testNonTestMethod2() {}",
"", public void testNonTestMethod2() {}
" protected void testNonTestMethod3() {}",
"", protected void testNonTestMethod3() {}
" private void testNonTestMethod4() {}",
"", private void testNonTestMethod4() {}
" @Test",
" void test5() {}", @Test
"", void test5() {}
" @Test",
" // BUG: Diagnostic contains: (but note that a method named `toString` is already defined in this", @Test
" // class or a supertype)", // BUG: Diagnostic contains: (but note that a method named `toString` is already defined in this
" void testToString() {}", // class or a supertype)
"", void testToString() {}
" @Test",
" // BUG: Diagnostic contains: (but note that a method named `overload` is already defined in this", @Test
" // class or a supertype)", // BUG: Diagnostic contains: (but note that a method named `overload` is already defined in this
" void testOverload() {}", // class or a supertype)
"", void testOverload() {}
" void overload() {}",
"", void overload() {}
" @Test",
" // BUG: Diagnostic contains: (but note that another method named `arguments` is in scope)", @Test
" void testArguments() {", // BUG: Diagnostic contains: (but note that another method named `arguments` is in scope)
" arguments();", void testArguments() {
" }", arguments();
"", }
" @Test",
" // BUG: Diagnostic contains: (but note that `public` is not a valid identifier)", @Test
" void testPublic() {}", // BUG: Diagnostic contains: (but note that `public` is not a valid identifier)
"", void testPublic() {}
" @Test",
" // BUG: Diagnostic contains: (but note that `null` is not a valid identifier)", @Test
" void testNull() {}", // BUG: Diagnostic contains: (but note that `null` is not a valid identifier)
"", void testNull() {}
" @Test",
" // BUG: Diagnostic contains:", @Test
" void testRecord() {}", // BUG: Diagnostic contains:
"", void testRecord() {}
" @Test",
" // BUG: Diagnostic contains:", @Test
" void testMethodThatIsOverriddenWithoutOverrideAnnotation() {}", // BUG: Diagnostic contains:
"}") void testMethodThatIsOverriddenWithoutOverrideAnnotation() {}
}
""")
.addSourceLines( .addSourceLines(
"B.java", "B.java",
"import org.junit.jupiter.api.AfterAll;", """
"import org.junit.jupiter.api.AfterEach;", import org.junit.jupiter.api.AfterAll;
"import org.junit.jupiter.api.BeforeAll;", import org.junit.jupiter.api.AfterEach;
"import org.junit.jupiter.api.BeforeEach;", import org.junit.jupiter.api.BeforeAll;
"import org.junit.jupiter.api.Test;", import org.junit.jupiter.api.BeforeEach;
"import org.junit.jupiter.params.ParameterizedTest;", import org.junit.jupiter.api.Test;
"", import org.junit.jupiter.params.ParameterizedTest;
"class B extends A {",
" @Override", class B extends A {
" @BeforeAll", @Override
" void setUp1() {}", @BeforeAll
"", void setUp1() {}
" @Override",
" @BeforeAll", @Override
" public void setUp2() {}", @BeforeAll
"", public void setUp2() {}
" @Override",
" @BeforeAll", @Override
" protected void setUp3() {}", @BeforeAll
"", protected void setUp3() {}
" @Override",
" @BeforeEach", @Override
" void setup5() {}", @BeforeEach
"", void setup5() {}
" @Override",
" @BeforeEach", @Override
" public void setUp6() {}", @BeforeEach
"", public void setUp6() {}
" @Override",
" @BeforeEach", @Override
" protected void setUp7() {}", @BeforeEach
"", protected void setUp7() {}
" @Override",
" @AfterEach", @Override
" void tearDown1() {}", @AfterEach
"", void tearDown1() {}
" @Override",
" @AfterEach", @Override
" public void tearDown2() {}", @AfterEach
"", public void tearDown2() {}
" @Override",
" @AfterEach", @Override
" protected void tearDown3() {}", @AfterEach
"", protected void tearDown3() {}
" @Override",
" @AfterAll", @Override
" void tearDown5() {}", @AfterAll
"", void tearDown5() {}
" @Override",
" @AfterAll", @Override
" public void tearDown6() {}", @AfterAll
"", public void tearDown6() {}
" @Override",
" @AfterAll", @Override
" protected void tearDown7() {}", @AfterAll
"", protected void tearDown7() {}
" @Override",
" @Test", @Override
" void test() {}", @Test
"", void test() {}
" @Override",
" @Test", @Override
" void method1() {}", @Test
"", void method1() {}
" @Override",
" @Test", @Override
" void testMethod2() {}", @Test
"", void testMethod2() {}
" @Override",
" @Test", @Override
" public void method3() {}", @Test
"", public void method3() {}
" @Override",
" @Test", @Override
" protected void method4() {}", @Test
"", protected void method4() {}
" @Override",
" @ParameterizedTest", @Override
" void method6() {}", @ParameterizedTest
"", void method6() {}
" @Override",
" @ParameterizedTest", @Override
" void testMethod7() {}", @ParameterizedTest
"", void testMethod7() {}
" @Override",
" @ParameterizedTest", @Override
" public void method8() {}", @ParameterizedTest
"", public void method8() {}
" @Override",
" @ParameterizedTest", @Override
" protected void method9() {}", @ParameterizedTest
"", protected void method9() {}
" @Override",
" @BeforeEach", @Override
" @BeforeAll", @BeforeEach
" @AfterEach", @BeforeAll
" @AfterAll", @AfterEach
" void testNonTestMethod1() {}", @AfterAll
"", void testNonTestMethod1() {}
" @Override",
" public void testNonTestMethod2() {}", @Override
"", public void testNonTestMethod2() {}
" @Override",
" protected void testNonTestMethod3() {}", @Override
"", protected void testNonTestMethod3() {}
" @Override",
" @Test", @Override
" void test5() {}", @Test
"", void test5() {}
" @Override",
" @Test", @Override
" void testToString() {}", @Test
"", void testToString() {}
" @Override",
" @Test", @Override
" void testOverload() {}", @Test
"", void testOverload() {}
" @Override",
" void overload() {}", @Override
"", void overload() {}
" @Override",
" @Test", @Override
" void testArguments() {}", @Test
"", void testArguments() {}
" @Override",
" @Test", @Override
" void testPublic() {}", @Test
"", void testPublic() {}
" @Override",
" @Test", @Override
" void testNull() {}", @Test
"", void testNull() {}
" @Override",
" @Test", @Override
" void testRecord() {}", @Test
"", void testRecord() {}
" @Test",
" void testMethodThatIsOverriddenWithoutOverrideAnnotation() {}", @Test
"}") void testMethodThatIsOverriddenWithoutOverrideAnnotation() {}
}
""")
.addSourceLines( .addSourceLines(
"C.java", "C.java",
"import org.junit.jupiter.api.AfterAll;", """
"import org.junit.jupiter.api.BeforeAll;", import org.junit.jupiter.api.AfterAll;
"import org.junit.jupiter.api.Test;", import org.junit.jupiter.api.BeforeAll;
"", import org.junit.jupiter.api.Test;
"abstract class C {",
" @BeforeAll", abstract class C {
" public void setUp() {}", @BeforeAll
"", public void setUp() {}
" @Test",
" void testMethod1() {}", @Test
"", void testMethod1() {}
" @AfterAll",
" // BUG: Diagnostic contains:", @AfterAll
" private void tearDown() {}", // BUG: Diagnostic contains:
"", private void tearDown() {}
" @Test",
" // BUG: Diagnostic contains:", @Test
" final void testMethod2() {}", // BUG: Diagnostic contains:
"}") final void testMethod2() {}
}
""")
.doTest(); .doTest();
} }
@@ -345,126 +351,130 @@ final class JUnitMethodDeclarationTest {
BugCheckerRefactoringTestHelper.newInstance(JUnitMethodDeclaration.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(JUnitMethodDeclaration.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static org.junit.jupiter.params.provider.Arguments.arguments;", """
"", import static org.junit.jupiter.params.provider.Arguments.arguments;
"import org.junit.jupiter.api.AfterAll;",
"import org.junit.jupiter.api.AfterEach;", import org.junit.jupiter.api.AfterAll;
"import org.junit.jupiter.api.BeforeAll;", import org.junit.jupiter.api.AfterEach;
"import org.junit.jupiter.api.BeforeEach;", import org.junit.jupiter.api.BeforeAll;
"import org.junit.jupiter.api.RepeatedTest;", import org.junit.jupiter.api.BeforeEach;
"import org.junit.jupiter.api.Test;", import org.junit.jupiter.api.RepeatedTest;
"import org.junit.jupiter.params.ParameterizedTest;", import org.junit.jupiter.api.Test;
"", import org.junit.jupiter.params.ParameterizedTest;
"class A {",
" {", class A {
" arguments();", {
" }", arguments();
"", }
" @BeforeAll",
" public void setUp1() {}", @BeforeAll
"", public void setUp1() {}
" @BeforeEach",
" protected void setUp2() {}", @BeforeEach
"", protected void setUp2() {}
" @AfterEach",
" private void setUp3() {}", @AfterEach
"", private void setUp3() {}
" @AfterAll",
" private void setUp4() {}", @AfterAll
"", private void setUp4() {}
" @Test",
" void testFoo() {}", @Test
"", void testFoo() {}
" @ParameterizedTest",
" void testBar() {}", @ParameterizedTest
"", void testBar() {}
" @Test",
" public void baz() {}", @Test
"", public void baz() {}
" @RepeatedTest(2)",
" private void qux() {}", @RepeatedTest(2)
"", private void qux() {}
" @ParameterizedTest",
" protected void quux() {}", @ParameterizedTest
"", protected void quux() {}
" @Test",
" public void testToString() {}", @Test
"", public void testToString() {}
" @Test",
" public void testOverload() {}", @Test
"", public void testOverload() {}
" void overload() {}",
"", void overload() {}
" @Test",
" protected void testArguments() {}", @Test
"", protected void testArguments() {}
" @Test",
" private void testClass() {}", @Test
"", private void testClass() {}
" @Test",
" private void testTrue() {}", @Test
"}") private void testTrue() {}
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static org.junit.jupiter.params.provider.Arguments.arguments;", """
"", import static org.junit.jupiter.params.provider.Arguments.arguments;
"import org.junit.jupiter.api.AfterAll;",
"import org.junit.jupiter.api.AfterEach;", import org.junit.jupiter.api.AfterAll;
"import org.junit.jupiter.api.BeforeAll;", import org.junit.jupiter.api.AfterEach;
"import org.junit.jupiter.api.BeforeEach;", import org.junit.jupiter.api.BeforeAll;
"import org.junit.jupiter.api.RepeatedTest;", import org.junit.jupiter.api.BeforeEach;
"import org.junit.jupiter.api.Test;", import org.junit.jupiter.api.RepeatedTest;
"import org.junit.jupiter.params.ParameterizedTest;", import org.junit.jupiter.api.Test;
"", import org.junit.jupiter.params.ParameterizedTest;
"class A {",
" {", class A {
" arguments();", {
" }", arguments();
"", }
" @BeforeAll",
" void setUp1() {}", @BeforeAll
"", void setUp1() {}
" @BeforeEach",
" void setUp2() {}", @BeforeEach
"", void setUp2() {}
" @AfterEach",
" void setUp3() {}", @AfterEach
"", void setUp3() {}
" @AfterAll",
" void setUp4() {}", @AfterAll
"", void setUp4() {}
" @Test",
" void foo() {}", @Test
"", void foo() {}
" @ParameterizedTest",
" void bar() {}", @ParameterizedTest
"", void bar() {}
" @Test",
" void baz() {}", @Test
"", void baz() {}
" @RepeatedTest(2)",
" void qux() {}", @RepeatedTest(2)
"", void qux() {}
" @ParameterizedTest",
" void quux() {}", @ParameterizedTest
"", void quux() {}
" @Test",
" void testToString() {}", @Test
"", void testToString() {}
" @Test",
" void testOverload() {}", @Test
"", void testOverload() {}
" void overload() {}",
"", void overload() {}
" @Test",
" void testArguments() {}", @Test
"", void testArguments() {}
" @Test",
" void testClass() {}", @Test
"", void testClass() {}
" @Test",
" void testTrue() {}", @Test
"}") void testTrue() {}
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,25 +11,27 @@ final class JUnitNullaryParameterizedTestDeclarationTest {
CompilationTestHelper.newInstance(JUnitNullaryParameterizedTestDeclaration.class, getClass()) CompilationTestHelper.newInstance(JUnitNullaryParameterizedTestDeclaration.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import org.junit.jupiter.api.Test;", """
"import org.junit.jupiter.params.ParameterizedTest;", import org.junit.jupiter.api.Test;
"import org.junit.jupiter.params.provider.ValueSource;", import org.junit.jupiter.params.ParameterizedTest;
"", import org.junit.jupiter.params.provider.ValueSource;
"class A {",
" void nonTest() {}", class A {
"", void nonTest() {}
" @Test",
" void nonParameterizedTest() {}", @Test
"", void nonParameterizedTest() {}
" @ParameterizedTest",
" @ValueSource(ints = {0, 1})", @ParameterizedTest
" void goodParameterizedTest(int someInt) {}", @ValueSource(ints = {0, 1})
"", void goodParameterizedTest(int someInt) {}
" @ParameterizedTest",
" @ValueSource(ints = {0, 1})", @ParameterizedTest
" // BUG: Diagnostic contains:", @ValueSource(ints = {0, 1})
" void nullaryParameterizedTest() {}", // BUG: Diagnostic contains:
"}") void nullaryParameterizedTest() {}
}
""")
.doTest(); .doTest();
} }
@@ -39,117 +41,125 @@ final class JUnitNullaryParameterizedTestDeclarationTest {
JUnitNullaryParameterizedTestDeclaration.class, getClass()) JUnitNullaryParameterizedTestDeclaration.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import org.junit.jupiter.params.ParameterizedTest;", """
"import org.junit.jupiter.params.provider.ArgumentsProvider;", import org.junit.jupiter.params.ParameterizedTest;
"import org.junit.jupiter.params.provider.ArgumentsSource;", import org.junit.jupiter.params.provider.ArgumentsProvider;
"import org.junit.jupiter.params.provider.ArgumentsSources;", import org.junit.jupiter.params.provider.ArgumentsSource;
"import org.junit.jupiter.params.provider.MethodSource;", import org.junit.jupiter.params.provider.ArgumentsSources;
"import org.junit.jupiter.params.provider.ValueSource;", import org.junit.jupiter.params.provider.MethodSource;
"", import org.junit.jupiter.params.provider.ValueSource;
"class A {",
" @ParameterizedTest", class A {
" void withoutArgumentSource() {}", @ParameterizedTest
"", void withoutArgumentSource() {}
" @ParameterizedTest",
" @ArgumentsSource(ArgumentsProvider.class)", @ParameterizedTest
" void withCustomArgumentSource() {}", @ArgumentsSource(ArgumentsProvider.class)
"", void withCustomArgumentSource() {}
" @ParameterizedTest",
" @ArgumentsSources({", @ParameterizedTest
" @ArgumentsSource(ArgumentsProvider.class),", @ArgumentsSources({
" @ArgumentsSource(ArgumentsProvider.class)", @ArgumentsSource(ArgumentsProvider.class),
" })", @ArgumentsSource(ArgumentsProvider.class)
" void withCustomerArgumentSources() {}", })
"", void withCustomerArgumentSources() {}
" /** Foo. */",
" @ParameterizedTest", /** Foo. */
" @ValueSource(ints = {0, 1})", @ParameterizedTest
" void withValueSourceAndJavadoc() {}", @ValueSource(ints = {0, 1})
"", void withValueSourceAndJavadoc() {}
" @ParameterizedTest",
" @MethodSource(\"nonexistentMethod\")", @ParameterizedTest
" @SuppressWarnings(\"foo\")", @MethodSource("nonexistentMethod")
" void withMethodSourceAndUnrelatedAnnotation() {}", @SuppressWarnings("foo")
"", void withMethodSourceAndUnrelatedAnnotation() {}
" @org.junit.jupiter.params.ParameterizedTest",
" @ArgumentsSource(ArgumentsProvider.class)", @org.junit.jupiter.params.ParameterizedTest
" @ValueSource(ints = {0, 1})", @ArgumentsSource(ArgumentsProvider.class)
" @MethodSource(\"nonexistentMethod\")", @ValueSource(ints = {0, 1})
" void withMultipleArgumentSourcesAndFullyQualifiedImport() {}", @MethodSource("nonexistentMethod")
"", void withMultipleArgumentSourcesAndFullyQualifiedImport() {}
" class NestedWithTestAnnotationFirst {",
" @ParameterizedTest", class NestedWithTestAnnotationFirst {
" @ValueSource(ints = {0, 1})", @ParameterizedTest
" void withValueSource() {}", @ValueSource(ints = {0, 1})
" }", void withValueSource() {}
"", }
" class NestedWithTestAnnotationSecond {",
" @ValueSource(ints = {0, 1})", class NestedWithTestAnnotationSecond {
" @ParameterizedTest", @ValueSource(ints = {0, 1})
" void withValueSource() {}", @ParameterizedTest
" }", void withValueSource() {}
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import org.junit.jupiter.api.Test;", """
"import org.junit.jupiter.params.ParameterizedTest;", import org.junit.jupiter.api.Test;
"import org.junit.jupiter.params.provider.ArgumentsProvider;", import org.junit.jupiter.params.ParameterizedTest;
"import org.junit.jupiter.params.provider.ArgumentsSource;", import org.junit.jupiter.params.provider.ArgumentsProvider;
"import org.junit.jupiter.params.provider.ArgumentsSources;", import org.junit.jupiter.params.provider.ArgumentsSource;
"import org.junit.jupiter.params.provider.MethodSource;", import org.junit.jupiter.params.provider.ArgumentsSources;
"import org.junit.jupiter.params.provider.ValueSource;", import org.junit.jupiter.params.provider.MethodSource;
"", import org.junit.jupiter.params.provider.ValueSource;
"class A {",
" @Test", class A {
" void withoutArgumentSource() {}", @Test
"", void withoutArgumentSource() {}
" @Test",
" void withCustomArgumentSource() {}", @Test
"", void withCustomArgumentSource() {}
" @Test",
" void withCustomerArgumentSources() {}", @Test
"", void withCustomerArgumentSources() {}
" /** Foo. */",
" @Test", /** Foo. */
" void withValueSourceAndJavadoc() {}", @Test
"", void withValueSourceAndJavadoc() {}
" @Test",
" @SuppressWarnings(\"foo\")", @Test
" void withMethodSourceAndUnrelatedAnnotation() {}", @SuppressWarnings("foo")
"", void withMethodSourceAndUnrelatedAnnotation() {}
" @Test",
" void withMultipleArgumentSourcesAndFullyQualifiedImport() {}", @Test
"", void withMultipleArgumentSourcesAndFullyQualifiedImport() {}
" class NestedWithTestAnnotationFirst {",
" @Test", class NestedWithTestAnnotationFirst {
" void withValueSource() {}", @Test
" }", void withValueSource() {}
"", }
" class NestedWithTestAnnotationSecond {",
" @Test", class NestedWithTestAnnotationSecond {
" void withValueSource() {}", @Test
" }", void withValueSource() {}
"}") }
}
""")
.addInputLines( .addInputLines(
"B.java", "B.java",
"import org.junit.jupiter.params.ParameterizedTest;", """
"", import org.junit.jupiter.params.ParameterizedTest;
"class B {",
" @ParameterizedTest", class B {
" void scopeInWhichIdentifierTestIsAlreadyDeclared() {}", @ParameterizedTest
"", void scopeInWhichIdentifierTestIsAlreadyDeclared() {}
" class Test {}",
"}") class Test {}
}
""")
.addOutputLines( .addOutputLines(
"B.java", "B.java",
"import org.junit.jupiter.params.ParameterizedTest;", """
"", import org.junit.jupiter.params.ParameterizedTest;
"class B {",
" @org.junit.jupiter.api.Test", class B {
" void scopeInWhichIdentifierTestIsAlreadyDeclared() {}", @org.junit.jupiter.api.Test
"", void scopeInWhichIdentifierTestIsAlreadyDeclared() {}
" class Test {}",
"}") class Test {}
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,189 +11,191 @@ final class JUnitValueSourceTest {
CompilationTestHelper.newInstance(JUnitValueSource.class, getClass()) CompilationTestHelper.newInstance(JUnitValueSource.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static org.junit.jupiter.params.provider.Arguments.arguments;", """
"", import static org.junit.jupiter.params.provider.Arguments.arguments;
"import java.util.Optional;",
"import java.util.stream.Stream;", import java.util.Optional;
"import org.junit.jupiter.params.ParameterizedTest;", import java.util.stream.Stream;
"import org.junit.jupiter.params.provider.Arguments;", import org.junit.jupiter.params.ParameterizedTest;
"import org.junit.jupiter.params.provider.MethodSource;", import org.junit.jupiter.params.provider.Arguments;
"", import org.junit.jupiter.params.provider.MethodSource;
"class A {",
" private static Stream<Arguments> identificationTestCases() {", class A {
" return Stream.of(arguments(1), Arguments.of(2));", private static Stream<Arguments> identificationTestCases() {
" }", return Stream.of(arguments(1), Arguments.of(2));
"", }
" @ParameterizedTest",
" // BUG: Diagnostic contains:", @ParameterizedTest
" @MethodSource(\"identificationTestCases\")", // BUG: Diagnostic contains:
" void identification(int foo) {}", @MethodSource("identificationTestCases")
"", void identification(int foo) {}
" private static int[] identificationWithParensTestCases() {",
" return new int[] {1, 2};", private static int[] identificationWithParensTestCases() {
" }", return new int[] {1, 2};
"", }
" @ParameterizedTest",
" // BUG: Diagnostic contains:", @ParameterizedTest
" @MethodSource(\"identificationWithParensTestCases()\")", // BUG: Diagnostic contains:
" void identificationWithParens(int foo) {}", @MethodSource("identificationWithParensTestCases()")
"", void identificationWithParens(int foo) {}
" @ParameterizedTest",
" @MethodSource(\"valueFactoryMissingTestCases\")", @ParameterizedTest
" void valueFactoryMissing(int foo) {}", @MethodSource("valueFactoryMissingTestCases")
"", void valueFactoryMissing(int foo) {}
" private static Stream<Arguments> multipleUsagesTestCases() {",
" return Stream.of(arguments(1), Arguments.of(2));", private static Stream<Arguments> multipleUsagesTestCases() {
" }", return Stream.of(arguments(1), Arguments.of(2));
"", }
" @ParameterizedTest",
" @MethodSource(\"multipleUsagesTestCases\")", @ParameterizedTest
" void multipleUsages1(int foo) {}", @MethodSource("multipleUsagesTestCases")
"", void multipleUsages1(int foo) {}
" @ParameterizedTest",
" @MethodSource(\"multipleUsagesTestCases()\")", @ParameterizedTest
" void multipleUsages2(int bar) {}", @MethodSource("multipleUsagesTestCases()")
"", void multipleUsages2(int bar) {}
" private static Stream<Arguments> valueFactoryRepeatedTestCases() {",
" return Stream.of(arguments(1), arguments(2));", private static Stream<Arguments> valueFactoryRepeatedTestCases() {
" }", return Stream.of(arguments(1), arguments(2));
"", }
" @ParameterizedTest",
" @MethodSource({\"valueFactoryRepeatedTestCases\", \"valueFactoryRepeatedTestCases\"})", @ParameterizedTest
" void valueFactoryRepeated(int foo) {}", @MethodSource({"valueFactoryRepeatedTestCases", "valueFactoryRepeatedTestCases"})
"", void valueFactoryRepeated(int foo) {}
" private static Stream<Arguments> multipleParametersTestCases() {",
" return Stream.of(arguments(1, 2), arguments(3, 4));", private static Stream<Arguments> multipleParametersTestCases() {
" }", return Stream.of(arguments(1, 2), arguments(3, 4));
"", }
" @ParameterizedTest",
" @MethodSource(\"multipleParametersTestCases\")", @ParameterizedTest
" void multipleParameters(int first, int second) {}", @MethodSource("multipleParametersTestCases")
"", void multipleParameters(int first, int second) {}
" private static int[] arrayWithoutInitializersTestCases() {",
" return new int[1];", private static int[] arrayWithoutInitializersTestCases() {
" }", return new int[1];
"", }
" @ParameterizedTest",
" @MethodSource(\"arrayWithoutInitializersTestCases\")", @ParameterizedTest
" void arrayWithoutInitializers(int foo) {}", @MethodSource("arrayWithoutInitializersTestCases")
"", void arrayWithoutInitializers(int foo) {}
" private static Stream<Arguments> runtimeValueTestCases() {",
" int second = 2;", private static Stream<Arguments> runtimeValueTestCases() {
" return Stream.of(arguments(1), arguments(second));", int second = 2;
" }", return Stream.of(arguments(1), arguments(second));
"", }
" @ParameterizedTest",
" @MethodSource(\"runtimeValueTestCases\")", @ParameterizedTest
" void runtimeValue(int foo) {}", @MethodSource("runtimeValueTestCases")
"", void runtimeValue(int foo) {}
" private static Stream<Arguments> streamChainTestCases() {",
" return Stream.of(1, 2).map(Arguments::arguments);", private static Stream<Arguments> streamChainTestCases() {
" }", return Stream.of(1, 2).map(Arguments::arguments);
"", }
" @ParameterizedTest",
" @MethodSource(\"streamChainTestCases\")", @ParameterizedTest
" void streamChain(int number) {}", @MethodSource("streamChainTestCases")
"", void streamChain(int number) {}
" private static Stream<Arguments> multipleReturnsTestCases() {",
" if (true) {", private static Stream<Arguments> multipleReturnsTestCases() {
" return Stream.of(arguments(1), arguments(2));", if (true) {
" } else {", return Stream.of(arguments(1), arguments(2));
" return Stream.of(arguments(3), arguments(4));", } else {
" }", return Stream.of(arguments(3), arguments(4));
" }", }
"", }
" @ParameterizedTest",
" @MethodSource(\"multipleReturnsTestCases\")", @ParameterizedTest
" void multipleReturns(int number) {}", @MethodSource("multipleReturnsTestCases")
"", void multipleReturns(int number) {}
" private static Stream<Arguments> multipleFactoriesFooTestCases() {",
" return Stream.of(arguments(1));", private static Stream<Arguments> multipleFactoriesFooTestCases() {
" }", return Stream.of(arguments(1));
"", }
" private static Stream<Arguments> multipleFactoriesBarTestCases() {",
" return Stream.of(arguments(1));", private static Stream<Arguments> multipleFactoriesBarTestCases() {
" }", return Stream.of(arguments(1));
"", }
" @ParameterizedTest",
" @MethodSource({\"multipleFactoriesFooTestCases\", \"multipleFactoriesBarTestCases\"})", @ParameterizedTest
" void multipleFactories(int i) {}", @MethodSource({"multipleFactoriesFooTestCases", "multipleFactoriesBarTestCases"})
"", void multipleFactories(int i) {}
" private static Stream<Arguments> extraArgsTestCases() {",
" return Stream.of(arguments(1), arguments(1, 2));", private static Stream<Arguments> extraArgsTestCases() {
" }", return Stream.of(arguments(1), arguments(1, 2));
"", }
" @ParameterizedTest",
" @MethodSource(\"extraArgsTestCases\")", @ParameterizedTest
" void extraArgs(int... i) {}", @MethodSource("extraArgsTestCases")
"", void extraArgs(int... i) {}
" private static Stream<Arguments> localClassTestCases() {",
" class Foo {", private static Stream<Arguments> localClassTestCases() {
" Stream<Arguments> foo() {", class Foo {
" return Stream.of(arguments(1), arguments(2));", Stream<Arguments> foo() {
" }", return Stream.of(arguments(1), arguments(2));
" }", }
" return Stream.of(arguments(1), arguments(2));", }
" }", return Stream.of(arguments(1), arguments(2));
"", }
" @ParameterizedTest",
" // BUG: Diagnostic contains:", @ParameterizedTest
" @MethodSource(\"localClassTestCases\")", // BUG: Diagnostic contains:
" void localClass(int i) {}", @MethodSource("localClassTestCases")
"", void localClass(int i) {}
" private static Stream<Arguments> lambdaReturnTestCases() {",
" int foo =", private static Stream<Arguments> lambdaReturnTestCases() {
" Optional.of(10)", int foo =
" .map(", Optional.of(10)
" i -> {", .map(
" return i / 2;", i -> {
" })", return i / 2;
" .orElse(0);", })
" return Stream.of(arguments(1), arguments(1));", .orElse(0);
" }", return Stream.of(arguments(1), arguments(1));
"", }
" @ParameterizedTest",
" // BUG: Diagnostic contains:", @ParameterizedTest
" @MethodSource(\"lambdaReturnTestCases\")", // BUG: Diagnostic contains:
" void lambdaReturn(int i) {}", @MethodSource("lambdaReturnTestCases")
"", void lambdaReturn(int i) {}
" @ParameterizedTest",
" @MethodSource(\"tech.picnic.errorprone.Foo#fooTestCases\")", @ParameterizedTest
" void staticMethodReference(int foo) {}", @MethodSource("tech.picnic.errorprone.Foo#fooTestCases")
"", void staticMethodReference(int foo) {}
" private static Stream<Arguments> valueFactoryWithArgumentTestCases(int amount) {",
" return Stream.of(arguments(1), arguments(2));", private static Stream<Arguments> valueFactoryWithArgumentTestCases(int amount) {
" }", return Stream.of(arguments(1), arguments(2));
"", }
" @ParameterizedTest",
" // BUG: Diagnostic contains:", @ParameterizedTest
" @MethodSource(\"valueFactoryWithArgumentTestCases\")", // BUG: Diagnostic contains:
" void valueFactoryWithArgument(int foo) {}", @MethodSource("valueFactoryWithArgumentTestCases")
"", void valueFactoryWithArgument(int foo) {}
" private static Arguments[] emptyArrayValueFactoryTestCases() {",
" return new Arguments[] {};", private static Arguments[] emptyArrayValueFactoryTestCases() {
" }", return new Arguments[] {};
"", }
" @ParameterizedTest",
" @MethodSource(\"emptyArrayValueFactoryTestCases\")", @ParameterizedTest
" void emptyArrayValueFactory(int foo) {}", @MethodSource("emptyArrayValueFactoryTestCases")
"", void emptyArrayValueFactory(int foo) {}
" private static Stream<Arguments> emptyStreamValueFactoryTestCases() {",
" return Stream.of();", private static Stream<Arguments> emptyStreamValueFactoryTestCases() {
" }", return Stream.of();
"", }
" @ParameterizedTest",
" @MethodSource(\"emptyStreamValueFactoryTestCases\")", @ParameterizedTest
" void emptyStreamValueFactory(int foo) {}", @MethodSource("emptyStreamValueFactoryTestCases")
"", void emptyStreamValueFactory(int foo) {}
" private static Arguments[] invalidValueFactoryArgumentsTestCases() {",
" return new Arguments[] {arguments(1), arguments(new Object() {})};", private static Arguments[] invalidValueFactoryArgumentsTestCases() {
" }", return new Arguments[] {arguments(1), arguments(new Object() {})};
"", }
" @ParameterizedTest",
" @MethodSource(\"invalidValueFactoryArgumentsTestCases\")", @ParameterizedTest
" void invalidValueFactoryArguments(int foo) {}", @MethodSource("invalidValueFactoryArgumentsTestCases")
"}") void invalidValueFactoryArguments(int foo) {}
}
""")
.doTest(); .doTest();
} }
@@ -202,295 +204,299 @@ final class JUnitValueSourceTest {
BugCheckerRefactoringTestHelper.newInstance(JUnitValueSource.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(JUnitValueSource.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static org.junit.jupiter.params.provider.Arguments.arguments;", """
"", import static org.junit.jupiter.params.provider.Arguments.arguments;
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import java.util.List;", import com.google.common.collect.ImmutableSet;
"import java.util.Set;", import java.util.List;
"import java.util.stream.DoubleStream;", import java.util.Set;
"import java.util.stream.IntStream;", import java.util.stream.DoubleStream;
"import java.util.stream.LongStream;", import java.util.stream.IntStream;
"import java.util.stream.Stream;", import java.util.stream.LongStream;
"import org.junit.jupiter.params.ParameterizedTest;", import java.util.stream.Stream;
"import org.junit.jupiter.params.provider.Arguments;", import org.junit.jupiter.params.ParameterizedTest;
"import org.junit.jupiter.params.provider.MethodSource;", import org.junit.jupiter.params.provider.Arguments;
"", import org.junit.jupiter.params.provider.MethodSource;
"class A {",
" private static final boolean CONST_BOOLEAN = false;", class A {
" private static final byte CONST_BYTE = 42;", private static final boolean CONST_BOOLEAN = false;
" private static final char CONST_CHARACTER = 'a';", private static final byte CONST_BYTE = 42;
" private static final short CONST_SHORT = 42;", private static final char CONST_CHARACTER = 'a';
" private static final int CONST_INTEGER = 42;", private static final short CONST_SHORT = 42;
" private static final long CONST_LONG = 42;", private static final int CONST_INTEGER = 42;
" private static final float CONST_FLOAT = 42;", private static final long CONST_LONG = 42;
" private static final double CONST_DOUBLE = 42;", private static final float CONST_FLOAT = 42;
" private static final String CONST_STRING = \"foo\";", private static final double CONST_DOUBLE = 42;
"", private static final String CONST_STRING = "foo";
" private static Stream<Arguments> streamOfBooleanArguments() {",
" return Stream.of(arguments(false), arguments(true), arguments(CONST_BOOLEAN));", private static Stream<Arguments> streamOfBooleanArguments() {
" }", return Stream.of(arguments(false), arguments(true), arguments(CONST_BOOLEAN));
"", }
" @ParameterizedTest",
" @MethodSource(\"streamOfBooleanArguments\")", @ParameterizedTest
" void primitiveBoolean(boolean b) {}", @MethodSource("streamOfBooleanArguments")
"", void primitiveBoolean(boolean b) {}
" private static Stream<Object> streamOfBooleansAndBooleanArguments() {",
" return Stream.of(false, arguments(true), CONST_BOOLEAN);", private static Stream<Object> streamOfBooleansAndBooleanArguments() {
" }", return Stream.of(false, arguments(true), CONST_BOOLEAN);
"", }
" @ParameterizedTest",
" @MethodSource(\"streamOfBooleansAndBooleanArguments\")", @ParameterizedTest
" void boxedBoolean(Boolean b) {}", @MethodSource("streamOfBooleansAndBooleanArguments")
"", void boxedBoolean(Boolean b) {}
" private static List<Arguments> listOfByteArguments() {",
" return List.of(arguments((byte) 0), arguments((byte) 1), arguments(CONST_BYTE));", private static List<Arguments> listOfByteArguments() {
" }", return List.of(arguments((byte) 0), arguments((byte) 1), arguments(CONST_BYTE));
"", }
" @ParameterizedTest",
" @MethodSource(\"listOfByteArguments\")", @ParameterizedTest
" void primitiveByte(byte b) {}", @MethodSource("listOfByteArguments")
"", void primitiveByte(byte b) {}
" private static List<Object> listOfBytesAndByteArguments() {",
" return List.of((byte) 0, arguments((byte) 1), CONST_BYTE);", private static List<Object> listOfBytesAndByteArguments() {
" }", return List.of((byte) 0, arguments((byte) 1), CONST_BYTE);
"", }
" @ParameterizedTest",
" @MethodSource(\"listOfBytesAndByteArguments\")", @ParameterizedTest
" void boxedByte(Byte b) {}", @MethodSource("listOfBytesAndByteArguments")
"", void boxedByte(Byte b) {}
" private static Set<Arguments> setOfCharacterArguments() {",
" return Set.of(arguments((char) 0), arguments((char) 1), arguments(CONST_CHARACTER));", private static Set<Arguments> setOfCharacterArguments() {
" }", return Set.of(arguments((char) 0), arguments((char) 1), arguments(CONST_CHARACTER));
"", }
" @ParameterizedTest",
" @MethodSource(\"setOfCharacterArguments\")", @ParameterizedTest
" void primitiveCharacter(char c) {}", @MethodSource("setOfCharacterArguments")
"", void primitiveCharacter(char c) {}
" private static Set<Object> setOfCharactersAndCharacterArguments() {",
" return Set.of((char) 0, arguments((char) 1), CONST_CHARACTER);", private static Set<Object> setOfCharactersAndCharacterArguments() {
" }", return Set.of((char) 0, arguments((char) 1), CONST_CHARACTER);
"", }
" @ParameterizedTest",
" @MethodSource(\"setOfCharactersAndCharacterArguments\")", @ParameterizedTest
" void boxedCharacter(Character c) {}", @MethodSource("setOfCharactersAndCharacterArguments")
"", void boxedCharacter(Character c) {}
" private static Arguments[] arrayOfShortArguments() {",
" return new Arguments[] {arguments((short) 0), arguments((short) 1), arguments(CONST_SHORT)};", private static Arguments[] arrayOfShortArguments() {
" }", return new Arguments[] {arguments((short) 0), arguments((short) 1), arguments(CONST_SHORT)};
"", }
" @ParameterizedTest",
" @MethodSource(\"arrayOfShortArguments\")", @ParameterizedTest
" void primitiveShort(short s) {}", @MethodSource("arrayOfShortArguments")
"", void primitiveShort(short s) {}
" private static Object[] arrayOfShortsAndShortArguments() {",
" return new Object[] {(short) 0, arguments((short) 1), CONST_SHORT};", private static Object[] arrayOfShortsAndShortArguments() {
" }", return new Object[] {(short) 0, arguments((short) 1), CONST_SHORT};
"", }
" @ParameterizedTest",
" @MethodSource(\"arrayOfShortsAndShortArguments\")", @ParameterizedTest
" void boxedShort(Short s) {}", @MethodSource("arrayOfShortsAndShortArguments")
"", void boxedShort(Short s) {}
" private static IntStream intStream() {",
" return IntStream.of(0, 1, CONST_INTEGER);", private static IntStream intStream() {
" }", return IntStream.of(0, 1, CONST_INTEGER);
"", }
" @ParameterizedTest",
" @MethodSource(\"intStream\")", @ParameterizedTest
" void primitiveInteger(int i) {}", @MethodSource("intStream")
"", void primitiveInteger(int i) {}
" private static int[] intArray() {",
" return new int[] {0, 1, CONST_INTEGER};", private static int[] intArray() {
" }", return new int[] {0, 1, CONST_INTEGER};
"", }
" @ParameterizedTest",
" @MethodSource(\"intArray\")", @ParameterizedTest
" void boxedInteger(Integer i) {}", @MethodSource("intArray")
"", void boxedInteger(Integer i) {}
" private static LongStream longStream() {",
" return LongStream.of(0, 1, CONST_LONG);", private static LongStream longStream() {
" }", return LongStream.of(0, 1, CONST_LONG);
"", }
" @ParameterizedTest",
" @MethodSource(\"longStream\")", @ParameterizedTest
" void primitiveLong(long l) {}", @MethodSource("longStream")
"", void primitiveLong(long l) {}
" private static long[] longArray() {",
" return new long[] {0, 1, CONST_LONG};", private static long[] longArray() {
" }", return new long[] {0, 1, CONST_LONG};
"", }
" @ParameterizedTest",
" @MethodSource(\"longArray\")", @ParameterizedTest
" void boxedLong(Long l) {}", @MethodSource("longArray")
"", void boxedLong(Long l) {}
" private static ImmutableList<Arguments> immutableListOfFloatArguments() {",
" return ImmutableList.of(arguments(0.0F), arguments(1.0F), arguments(CONST_FLOAT));", private static ImmutableList<Arguments> immutableListOfFloatArguments() {
" }", return ImmutableList.of(arguments(0.0F), arguments(1.0F), arguments(CONST_FLOAT));
"", }
" @ParameterizedTest",
" @MethodSource(\"immutableListOfFloatArguments\")", @ParameterizedTest
" void primitiveFloat(float f) {}", @MethodSource("immutableListOfFloatArguments")
"", void primitiveFloat(float f) {}
" private static Stream<Object> streamOfFloatsAndFloatArguments() {",
" return Stream.of(0.0F, arguments(1.0F), CONST_FLOAT);", private static Stream<Object> streamOfFloatsAndFloatArguments() {
" }", return Stream.of(0.0F, arguments(1.0F), CONST_FLOAT);
"", }
" @ParameterizedTest",
" @MethodSource(\"streamOfFloatsAndFloatArguments\")", @ParameterizedTest
" void boxedFloat(Float f) {}", @MethodSource("streamOfFloatsAndFloatArguments")
"", void boxedFloat(Float f) {}
" private static DoubleStream doubleStream() {",
" return DoubleStream.of(0, 1, CONST_DOUBLE);", private static DoubleStream doubleStream() {
" }", return DoubleStream.of(0, 1, CONST_DOUBLE);
"", }
" @ParameterizedTest",
" @MethodSource(\"doubleStream\")", @ParameterizedTest
" void primitiveDouble(double d) {}", @MethodSource("doubleStream")
"", void primitiveDouble(double d) {}
" private static double[] doubleArray() {",
" return new double[] {0, 1, CONST_DOUBLE};", private static double[] doubleArray() {
" }", return new double[] {0, 1, CONST_DOUBLE};
"", }
" @ParameterizedTest",
" @MethodSource(\"doubleArray\")", @ParameterizedTest
" void boxedDouble(Double d) {}", @MethodSource("doubleArray")
"", void boxedDouble(Double d) {}
" private static ImmutableSet<Arguments> immutableSetOfStringArguments() {",
" return ImmutableSet.of(arguments(\"foo\"), arguments(\"bar\"), arguments(CONST_STRING));", private static ImmutableSet<Arguments> immutableSetOfStringArguments() {
" }", return ImmutableSet.of(arguments("foo"), arguments("bar"), arguments(CONST_STRING));
"", }
" @ParameterizedTest",
" @MethodSource(\"immutableSetOfStringArguments\")", @ParameterizedTest
" void string(String s) {}", @MethodSource("immutableSetOfStringArguments")
"", void string(String s) {}
" private static Stream<Class<?>> streamOfClasses() {",
" return Stream.of(Stream.class, java.util.Map.class);", private static Stream<Class<?>> streamOfClasses() {
" }", return Stream.of(Stream.class, java.util.Map.class);
"", }
" @ParameterizedTest",
" @MethodSource(\"streamOfClasses\")", @ParameterizedTest
" void clazz(Class<?> c) {}", @MethodSource("streamOfClasses")
"", void clazz(Class<?> c) {}
" private static Stream<Arguments> sameNameFactoryTestCases() {",
" return Stream.of(arguments(1));", private static Stream<Arguments> sameNameFactoryTestCases() {
" }", return Stream.of(arguments(1));
"", }
" private static Stream<Arguments> sameNameFactoryTestCases(int overload) {",
" return Stream.of(arguments(overload));", private static Stream<Arguments> sameNameFactoryTestCases(int overload) {
" }", return Stream.of(arguments(overload));
"", }
" @ParameterizedTest",
" @MethodSource(\"sameNameFactoryTestCases\")", @ParameterizedTest
" void sameNameFactory(int i) {}", @MethodSource("sameNameFactoryTestCases")
"}") void sameNameFactory(int i) {}
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static org.junit.jupiter.params.provider.Arguments.arguments;", """
"", import static org.junit.jupiter.params.provider.Arguments.arguments;
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import java.util.List;", import com.google.common.collect.ImmutableSet;
"import java.util.Set;", import java.util.List;
"import java.util.stream.DoubleStream;", import java.util.Set;
"import java.util.stream.IntStream;", import java.util.stream.DoubleStream;
"import java.util.stream.LongStream;", import java.util.stream.IntStream;
"import java.util.stream.Stream;", import java.util.stream.LongStream;
"import org.junit.jupiter.params.ParameterizedTest;", import java.util.stream.Stream;
"import org.junit.jupiter.params.provider.Arguments;", import org.junit.jupiter.params.ParameterizedTest;
"import org.junit.jupiter.params.provider.MethodSource;", import org.junit.jupiter.params.provider.Arguments;
"import org.junit.jupiter.params.provider.ValueSource;", import org.junit.jupiter.params.provider.MethodSource;
"", import org.junit.jupiter.params.provider.ValueSource;
"class A {",
" private static final boolean CONST_BOOLEAN = false;", class A {
" private static final byte CONST_BYTE = 42;", private static final boolean CONST_BOOLEAN = false;
" private static final char CONST_CHARACTER = 'a';", private static final byte CONST_BYTE = 42;
" private static final short CONST_SHORT = 42;", private static final char CONST_CHARACTER = 'a';
" private static final int CONST_INTEGER = 42;", private static final short CONST_SHORT = 42;
" private static final long CONST_LONG = 42;", private static final int CONST_INTEGER = 42;
" private static final float CONST_FLOAT = 42;", private static final long CONST_LONG = 42;
" private static final double CONST_DOUBLE = 42;", private static final float CONST_FLOAT = 42;
" private static final String CONST_STRING = \"foo\";", private static final double CONST_DOUBLE = 42;
"", private static final String CONST_STRING = "foo";
" @ParameterizedTest",
" @ValueSource(booleans = {false, true, CONST_BOOLEAN})", @ParameterizedTest
" void primitiveBoolean(boolean b) {}", @ValueSource(booleans = {false, true, CONST_BOOLEAN})
"", void primitiveBoolean(boolean b) {}
" @ParameterizedTest",
" @ValueSource(booleans = {false, true, CONST_BOOLEAN})", @ParameterizedTest
" void boxedBoolean(Boolean b) {}", @ValueSource(booleans = {false, true, CONST_BOOLEAN})
"", void boxedBoolean(Boolean b) {}
" @ParameterizedTest",
" @ValueSource(bytes = {(byte) 0, (byte) 1, CONST_BYTE})", @ParameterizedTest
" void primitiveByte(byte b) {}", @ValueSource(bytes = {(byte) 0, (byte) 1, CONST_BYTE})
"", void primitiveByte(byte b) {}
" @ParameterizedTest",
" @ValueSource(bytes = {(byte) 0, (byte) 1, CONST_BYTE})", @ParameterizedTest
" void boxedByte(Byte b) {}", @ValueSource(bytes = {(byte) 0, (byte) 1, CONST_BYTE})
"", void boxedByte(Byte b) {}
" @ParameterizedTest",
" @ValueSource(chars = {(char) 0, (char) 1, CONST_CHARACTER})", @ParameterizedTest
" void primitiveCharacter(char c) {}", @ValueSource(chars = {(char) 0, (char) 1, CONST_CHARACTER})
"", void primitiveCharacter(char c) {}
" @ParameterizedTest",
" @ValueSource(chars = {(char) 0, (char) 1, CONST_CHARACTER})", @ParameterizedTest
" void boxedCharacter(Character c) {}", @ValueSource(chars = {(char) 0, (char) 1, CONST_CHARACTER})
"", void boxedCharacter(Character c) {}
" @ParameterizedTest",
" @ValueSource(shorts = {(short) 0, (short) 1, CONST_SHORT})", @ParameterizedTest
" void primitiveShort(short s) {}", @ValueSource(shorts = {(short) 0, (short) 1, CONST_SHORT})
"", void primitiveShort(short s) {}
" @ParameterizedTest",
" @ValueSource(shorts = {(short) 0, (short) 1, CONST_SHORT})", @ParameterizedTest
" void boxedShort(Short s) {}", @ValueSource(shorts = {(short) 0, (short) 1, CONST_SHORT})
"", void boxedShort(Short s) {}
" @ParameterizedTest",
" @ValueSource(ints = {0, 1, CONST_INTEGER})", @ParameterizedTest
" void primitiveInteger(int i) {}", @ValueSource(ints = {0, 1, CONST_INTEGER})
"", void primitiveInteger(int i) {}
" @ParameterizedTest",
" @ValueSource(ints = {0, 1, CONST_INTEGER})", @ParameterizedTest
" void boxedInteger(Integer i) {}", @ValueSource(ints = {0, 1, CONST_INTEGER})
"", void boxedInteger(Integer i) {}
" @ParameterizedTest",
" @ValueSource(longs = {0, 1, CONST_LONG})", @ParameterizedTest
" void primitiveLong(long l) {}", @ValueSource(longs = {0, 1, CONST_LONG})
"", void primitiveLong(long l) {}
" @ParameterizedTest",
" @ValueSource(longs = {0, 1, CONST_LONG})", @ParameterizedTest
" void boxedLong(Long l) {}", @ValueSource(longs = {0, 1, CONST_LONG})
"", void boxedLong(Long l) {}
" @ParameterizedTest",
" @ValueSource(floats = {0.0F, 1.0F, CONST_FLOAT})", @ParameterizedTest
" void primitiveFloat(float f) {}", @ValueSource(floats = {0.0F, 1.0F, CONST_FLOAT})
"", void primitiveFloat(float f) {}
" @ParameterizedTest",
" @ValueSource(floats = {0.0F, 1.0F, CONST_FLOAT})", @ParameterizedTest
" void boxedFloat(Float f) {}", @ValueSource(floats = {0.0F, 1.0F, CONST_FLOAT})
"", void boxedFloat(Float f) {}
" @ParameterizedTest",
" @ValueSource(doubles = {0, 1, CONST_DOUBLE})", @ParameterizedTest
" void primitiveDouble(double d) {}", @ValueSource(doubles = {0, 1, CONST_DOUBLE})
"", void primitiveDouble(double d) {}
" @ParameterizedTest",
" @ValueSource(doubles = {0, 1, CONST_DOUBLE})", @ParameterizedTest
" void boxedDouble(Double d) {}", @ValueSource(doubles = {0, 1, CONST_DOUBLE})
"", void boxedDouble(Double d) {}
" @ParameterizedTest",
" @ValueSource(strings = {\"foo\", \"bar\", CONST_STRING})", @ParameterizedTest
" void string(String s) {}", @ValueSource(strings = {"foo", "bar", CONST_STRING})
"", void string(String s) {}
" @ParameterizedTest",
" @ValueSource(classes = {Stream.class, java.util.Map.class})", @ParameterizedTest
" void clazz(Class<?> c) {}", @ValueSource(classes = {Stream.class, java.util.Map.class})
"", void clazz(Class<?> c) {}
" private static Stream<Arguments> sameNameFactoryTestCases(int overload) {",
" return Stream.of(arguments(overload));", private static Stream<Arguments> sameNameFactoryTestCases(int overload) {
" }", return Stream.of(arguments(overload));
"", }
" @ParameterizedTest",
" @ValueSource(ints = 1)", @ParameterizedTest
" void sameNameFactory(int i) {}", @ValueSource(ints = 1)
"}") void sameNameFactory(int i) {}
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,176 +11,178 @@ final class LexicographicalAnnotationAttributeListingTest {
CompilationTestHelper.newInstance(LexicographicalAnnotationAttributeListing.class, getClass()) CompilationTestHelper.newInstance(LexicographicalAnnotationAttributeListing.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static java.math.RoundingMode.DOWN;", """
"import static java.math.RoundingMode.UP;", import static java.math.RoundingMode.DOWN;
"", import static java.math.RoundingMode.UP;
"import com.fasterxml.jackson.annotation.JsonPropertyOrder;",
"import io.swagger.annotations.ApiImplicitParam;", import com.fasterxml.jackson.annotation.JsonPropertyOrder;
"import io.swagger.annotations.ApiImplicitParams;", import io.swagger.annotations.ApiImplicitParam;
"import io.swagger.v3.oas.annotations.Parameter;", import io.swagger.annotations.ApiImplicitParams;
"import io.swagger.v3.oas.annotations.Parameters;", import io.swagger.v3.oas.annotations.Parameter;
"import java.math.RoundingMode;", import io.swagger.v3.oas.annotations.Parameters;
"import javax.xml.bind.annotation.XmlType;", import java.math.RoundingMode;
"import org.springframework.context.annotation.PropertySource;", import javax.xml.bind.annotation.XmlType;
"import org.springframework.test.context.TestPropertySource;", import org.springframework.context.annotation.PropertySource;
"", import org.springframework.test.context.TestPropertySource;
"interface A {",
" @interface Foo {", interface A {
" String[] value() default {};", @interface Foo {
"", String[] value() default {};
" boolean[] bools() default {};",
"", boolean[] bools() default {};
" char[] chars() default {};",
"", char[] chars() default {};
" int[] ints() default {};",
"", int[] ints() default {};
" Class<?>[] cls() default {};",
"", Class<?>[] cls() default {};
" RoundingMode[] enums() default {};",
"", RoundingMode[] enums() default {};
" Bar[] anns() default {};",
" }", Bar[] anns() default {};
"", }
" @interface Bar {",
" String[] value() default {};", @interface Bar {
" }", String[] value() default {};
"", }
" @Foo({})",
" A noString();", @Foo({})
"", A noString();
" @Foo({\"a\"})",
" A oneString();", @Foo({"a"})
"", A oneString();
" @Foo({\"a\", \"b\"})",
" A sortedStrings();", @Foo({"a", "b"})
"", A sortedStrings();
" // BUG: Diagnostic contains:",
" @Foo({\"b\", \"a\"})", // BUG: Diagnostic contains:
" A unsortedString();", @Foo({"b", "a"})
"", A unsortedString();
" @Foo({\"ab\", \"Ac\"})",
" A sortedStringCaseInsensitive();", @Foo({"ab", "Ac"})
"", A sortedStringCaseInsensitive();
" // BUG: Diagnostic contains:",
" @Foo({\"ac\", \"Ab\"})", // BUG: Diagnostic contains:
" A unsortedStringCaseInsensitive();", @Foo({"ac", "Ab"})
"", A unsortedStringCaseInsensitive();
" @Foo({\"A\", \"a\"})",
" A sortedStringCaseInsensitiveWithTotalOrderFallback();", @Foo({"A", "a"})
"", A sortedStringCaseInsensitiveWithTotalOrderFallback();
" // BUG: Diagnostic contains:",
" @Foo({\"a\", \"A\"})", // BUG: Diagnostic contains:
" A unsortedStringCaseInsensitiveWithTotalOrderFallback();", @Foo({"a", "A"})
"", A unsortedStringCaseInsensitiveWithTotalOrderFallback();
" @Foo(bools = {})",
" A noBools();", @Foo(bools = {})
"", A noBools();
" @Foo(bools = {false})",
" A oneBool();", @Foo(bools = {false})
"", A oneBool();
" @Foo(bools = {false, true})",
" A sortedBools();", @Foo(bools = {false, true})
"", A sortedBools();
" // BUG: Diagnostic contains:",
" @Foo(bools = {true, false})", // BUG: Diagnostic contains:
" A unsortedBools();", @Foo(bools = {true, false})
"", A unsortedBools();
" @Foo(chars = {})",
" A noChars();", @Foo(chars = {})
"", A noChars();
" @Foo(chars = {'a'})",
" A oneChar();", @Foo(chars = {'a'})
"", A oneChar();
" @Foo(chars = {'a', 'b'})",
" A sortedChars();", @Foo(chars = {'a', 'b'})
"", A sortedChars();
" // BUG: Diagnostic contains:",
" @Foo(chars = {'b', 'a'})", // BUG: Diagnostic contains:
" A unsortedChars();", @Foo(chars = {'b', 'a'})
"", A unsortedChars();
" @Foo(ints = {})",
" A noInts();", @Foo(ints = {})
"", A noInts();
" @Foo(ints = {0})",
" A oneInt();", @Foo(ints = {0})
"", A oneInt();
" @Foo(ints = {0, 1})",
" A sortedInts();", @Foo(ints = {0, 1})
"", A sortedInts();
" @Foo(ints = {1, 0})",
" A unsortedInts();", @Foo(ints = {1, 0})
"", A unsortedInts();
" @Foo(cls = {})",
" A noClasses();", @Foo(cls = {})
"", A noClasses();
" @Foo(cls = {int.class})",
" A oneClass();", @Foo(cls = {int.class})
"", A oneClass();
" @Foo(cls = {int.class, long.class})",
" A sortedClasses();", @Foo(cls = {int.class, long.class})
"", A sortedClasses();
" // BUG: Diagnostic contains:",
" @Foo(cls = {long.class, int.class})", // BUG: Diagnostic contains:
" A unsortedClasses();", @Foo(cls = {long.class, int.class})
"", A unsortedClasses();
" @Foo(enums = {})",
" A noEnums();", @Foo(enums = {})
"", A noEnums();
" @Foo(enums = {DOWN})",
" A oneEnum();", @Foo(enums = {DOWN})
"", A oneEnum();
" @Foo(enums = {DOWN, UP})",
" A sortedEnums();", @Foo(enums = {DOWN, UP})
"", A sortedEnums();
" // BUG: Diagnostic contains:",
" @Foo(enums = {UP, DOWN})", // BUG: Diagnostic contains:
" A unsortedEnums();", @Foo(enums = {UP, DOWN})
"", A unsortedEnums();
" @Foo(anns = {})",
" A noAnns();", @Foo(anns = {})
"", A noAnns();
" @Foo(anns = {@Bar(\"a\")})",
" A oneAnn();", @Foo(anns = {@Bar("a")})
"", A oneAnn();
" @Foo(anns = {@Bar(\"a\"), @Bar(\"b\")})",
" A sortedAnns();", @Foo(anns = {@Bar("a"), @Bar("b")})
"", A sortedAnns();
" // BUG: Diagnostic contains:",
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})", // BUG: Diagnostic contains:
" A unsortedAnns();", @Foo(anns = {@Bar("b"), @Bar("a")})
"", A unsortedAnns();
" // BUG: Diagnostic contains:",
" @Foo(anns = {@Bar(\"a\"), @Bar({\"b\", \"a\"})})", // BUG: Diagnostic contains:
" A unsortedInnderAnns();", @Foo(anns = {@Bar("a"), @Bar({"b", "a"})})
"", A unsortedInnderAnns();
" @Foo({\"a=foo\", \"a.b=bar\", \"a.c=baz\"})",
" A hierarchicallySorted();", @Foo({"a=foo", "a.b=bar", "a.c=baz"})
"", A hierarchicallySorted();
" // BUG: Diagnostic contains:",
" @Foo({\"a.b=bar\", \"a.c=baz\", \"a=foo\"})", // BUG: Diagnostic contains:
" A hierarchicallyUnsorted();", @Foo({"a.b=bar", "a.c=baz", "a=foo"})
"", A hierarchicallyUnsorted();
" @JsonPropertyOrder({\"field2\", \"field1\"})",
" A dto();", @JsonPropertyOrder({"field2", "field1"})
"", A dto();
" @ApiImplicitParams({@ApiImplicitParam(\"p2\"), @ApiImplicitParam(\"p1\")})",
" A firstEndpoint();", @ApiImplicitParams({@ApiImplicitParam("p2"), @ApiImplicitParam("p1")})
"", A firstEndpoint();
" @Parameters({@Parameter(name = \"p2\"), @Parameter(name = \"p1\")})",
" A secondEndpoint();", @Parameters({@Parameter(name = "p2"), @Parameter(name = "p1")})
"", A secondEndpoint();
" @XmlType(propOrder = {\"field2\", \"field1\"})",
" class XmlTypeDummy {}", @XmlType(propOrder = {"field2", "field1"})
"", class XmlTypeDummy {}
" @PropertySource({\"field2\", \"field1\"})",
" class PropertySourceDummy {}", @PropertySource({"field2", "field1"})
"", class PropertySourceDummy {}
" @TestPropertySource(locations = {\"field2\", \"field1\"})",
" class FirstTestPropertySourceDummy {}", @TestPropertySource(locations = {"field2", "field1"})
"", class FirstTestPropertySourceDummy {}
" @TestPropertySource({\"field2\", \"field1\"})",
" class SecondTestPropertySourceDummy {}", @TestPropertySource({"field2", "field1"})
"}") class SecondTestPropertySourceDummy {}
}
""")
.doTest(); .doTest();
} }
@@ -193,98 +195,102 @@ final class LexicographicalAnnotationAttributeListingTest {
LexicographicalAnnotationAttributeListing.class, getClass()) LexicographicalAnnotationAttributeListing.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static java.math.RoundingMode.DOWN;", """
"import static java.math.RoundingMode.UP;", import static java.math.RoundingMode.DOWN;
"", import static java.math.RoundingMode.UP;
"import java.math.RoundingMode;",
"", import java.math.RoundingMode;
"interface A {",
" @interface Foo {", interface A {
" String[] value() default {};", @interface Foo {
"", String[] value() default {};
" boolean[] bools() default {};",
"", boolean[] bools() default {};
" char[] chars() default {};",
"", char[] chars() default {};
" Class<?>[] cls() default {};",
"", Class<?>[] cls() default {};
" RoundingMode[] enums() default {};",
"", RoundingMode[] enums() default {};
" Bar[] anns() default {};",
" }", Bar[] anns() default {};
"", }
" @interface Bar {",
" String[] value() default {};", @interface Bar {
" }", String[] value() default {};
"", }
" @Foo({\" \", \"\", \"b\", \"a\"})",
" A unsortedStrings();", @Foo({" ", "", "b", "a"})
"", A unsortedStrings();
" @Foo(bools = {true, false})",
" A unsortedBooleans();", @Foo(bools = {true, false})
"", A unsortedBooleans();
" @Foo(chars = {'b', 'a'})",
" A unsortedChars();", @Foo(chars = {'b', 'a'})
"", A unsortedChars();
" @Foo(cls = {long.class, int.class})",
" A unsortedClasses();", @Foo(cls = {long.class, int.class})
"", A unsortedClasses();
" @Foo(enums = {UP, DOWN})",
" A unsortedEnums();", @Foo(enums = {UP, DOWN})
"", A unsortedEnums();
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})",
" A unsortedAnns();", @Foo(anns = {@Bar("b"), @Bar("a")})
"", A unsortedAnns();
" @Foo(anns = {@Bar(\"a\"), @Bar({\"b\", \"a\"})})",
" A unsortedInnderAnns();", @Foo(anns = {@Bar("a"), @Bar({"b", "a"})})
"}") A unsortedInnderAnns();
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static java.math.RoundingMode.DOWN;", """
"import static java.math.RoundingMode.UP;", import static java.math.RoundingMode.DOWN;
"", import static java.math.RoundingMode.UP;
"import java.math.RoundingMode;",
"", import java.math.RoundingMode;
"interface A {",
" @interface Foo {", interface A {
" String[] value() default {};", @interface Foo {
"", String[] value() default {};
" boolean[] bools() default {};",
"", boolean[] bools() default {};
" char[] chars() default {};",
"", char[] chars() default {};
" Class<?>[] cls() default {};",
"", Class<?>[] cls() default {};
" RoundingMode[] enums() default {};",
"", RoundingMode[] enums() default {};
" Bar[] anns() default {};",
" }", Bar[] anns() default {};
"", }
" @interface Bar {",
" String[] value() default {};", @interface Bar {
" }", String[] value() default {};
"", }
" @Foo({\"\", \" \", \"a\", \"b\"})",
" A unsortedStrings();", @Foo({"", " ", "a", "b"})
"", A unsortedStrings();
" @Foo(bools = {false, true})",
" A unsortedBooleans();", @Foo(bools = {false, true})
"", A unsortedBooleans();
" @Foo(chars = {'a', 'b'})",
" A unsortedChars();", @Foo(chars = {'a', 'b'})
"", A unsortedChars();
" @Foo(cls = {int.class, long.class})",
" A unsortedClasses();", @Foo(cls = {int.class, long.class})
"", A unsortedClasses();
" @Foo(enums = {DOWN, UP})",
" A unsortedEnums();", @Foo(enums = {DOWN, UP})
"", A unsortedEnums();
" @Foo(anns = {@Bar(\"a\"), @Bar(\"b\")})",
" A unsortedAnns();", @Foo(anns = {@Bar("a"), @Bar("b")})
"", A unsortedAnns();
" @Foo(anns = {@Bar(\"a\"), @Bar({\"a\", \"b\"})})",
" A unsortedInnderAnns();", @Foo(anns = {@Bar("a"), @Bar({"a", "b"})})
"}") A unsortedInnderAnns();
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -297,48 +303,50 @@ final class LexicographicalAnnotationAttributeListingTest {
"-XepOpt:LexicographicalAnnotationAttributeListing:Excludes=pkg.A.Bar#value") "-XepOpt:LexicographicalAnnotationAttributeListing:Excludes=pkg.A.Bar#value")
.addSourceLines( .addSourceLines(
"pkg/A.java", "pkg/A.java",
"package pkg;", """
"", package pkg;
"interface A {",
" @interface Foo {", interface A {
" String[] value() default {};", @interface Foo {
"", String[] value() default {};
" String[] value2() default {};",
" }", String[] value2() default {};
"", }
" @interface Bar {",
" String[] value() default {};", @interface Bar {
"", String[] value() default {};
" String[] value2() default {};",
" }", String[] value2() default {};
"", }
" @interface Baz {",
" String[] value() default {};", @interface Baz {
"", String[] value() default {};
" String[] value2() default {};",
" }", String[] value2() default {};
"", }
" // BUG: Diagnostic contains:",
" @Foo({\"b\", \"a\"})", // BUG: Diagnostic contains:
" A fooValue();", @Foo({"b", "a"})
"", A fooValue();
" // BUG: Diagnostic contains:",
" @Foo(value2 = {\"b\", \"a\"})", // BUG: Diagnostic contains:
" A fooValue2();", @Foo(value2 = {"b", "a"})
"", A fooValue2();
" @Bar({\"b\", \"a\"})",
" A barValue();", @Bar({"b", "a"})
"", A barValue();
" // BUG: Diagnostic contains:",
" @Bar(value2 = {\"b\", \"a\"})", // BUG: Diagnostic contains:
" A barValue2();", @Bar(value2 = {"b", "a"})
"", A barValue2();
" @Baz({\"b\", \"a\"})",
" A bazValue();", @Baz({"b", "a"})
"", A bazValue();
" @Baz(value2 = {\"b\", \"a\"})",
" A bazValue2();", @Baz(value2 = {"b", "a"})
"}") A bazValue2();
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -11,122 +11,124 @@ final class LexicographicalAnnotationListingTest {
CompilationTestHelper.newInstance(LexicographicalAnnotationListing.class, getClass()) CompilationTestHelper.newInstance(LexicographicalAnnotationListing.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.lang.annotation.ElementType;", """
"import java.lang.annotation.Repeatable;", import java.lang.annotation.ElementType;
"import java.lang.annotation.Target;", import java.lang.annotation.Repeatable;
"", import java.lang.annotation.Target;
"interface A {",
" @Repeatable(Foos.class)", interface A {
" @interface Foo {", @Repeatable(Foos.class)
" String[] value() default {};", @interface Foo {
"", String[] value() default {};
" int[] ints() default {};",
"", int[] ints() default {};
" Bar[] anns() default {};",
" }", Bar[] anns() default {};
"", }
" @Target(ElementType.METHOD)",
" @interface Bar {", @Target(ElementType.METHOD)
" String[] value() default {};", @interface Bar {
" }", String[] value() default {};
"", }
" @interface Baz {",
" String[] str() default {};", @interface Baz {
" }", String[] str() default {};
"", }
" @interface Foos {",
" Foo[] value();", @interface Foos {
" }", Foo[] value();
"", }
" @Target(ElementType.TYPE_USE)",
" @interface FooTypeUse {", @Target(ElementType.TYPE_USE)
" String[] value() default {};", @interface FooTypeUse {
" }", String[] value() default {};
"", }
" @Target(ElementType.TYPE_USE)",
" @interface BarTypeUse {", @Target(ElementType.TYPE_USE)
" String[] value() default {};", @interface BarTypeUse {
" }", String[] value() default {};
"", }
" // BUG: Diagnostic contains:",
" @Foo", // BUG: Diagnostic contains:
" @Bar", @Foo
" A unsortedSimpleCase();", @Bar
"", A unsortedSimpleCase();
" // BUG: Diagnostic contains:",
" @Foo()", // BUG: Diagnostic contains:
" @Bar()", @Foo()
" A unsortedWithParens();", @Bar()
"", A unsortedWithParens();
" @Foo()",
" A onlyOneAnnotation();", @Foo()
"", A onlyOneAnnotation();
" @Bar",
" @Foo()", @Bar
" A sortedAnnotationsOneWithParens();", @Foo()
"", A sortedAnnotationsOneWithParens();
" // BUG: Diagnostic contains:",
" @Foo", // BUG: Diagnostic contains:
" @Baz", @Foo
" @Bar", @Baz
" A threeUnsortedAnnotationsSameInitialLetter();", @Bar
"", A threeUnsortedAnnotationsSameInitialLetter();
" // BUG: Diagnostic contains:",
" @Bar", // BUG: Diagnostic contains:
" @Foo()", @Bar
" @Baz", @Foo()
" A firstOrderedWithTwoUnsortedAnnotations();", @Baz
"", A firstOrderedWithTwoUnsortedAnnotations();
" @Bar",
" @Baz", @Bar
" @Foo()", @Baz
" A threeSortedAnnotations();", @Foo()
"", A threeSortedAnnotations();
" // BUG: Diagnostic contains:",
" @Foo({\"b\"})", // BUG: Diagnostic contains:
" @Bar({\"a\"})", @Foo({"b"})
" A unsortedWithStringAttributes();", @Bar({"a"})
"", A unsortedWithStringAttributes();
" // BUG: Diagnostic contains:",
" @Baz(str = {\"a\", \"b\"})", // BUG: Diagnostic contains:
" @Foo(ints = {1, 0})", @Baz(str = {"a", "b"})
" @Bar", @Foo(ints = {1, 0})
" A unsortedWithAttributes();", @Bar
"", A unsortedWithAttributes();
" // BUG: Diagnostic contains:",
" @Bar", // BUG: Diagnostic contains:
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})", @Bar
" @Baz", @Foo(anns = {@Bar("b"), @Bar("a")})
" A unsortedWithNestedBar();", @Baz
"", A unsortedWithNestedBar();
" @Bar",
" @Baz", @Bar
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})", @Baz
" A sortedWithNestedBar();", @Foo(anns = {@Bar("b"), @Bar("a")})
"", A sortedWithNestedBar();
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})",
" @Foo(ints = {1, 2})", @Foo(anns = {@Bar("b"), @Bar("a")})
" @Foo({\"b\"})", @Foo(ints = {1, 2})
" A sortedRepeatableAnnotation();", @Foo({"b"})
"", A sortedRepeatableAnnotation();
" // BUG: Diagnostic contains:",
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})", // BUG: Diagnostic contains:
" @Bar", @Foo(anns = {@Bar("b"), @Bar("a")})
" @Foo(ints = {1, 2})", @Bar
" A unsortedRepeatableAnnotation();", @Foo(ints = {1, 2})
"", A unsortedRepeatableAnnotation();
" // BUG: Diagnostic contains:",
" default @FooTypeUse @BarTypeUse A unsortedTypeAnnotations() {", // BUG: Diagnostic contains:
" return null;", default @FooTypeUse @BarTypeUse A unsortedTypeAnnotations() {
" }", return null;
"", }
" // BUG: Diagnostic contains:",
" @Baz", // BUG: Diagnostic contains:
" @Bar", @Baz
" default @FooTypeUse @BarTypeUse A unsortedTypeUseAndOtherAnnotations() {", @Bar
" return null;", default @FooTypeUse @BarTypeUse A unsortedTypeUseAndOtherAnnotations() {
" }", return null;
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -135,166 +137,170 @@ final class LexicographicalAnnotationListingTest {
BugCheckerRefactoringTestHelper.newInstance(LexicographicalAnnotationListing.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(LexicographicalAnnotationListing.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import java.lang.annotation.ElementType;", """
"import java.lang.annotation.Repeatable;", import java.lang.annotation.ElementType;
"import java.lang.annotation.Target;", import java.lang.annotation.Repeatable;
"", import java.lang.annotation.Target;
"interface A {",
" @Repeatable(Foos.class)", interface A {
" @interface Foo {", @Repeatable(Foos.class)
" String[] value() default {};", @interface Foo {
"", String[] value() default {};
" int[] ints() default {};",
"", int[] ints() default {};
" Bar[] anns() default {};",
" }", Bar[] anns() default {};
"", }
" @Target(ElementType.METHOD)",
" @interface Bar {", @Target(ElementType.METHOD)
" String[] value() default {};", @interface Bar {
" }", String[] value() default {};
"", }
" @interface Baz {",
" String[] str() default {};", @interface Baz {
" }", String[] str() default {};
"", }
" @interface Foos {",
" Foo[] value();", @interface Foos {
" }", Foo[] value();
"", }
" @Target(ElementType.TYPE_USE)",
" @interface FooTypeUse {", @Target(ElementType.TYPE_USE)
" String[] value() default {};", @interface FooTypeUse {
" }", String[] value() default {};
"", }
" @Target(ElementType.TYPE_USE)",
" @interface BarTypeUse {", @Target(ElementType.TYPE_USE)
" String[] value() default {};", @interface BarTypeUse {
" }", String[] value() default {};
"", }
" @Bar",
" A singleAnnotation();", @Bar
"", A singleAnnotation();
" @Bar",
" @Foo", @Bar
" A sortedAnnotations();", @Foo
"", A sortedAnnotations();
" @Foo",
" @Bar", @Foo
" A unsortedAnnotations();", @Bar
"", A unsortedAnnotations();
" @Foo()",
" @Baz()", @Foo()
" @Bar", @Baz()
" A unsortedAnnotationsWithSomeParens();", @Bar
"", A unsortedAnnotationsWithSomeParens();
" @Bar",
" @Baz(str = {\"a\", \"b\"})", @Bar
" @Foo()", @Baz(str = {"a", "b"})
" A unsortedAnnotationsOneContainingAttributes();", @Foo()
"", A unsortedAnnotationsOneContainingAttributes();
" @Baz(str = {\"a\", \"b\"})",
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})", @Baz(str = {"a", "b"})
" @Bar({\"b\"})", @Foo(anns = {@Bar("b"), @Bar("a")})
" A unsortedAnnotationsWithAttributes();", @Bar({"b"})
"", A unsortedAnnotationsWithAttributes();
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})",
" @Foo(ints = {1, 2})", @Foo(anns = {@Bar("b"), @Bar("a")})
" @Foo({\"b\"})", @Foo(ints = {1, 2})
" A sortedRepeatableAnnotation();", @Foo({"b"})
"", A sortedRepeatableAnnotation();
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})",
" @Bar", @Foo(anns = {@Bar("b"), @Bar("a")})
" @Foo(ints = {1, 2})", @Bar
" A unsortedRepeatableAnnotation();", @Foo(ints = {1, 2})
"", A unsortedRepeatableAnnotation();
" @Baz",
" @Bar", @Baz
" default @FooTypeUse @BarTypeUse A unsortedWithTypeUseAnnotations() {", @Bar
" return null;", default @FooTypeUse @BarTypeUse A unsortedWithTypeUseAnnotations() {
" }", return null;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import java.lang.annotation.ElementType;", """
"import java.lang.annotation.Repeatable;", import java.lang.annotation.ElementType;
"import java.lang.annotation.Target;", import java.lang.annotation.Repeatable;
"", import java.lang.annotation.Target;
"interface A {",
" @Repeatable(Foos.class)", interface A {
" @interface Foo {", @Repeatable(Foos.class)
" String[] value() default {};", @interface Foo {
"", String[] value() default {};
" int[] ints() default {};",
"", int[] ints() default {};
" Bar[] anns() default {};",
" }", Bar[] anns() default {};
"", }
" @Target(ElementType.METHOD)",
" @interface Bar {", @Target(ElementType.METHOD)
" String[] value() default {};", @interface Bar {
" }", String[] value() default {};
"", }
" @interface Baz {",
" String[] str() default {};", @interface Baz {
" }", String[] str() default {};
"", }
" @interface Foos {",
" Foo[] value();", @interface Foos {
" }", Foo[] value();
"", }
" @Target(ElementType.TYPE_USE)",
" @interface FooTypeUse {", @Target(ElementType.TYPE_USE)
" String[] value() default {};", @interface FooTypeUse {
" }", String[] value() default {};
"", }
" @Target(ElementType.TYPE_USE)",
" @interface BarTypeUse {", @Target(ElementType.TYPE_USE)
" String[] value() default {};", @interface BarTypeUse {
" }", String[] value() default {};
"", }
" @Bar",
" A singleAnnotation();", @Bar
"", A singleAnnotation();
" @Bar",
" @Foo", @Bar
" A sortedAnnotations();", @Foo
"", A sortedAnnotations();
" @Bar",
" @Foo", @Bar
" A unsortedAnnotations();", @Foo
"", A unsortedAnnotations();
" @Bar",
" @Baz()", @Bar
" @Foo()", @Baz()
" A unsortedAnnotationsWithSomeParens();", @Foo()
"", A unsortedAnnotationsWithSomeParens();
" @Bar",
" @Baz(str = {\"a\", \"b\"})", @Bar
" @Foo()", @Baz(str = {"a", "b"})
" A unsortedAnnotationsOneContainingAttributes();", @Foo()
"", A unsortedAnnotationsOneContainingAttributes();
" @Bar({\"b\"})",
" @Baz(str = {\"a\", \"b\"})", @Bar({"b"})
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})", @Baz(str = {"a", "b"})
" A unsortedAnnotationsWithAttributes();", @Foo(anns = {@Bar("b"), @Bar("a")})
"", A unsortedAnnotationsWithAttributes();
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})",
" @Foo(ints = {1, 2})", @Foo(anns = {@Bar("b"), @Bar("a")})
" @Foo({\"b\"})", @Foo(ints = {1, 2})
" A sortedRepeatableAnnotation();", @Foo({"b"})
"", A sortedRepeatableAnnotation();
" @Bar",
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")})", @Bar
" @Foo(ints = {1, 2})", @Foo(anns = {@Bar("b"), @Bar("a")})
" A unsortedRepeatableAnnotation();", @Foo(ints = {1, 2})
"", A unsortedRepeatableAnnotation();
" @Bar",
" @Baz", @Bar
" default @BarTypeUse @FooTypeUse A unsortedWithTypeUseAnnotations() {", @Baz
" return null;", default @BarTypeUse @FooTypeUse A unsortedWithTypeUseAnnotations() {
" }", return null;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,86 +11,88 @@ final class MockitoMockClassReferenceTest {
CompilationTestHelper.newInstance(MockitoMockClassReference.class, getClass()) CompilationTestHelper.newInstance(MockitoMockClassReference.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static org.mockito.Mockito.mock;", """
"import static org.mockito.Mockito.spy;", import static org.mockito.Mockito.mock;
"import static org.mockito.Mockito.withSettings;", import static org.mockito.Mockito.spy;
"", import static org.mockito.Mockito.withSettings;
"import java.util.List;",
"import java.util.Objects;", import java.util.List;
"import org.mockito.invocation.InvocationOnMock;", import java.util.Objects;
"", import org.mockito.invocation.InvocationOnMock;
"class A {",
" {", class A {
" Double d = Objects.requireNonNullElseGet(null, () -> mock(Double.class));", {
" Double d2 =", Double d = Objects.requireNonNullElseGet(null, () -> mock(Double.class));
" Objects.requireNonNullElseGet(", Double d2 =
" null,", Objects.requireNonNullElseGet(
" () -> {", null,
" return mock(Double.class);", () -> {
" });", return mock(Double.class);
" }", });
"", }
" void m() {",
" Number variableMock = 42;", void m() {
" // BUG: Diagnostic contains:", Number variableMock = 42;
" variableMock = mock(Number.class);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", variableMock = mock(Number.class);
" variableMock = mock(Number.class, \"name\");", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", variableMock = mock(Number.class, "name");
" variableMock = mock(Number.class, InvocationOnMock::callRealMethod);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", variableMock = mock(Number.class, InvocationOnMock::callRealMethod);
" variableMock = mock(Number.class, withSettings());", // BUG: Diagnostic contains:
" variableMock = mock(Integer.class);", variableMock = mock(Number.class, withSettings());
" variableMock = 42;", variableMock = mock(Integer.class);
" // BUG: Diagnostic contains:", variableMock = 42;
" List rawMock = mock(List.class);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", List rawMock = mock(List.class);
" List<String> genericMock = mock(List.class);", // BUG: Diagnostic contains:
" var varMock = mock(Integer.class);", List<String> genericMock = mock(List.class);
" Class<? extends Number> numberType = Integer.class;", var varMock = mock(Integer.class);
" Number variableTypeMock = mock(numberType);", Class<? extends Number> numberType = Integer.class;
" Object subtypeMock = mock(Integer.class);", Number variableTypeMock = mock(numberType);
"", Object subtypeMock = mock(Integer.class);
" Number variableSpy = 42;",
" // BUG: Diagnostic contains:", Number variableSpy = 42;
" variableSpy = spy(Number.class);", // BUG: Diagnostic contains:
" variableSpy = spy(Integer.class);", variableSpy = spy(Number.class);
" variableSpy = 42;", variableSpy = spy(Integer.class);
" // BUG: Diagnostic contains:", variableSpy = 42;
" List rawSpy = spy(List.class);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", List rawSpy = spy(List.class);
" List<String> genericSpy = spy(List.class);", // BUG: Diagnostic contains:
" var varSpy = spy(Integer.class);", List<String> genericSpy = spy(List.class);
" Number variableTypeSpy = spy(numberType);", var varSpy = spy(Integer.class);
" Object subtypeSpy = spy(Integer.class);", Number variableTypeSpy = spy(numberType);
" Object objectSpy = spy(new Object());", Object subtypeSpy = spy(Integer.class);
"", Object objectSpy = spy(new Object());
" Objects.hash(mock(Integer.class));",
" Integer i = mock(mock(Integer.class));", Objects.hash(mock(Integer.class));
" String s = new String(mock(String.class));", Integer i = mock(mock(Integer.class));
" }", String s = new String(mock(String.class));
"", }
" Double getDoubleMock() {",
" return Objects.requireNonNullElseGet(", Double getDoubleMock() {
" null,", return Objects.requireNonNullElseGet(
" () -> {", null,
" return mock(Double.class);", () -> {
" });", return mock(Double.class);
" }", });
"", }
" Integer getIntegerMock() {",
" // BUG: Diagnostic contains:", Integer getIntegerMock() {
" return mock(Integer.class);", // BUG: Diagnostic contains:
" }", return mock(Integer.class);
"", }
" <T> T getGenericMock(Class<T> clazz) {",
" return mock(clazz);", <T> T getGenericMock(Class<T> clazz) {
" }", return mock(clazz);
"", }
" Number getSubTypeMock() {",
" return mock(Integer.class);", Number getSubTypeMock() {
" }", return mock(Integer.class);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -99,38 +101,42 @@ final class MockitoMockClassReferenceTest {
BugCheckerRefactoringTestHelper.newInstance(MockitoMockClassReference.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(MockitoMockClassReference.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static org.mockito.Mockito.mock;", """
"import static org.mockito.Mockito.spy;", import static org.mockito.Mockito.mock;
"import static org.mockito.Mockito.withSettings;", import static org.mockito.Mockito.spy;
"", import static org.mockito.Mockito.withSettings;
"import org.mockito.invocation.InvocationOnMock;",
"", import org.mockito.invocation.InvocationOnMock;
"class A {",
" void m() {", class A {
" Number simpleMock = mock(Number.class);", void m() {
" Number namedMock = mock(Number.class, \"name\");", Number simpleMock = mock(Number.class);
" Number customAnswerMock = mock(Number.class, InvocationOnMock::callRealMethod);", Number namedMock = mock(Number.class, "name");
" Number customSettingsMock = mock(Number.class, withSettings());", Number customAnswerMock = mock(Number.class, InvocationOnMock::callRealMethod);
" Number simpleSpy = spy(Number.class);", Number customSettingsMock = mock(Number.class, withSettings());
" }", Number simpleSpy = spy(Number.class);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static org.mockito.Mockito.mock;", """
"import static org.mockito.Mockito.spy;", import static org.mockito.Mockito.mock;
"import static org.mockito.Mockito.withSettings;", import static org.mockito.Mockito.spy;
"", import static org.mockito.Mockito.withSettings;
"import org.mockito.invocation.InvocationOnMock;",
"", import org.mockito.invocation.InvocationOnMock;
"class A {",
" void m() {", class A {
" Number simpleMock = mock();", void m() {
" Number namedMock = mock(\"name\");", Number simpleMock = mock();
" Number customAnswerMock = mock(InvocationOnMock::callRealMethod);", Number namedMock = mock("name");
" Number customSettingsMock = mock(withSettings());", Number customAnswerMock = mock(InvocationOnMock::callRealMethod);
" Number simpleSpy = spy();", Number customSettingsMock = mock(withSettings());
" }", Number simpleSpy = spy();
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,40 +11,42 @@ final class MockitoStubbingTest {
CompilationTestHelper.newInstance(MockitoStubbing.class, getClass()) CompilationTestHelper.newInstance(MockitoStubbing.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static org.mockito.ArgumentMatchers.eq;", """
"import static org.mockito.ArgumentMatchers.notNull;", import static org.mockito.ArgumentMatchers.eq;
"import static org.mockito.Mockito.doAnswer;", import static org.mockito.ArgumentMatchers.notNull;
"import static org.mockito.Mockito.mock;", import static org.mockito.Mockito.doAnswer;
"", import static org.mockito.Mockito.mock;
"import java.util.function.BiConsumer;",
"import java.util.function.Consumer;", import java.util.function.BiConsumer;
"import org.mockito.ArgumentMatchers;", import java.util.function.Consumer;
"", import org.mockito.ArgumentMatchers;
"class A {",
" void m() {", class A {
" Runnable runnable = mock(Runnable.class);", void m() {
" doAnswer(inv -> null).when(runnable).run();", Runnable runnable = mock(Runnable.class);
"", doAnswer(inv -> null).when(runnable).run();
" Consumer<String> consumer = mock(Consumer.class);",
" doAnswer(inv -> null).when(consumer).accept(\"foo\");", Consumer<String> consumer = mock(Consumer.class);
" doAnswer(inv -> null).when(consumer).accept(notNull());", doAnswer(inv -> null).when(consumer).accept("foo");
" // BUG: Diagnostic contains:", doAnswer(inv -> null).when(consumer).accept(notNull());
" doAnswer(inv -> null).when(consumer).accept(ArgumentMatchers.eq(\"foo\"));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", doAnswer(inv -> null).when(consumer).accept(ArgumentMatchers.eq("foo"));
" doAnswer(inv -> null).when(consumer).accept(eq(toString()));", // BUG: Diagnostic contains:
"", doAnswer(inv -> null).when(consumer).accept(eq(toString()));
" BiConsumer<Integer, String> biConsumer = mock(BiConsumer.class);",
" doAnswer(inv -> null).when(biConsumer).accept(0, \"foo\");", BiConsumer<Integer, String> biConsumer = mock(BiConsumer.class);
" doAnswer(inv -> null).when(biConsumer).accept(eq(0), notNull());", doAnswer(inv -> null).when(biConsumer).accept(0, "foo");
" doAnswer(inv -> null).when(biConsumer).accept(notNull(), eq(\"foo\"));", doAnswer(inv -> null).when(biConsumer).accept(eq(0), notNull());
" doAnswer(inv -> null)", doAnswer(inv -> null).when(biConsumer).accept(notNull(), eq("foo"));
" .when(biConsumer)", doAnswer(inv -> null)
" // BUG: Diagnostic contains:", .when(biConsumer)
" .accept(ArgumentMatchers.eq(0), ArgumentMatchers.eq(\"foo\"));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", .accept(ArgumentMatchers.eq(0), ArgumentMatchers.eq("foo"));
" doAnswer(inv -> null).when(biConsumer).accept(eq(hashCode()), eq(toString()));", // BUG: Diagnostic contains:
" }", doAnswer(inv -> null).when(biConsumer).accept(eq(hashCode()), eq(toString()));
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -53,48 +55,52 @@ final class MockitoStubbingTest {
BugCheckerRefactoringTestHelper.newInstance(MockitoStubbing.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(MockitoStubbing.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static org.mockito.ArgumentMatchers.eq;", """
"import static org.mockito.Mockito.doAnswer;", import static org.mockito.ArgumentMatchers.eq;
"import static org.mockito.Mockito.mock;", import static org.mockito.Mockito.doAnswer;
"", import static org.mockito.Mockito.mock;
"import java.util.function.BiConsumer;",
"import java.util.function.Consumer;", import java.util.function.BiConsumer;
"import org.mockito.ArgumentMatchers;", import java.util.function.Consumer;
"", import org.mockito.ArgumentMatchers;
"class A {",
" void m() {", class A {
" Consumer<String> consumer = mock(Consumer.class);", void m() {
" doAnswer(inv -> null).when(consumer).accept(ArgumentMatchers.eq(\"foo\"));", Consumer<String> consumer = mock(Consumer.class);
" doAnswer(inv -> null).when(consumer).accept(eq(toString()));", doAnswer(inv -> null).when(consumer).accept(ArgumentMatchers.eq("foo"));
"", doAnswer(inv -> null).when(consumer).accept(eq(toString()));
" BiConsumer<Integer, String> biConsumer = mock(BiConsumer.class);",
" doAnswer(inv -> null)", BiConsumer<Integer, String> biConsumer = mock(BiConsumer.class);
" .when(biConsumer)", doAnswer(inv -> null)
" .accept(ArgumentMatchers.eq(0), ArgumentMatchers.eq(\"foo\"));", .when(biConsumer)
" doAnswer(inv -> null).when(biConsumer).accept(eq(hashCode()), eq(toString()));", .accept(ArgumentMatchers.eq(0), ArgumentMatchers.eq("foo"));
" }", doAnswer(inv -> null).when(biConsumer).accept(eq(hashCode()), eq(toString()));
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static org.mockito.ArgumentMatchers.eq;", """
"import static org.mockito.Mockito.doAnswer;", import static org.mockito.ArgumentMatchers.eq;
"import static org.mockito.Mockito.mock;", import static org.mockito.Mockito.doAnswer;
"", import static org.mockito.Mockito.mock;
"import java.util.function.BiConsumer;",
"import java.util.function.Consumer;", import java.util.function.BiConsumer;
"import org.mockito.ArgumentMatchers;", import java.util.function.Consumer;
"", import org.mockito.ArgumentMatchers;
"class A {",
" void m() {", class A {
" Consumer<String> consumer = mock(Consumer.class);", void m() {
" doAnswer(inv -> null).when(consumer).accept(\"foo\");", Consumer<String> consumer = mock(Consumer.class);
" doAnswer(inv -> null).when(consumer).accept(toString());", doAnswer(inv -> null).when(consumer).accept("foo");
"", doAnswer(inv -> null).when(consumer).accept(toString());
" BiConsumer<Integer, String> biConsumer = mock(BiConsumer.class);",
" doAnswer(inv -> null).when(biConsumer).accept(0, \"foo\");", BiConsumer<Integer, String> biConsumer = mock(BiConsumer.class);
" doAnswer(inv -> null).when(biConsumer).accept(hashCode(), toString());", doAnswer(inv -> null).when(biConsumer).accept(0, "foo");
" }", doAnswer(inv -> null).when(biConsumer).accept(hashCode(), toString());
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -9,18 +9,20 @@ final class MongoDBTextFilterUsageTest {
CompilationTestHelper.newInstance(MongoDBTextFilterUsage.class, getClass()) CompilationTestHelper.newInstance(MongoDBTextFilterUsage.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.mongodb.client.model.Filters;", """
"import com.mongodb.client.model.TextSearchOptions;", import com.mongodb.client.model.Filters;
"", import com.mongodb.client.model.TextSearchOptions;
"class A {",
" void m() {", class A {
" Filters.eq(\"foo\", \"bar\");", void m() {
" // BUG: Diagnostic contains:", Filters.eq("foo", "bar");
" Filters.text(\"foo\");", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Filters.text("foo");
" Filters.text(\"foo\", new TextSearchOptions());", // BUG: Diagnostic contains:
" }", Filters.text("foo", new TextSearchOptions());
"}") }
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -9,31 +9,33 @@ final class NestedOptionalsTest {
CompilationTestHelper.newInstance(NestedOptionals.class, getClass()) CompilationTestHelper.newInstance(NestedOptionals.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.Optional;", """
"import java.util.stream.Stream;", import java.util.Optional;
"", import java.util.stream.Stream;
"class A {",
" void m() {", class A {
" Optional.empty();", void m() {
" Optional.of(1);", Optional.empty();
" // BUG: Diagnostic contains:", Optional.of(1);
" Optional.of(Optional.empty());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Optional.of(Optional.empty());
" Optional.of(Optional.of(1));", // BUG: Diagnostic contains:
"", Optional.of(Optional.of(1));
" Optional.ofNullable(null);",
" // BUG: Diagnostic contains:", Optional.ofNullable(null);
" Optional.ofNullable((Optional) null);", // BUG: Diagnostic contains:
"", Optional.ofNullable((Optional) null);
" Optional.of(\"foo\").map(String::length);",
" // BUG: Diagnostic contains:", Optional.of("foo").map(String::length);
" Optional.of(\"foo\").map(Optional::of);", // BUG: Diagnostic contains:
"", Optional.of("foo").map(Optional::of);
" Stream.of(\"foo\").findFirst();",
" // BUG: Diagnostic contains:", Stream.of("foo").findFirst();
" Stream.of(\"foo\").map(Optional::of).findFirst();", // BUG: Diagnostic contains:
" }", Stream.of("foo").map(Optional::of).findFirst();
"}") }
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -9,29 +9,31 @@ final class NestedPublishersTest {
CompilationTestHelper.newInstance(NestedPublishers.class, getClass()) CompilationTestHelper.newInstance(NestedPublishers.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import org.reactivestreams.Publisher;", """
"import reactor.core.publisher.Flux;", import org.reactivestreams.Publisher;
"import reactor.core.publisher.GroupedFlux;", import reactor.core.publisher.Flux;
"import reactor.core.publisher.Mono;", import reactor.core.publisher.GroupedFlux;
"", import reactor.core.publisher.Mono;
"class A {",
" void m() {", class A {
" Mono.empty();", void m() {
" Flux.just(1);", Mono.empty();
" Flux.just(1, 2).groupBy(i -> i).map(groupedFlux -> (GroupedFlux) groupedFlux);", Flux.just(1);
"", Flux.just(1, 2).groupBy(i -> i).map(groupedFlux -> (GroupedFlux) groupedFlux);
" // BUG: Diagnostic contains:",
" Mono.just(Mono.empty());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Mono.just(Mono.empty());
" Flux.just(Flux.empty());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(Flux.empty());
" Mono.just((Flux) Flux.just(1));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Mono.just((Flux) Flux.just(1));
" Flux.just((Publisher) Mono.just(1));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just((Publisher) Mono.just(1));
" Mono.just(1).map(Mono::just);", // BUG: Diagnostic contains:
" }", Mono.just(1).map(Mono::just);
"}") }
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -11,95 +11,97 @@ final class NonEmptyMonoTest {
CompilationTestHelper.newInstance(NonEmptyMono.class, getClass()) CompilationTestHelper.newInstance(NonEmptyMono.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;", """
"import static java.util.function.Function.identity;", import static com.google.common.collect.ImmutableList.toImmutableList;
"", import static java.util.function.Function.identity;
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableMap;", import com.google.common.collect.ImmutableList;
"import java.util.ArrayList;", import com.google.common.collect.ImmutableMap;
"import java.util.HashMap;", import java.util.ArrayList;
"import java.util.List;", import java.util.HashMap;
"import reactor.core.publisher.Flux;", import java.util.List;
"import reactor.core.publisher.Mono;", import reactor.core.publisher.Flux;
"", import reactor.core.publisher.Mono;
"class A {",
" void m() {", class A {
" Mono.just(1).defaultIfEmpty(2);", void m() {
" Mono.just(1).single();", Mono.just(1).defaultIfEmpty(2);
" Mono.just(1).switchIfEmpty(Mono.just(2));", Mono.just(1).single();
"", Mono.just(1).switchIfEmpty(Mono.just(2));
" // BUG: Diagnostic contains:",
" Flux.just(1).all(x -> true).defaultIfEmpty(true);", // BUG: Diagnostic contains:
"", Flux.just(1).all(x -> true).defaultIfEmpty(true);
" // BUG: Diagnostic contains:",
" Flux.just(1).any(x -> true).single();", // BUG: Diagnostic contains:
"", Flux.just(1).any(x -> true).single();
" // BUG: Diagnostic contains:",
" Flux.just(1).collect(toImmutableList()).switchIfEmpty(Mono.just(ImmutableList.of()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).collect(toImmutableList()).switchIfEmpty(Mono.just(ImmutableList.of()));
" Flux.just(1).collect(ArrayList::new, List::add).defaultIfEmpty(new ArrayList<>());", // BUG: Diagnostic contains:
"", Flux.just(1).collect(ArrayList::new, List::add).defaultIfEmpty(new ArrayList<>());
" // BUG: Diagnostic contains:",
" Flux.just(1).collectList().single();", // BUG: Diagnostic contains:
"", Flux.just(1).collectList().single();
" // BUG: Diagnostic contains:",
" Flux.just(1).collectMap(identity()).switchIfEmpty(Mono.just(ImmutableMap.of()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).collectMap(identity()).switchIfEmpty(Mono.just(ImmutableMap.of()));
" Flux.just(1).collectMap(identity(), identity()).defaultIfEmpty(ImmutableMap.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).collectMap(identity(), identity()).defaultIfEmpty(ImmutableMap.of());
" Flux.just(1).collectMap(identity(), identity(), HashMap::new).single();", // BUG: Diagnostic contains:
"", Flux.just(1).collectMap(identity(), identity(), HashMap::new).single();
" // BUG: Diagnostic contains:",
" Flux.just(1).collectMultimap(identity()).switchIfEmpty(Mono.just(ImmutableMap.of()));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).collectMultimap(identity()).switchIfEmpty(Mono.just(ImmutableMap.of()));
" Flux.just(1).collectMultimap(identity(), identity()).defaultIfEmpty(ImmutableMap.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).collectMultimap(identity(), identity()).defaultIfEmpty(ImmutableMap.of());
" Flux.just(1).collectMultimap(identity(), identity(), HashMap::new).single();", // BUG: Diagnostic contains:
"", Flux.just(1).collectMultimap(identity(), identity(), HashMap::new).single();
" // BUG: Diagnostic contains:",
" Flux.just(1).collectSortedList().defaultIfEmpty(ImmutableList.of());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).collectSortedList().defaultIfEmpty(ImmutableList.of());
" Flux.just(1).collectSortedList((o1, o2) -> 0).single();", // BUG: Diagnostic contains:
"", Flux.just(1).collectSortedList((o1, o2) -> 0).single();
" // BUG: Diagnostic contains:",
" Flux.just(1).count().switchIfEmpty(Mono.just(2L));", // BUG: Diagnostic contains:
"", Flux.just(1).count().switchIfEmpty(Mono.just(2L));
" // BUG: Diagnostic contains:",
" Flux.just(1).elementAt(0).defaultIfEmpty(1);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).elementAt(0).defaultIfEmpty(1);
" Flux.just(1).elementAt(0, 2).single();", // BUG: Diagnostic contains:
"", Flux.just(1).elementAt(0, 2).single();
" // BUG: Diagnostic contains:",
" Flux.just(1).hasElement(2).switchIfEmpty(Mono.just(true));", // BUG: Diagnostic contains:
"", Flux.just(1).hasElement(2).switchIfEmpty(Mono.just(true));
" // BUG: Diagnostic contains:",
" Flux.just(1).hasElements().defaultIfEmpty(true);", // BUG: Diagnostic contains:
"", Flux.just(1).hasElements().defaultIfEmpty(true);
" // BUG: Diagnostic contains:",
" Flux.just(1).last().single();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).last().single();
" Flux.just(1).last(2).switchIfEmpty(Mono.just(3));", // BUG: Diagnostic contains:
"", Flux.just(1).last(2).switchIfEmpty(Mono.just(3));
" // BUG: Diagnostic contains:",
" Flux.just(1).reduceWith(() -> 0, Integer::sum).defaultIfEmpty(2);", // BUG: Diagnostic contains:
"", Flux.just(1).reduceWith(() -> 0, Integer::sum).defaultIfEmpty(2);
" // BUG: Diagnostic contains:",
" Flux.just(1).single().single();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Flux.just(1).single().single();
" Flux.just(1).single(2).switchIfEmpty(Mono.just(3));", // BUG: Diagnostic contains:
"", Flux.just(1).single(2).switchIfEmpty(Mono.just(3));
" Flux.just(1).reduce(Integer::sum).defaultIfEmpty(2);",
" // BUG: Diagnostic contains:", Flux.just(1).reduce(Integer::sum).defaultIfEmpty(2);
" Flux.just(1).reduce(2, Integer::sum).single();", // BUG: Diagnostic contains:
"", Flux.just(1).reduce(2, Integer::sum).single();
" // BUG: Diagnostic contains:",
" Mono.just(1).defaultIfEmpty(1).switchIfEmpty(Mono.just(2));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Mono.just(1).defaultIfEmpty(1).switchIfEmpty(Mono.just(2));
" Mono.just(1).hasElement().defaultIfEmpty(true);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Mono.just(1).hasElement().defaultIfEmpty(true);
" Mono.just(1).single().single();", // BUG: Diagnostic contains:
" }", Mono.just(1).single().single();
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -108,42 +110,46 @@ final class NonEmptyMonoTest {
BugCheckerRefactoringTestHelper.newInstance(NonEmptyMono.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(NonEmptyMono.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;", """
"", import static com.google.common.collect.ImmutableList.toImmutableList;
"import com.google.common.collect.ImmutableList;",
"import reactor.core.publisher.Flux;", import com.google.common.collect.ImmutableList;
"import reactor.core.publisher.Mono;", import reactor.core.publisher.Flux;
"", import reactor.core.publisher.Mono;
"class A {",
" void m() {", class A {
" Flux.just(1).collect(toImmutableList()).single();", void m() {
" Flux.just(1).collect(toImmutableList()).defaultIfEmpty(ImmutableList.of());", Flux.just(1).collect(toImmutableList()).single();
" Flux.just(1).collect(toImmutableList()).switchIfEmpty(Mono.just(ImmutableList.of()));", Flux.just(1).collect(toImmutableList()).defaultIfEmpty(ImmutableList.of());
"", Flux.just(1).collect(toImmutableList()).switchIfEmpty(Mono.just(ImmutableList.of()));
" Mono.just(2).hasElement().single();",
" Mono.just(2).hasElement().defaultIfEmpty(true);", Mono.just(2).hasElement().single();
" Mono.just(2).hasElement().switchIfEmpty(Mono.just(true));", Mono.just(2).hasElement().defaultIfEmpty(true);
" }", Mono.just(2).hasElement().switchIfEmpty(Mono.just(true));
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;", """
"", import static com.google.common.collect.ImmutableList.toImmutableList;
"import com.google.common.collect.ImmutableList;",
"import reactor.core.publisher.Flux;", import com.google.common.collect.ImmutableList;
"import reactor.core.publisher.Mono;", import reactor.core.publisher.Flux;
"", import reactor.core.publisher.Mono;
"class A {",
" void m() {", class A {
" Flux.just(1).collect(toImmutableList());", void m() {
" Flux.just(1).collect(toImmutableList());", Flux.just(1).collect(toImmutableList());
" Flux.just(1).collect(toImmutableList());", Flux.just(1).collect(toImmutableList());
"", Flux.just(1).collect(toImmutableList());
" Mono.just(2).hasElement();",
" Mono.just(2).hasElement();", Mono.just(2).hasElement();
" Mono.just(2).hasElement();", Mono.just(2).hasElement();
" }", Mono.just(2).hasElement();
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -40,74 +40,76 @@ final class NonStaticImportTest {
CompilationTestHelper.newInstance(NonStaticImport.class, getClass()) CompilationTestHelper.newInstance(NonStaticImport.class, getClass())
.addSourceLines( .addSourceLines(
"pkg/A.java", "pkg/A.java",
"package pkg;", """
"", package pkg;
"// BUG: Diagnostic contains:",
"import static com.google.common.base.Strings.nullToEmpty;", // BUG: Diagnostic contains:
"// BUG: Diagnostic contains:", import static com.google.common.base.Strings.nullToEmpty;
"import static com.google.common.collect.ImmutableList.copyOf;", // BUG: Diagnostic contains:
"// BUG: Diagnostic contains:", import static com.google.common.collect.ImmutableList.copyOf;
"import static java.lang.Integer.MAX_VALUE;", // BUG: Diagnostic contains:
"// BUG: Diagnostic contains:", import static java.lang.Integer.MAX_VALUE;
"import static java.lang.Integer.MIN_VALUE;", // BUG: Diagnostic contains:
"// BUG: Diagnostic contains:", import static java.lang.Integer.MIN_VALUE;
"import static java.time.Clock.systemUTC;", // BUG: Diagnostic contains:
"// BUG: Diagnostic contains:", import static java.time.Clock.systemUTC;
"import static java.time.Instant.MIN;", // BUG: Diagnostic contains:
"// BUG: Diagnostic contains:", import static java.time.Instant.MIN;
"import static java.time.ZoneOffset.SHORT_IDS;", // BUG: Diagnostic contains:
"import static java.time.ZoneOffset.UTC;", import static java.time.ZoneOffset.SHORT_IDS;
"// BUG: Diagnostic contains:", import static java.time.ZoneOffset.UTC;
"import static java.util.Collections.min;", // BUG: Diagnostic contains:
"import static java.util.Locale.ENGLISH;", import static java.util.Collections.min;
"// BUG: Diagnostic contains:", import static java.util.Locale.ENGLISH;
"import static java.util.Locale.ROOT;", // BUG: Diagnostic contains:
"// BUG: Diagnostic contains:", import static java.util.Locale.ROOT;
"import static java.util.Optional.empty;", // BUG: Diagnostic contains:
"import static pkg.A.WithMethodThatIsSelectivelyFlagged.list;", import static java.util.Optional.empty;
"// BUG: Diagnostic contains:", import static pkg.A.WithMethodThatIsSelectivelyFlagged.list;
"import static reactor.core.publisher.Flux.just;", // BUG: Diagnostic contains:
"", import static reactor.core.publisher.Flux.just;
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import java.time.Instant;", import com.google.common.collect.ImmutableSet;
"import java.time.ZoneOffset;", import java.time.Instant;
"import java.util.Locale;", import java.time.ZoneOffset;
"import java.util.Map;", import java.util.Locale;
"import pkg.A.Wrapper.INSTANCE;", import java.util.Map;
"", import pkg.A.Wrapper.INSTANCE;
"class A {",
" private Integer MIN_VALUE = 12;", class A {
"", private Integer MIN_VALUE = 12;
" void m() {",
" nullToEmpty(null);", void m() {
" copyOf(ImmutableList.of());", nullToEmpty(null);
" int max = MAX_VALUE;", copyOf(ImmutableList.of());
" int min = MIN_VALUE;", int max = MAX_VALUE;
" systemUTC();", int min = MIN_VALUE;
" Instant minInstant = MIN;", systemUTC();
" Map<String, String> shortIds = SHORT_IDS;", Instant minInstant = MIN;
" ZoneOffset utc = UTC;", Map<String, String> shortIds = SHORT_IDS;
" min(ImmutableSet.of());", ZoneOffset utc = UTC;
" Locale english = ENGLISH;", min(ImmutableSet.of());
" Locale root = ROOT;", Locale english = ENGLISH;
" empty();", Locale root = ROOT;
" just();", empty();
"", just();
" list();",
" new INSTANCE();", list();
" }", new INSTANCE();
"", }
" static final class WithMethodThatIsSelectivelyFlagged {",
" static ImmutableList<String> list() {", static final class WithMethodThatIsSelectivelyFlagged {
" return ImmutableList.of();", static ImmutableList<String> list() {
" }", return ImmutableList.of();
" }", }
"", }
" static final class Wrapper {",
" static final class INSTANCE {}", static final class Wrapper {
" }", static final class INSTANCE {}
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -116,84 +118,88 @@ final class NonStaticImportTest {
BugCheckerRefactoringTestHelper.newInstance(NonStaticImport.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(NonStaticImport.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static com.google.common.collect.ImmutableList.copyOf;", """
"import static com.google.common.collect.ImmutableSet.of;", import static com.google.common.collect.ImmutableList.copyOf;
"import static java.time.Clock.systemUTC;", import static com.google.common.collect.ImmutableSet.of;
"import static java.time.Instant.MAX;", import static java.time.Clock.systemUTC;
"import static java.time.Instant.MIN;", import static java.time.Instant.MAX;
"import static java.util.Collections.min;", import static java.time.Instant.MIN;
"import static java.util.Locale.ROOT;", import static java.util.Collections.min;
"import static java.util.Optional.empty;", import static java.util.Locale.ROOT;
"", import static java.util.Optional.empty;
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import java.time.Clock;", import com.google.common.collect.ImmutableSet;
"import java.time.Instant;", import java.time.Clock;
"import java.util.Locale;", import java.time.Instant;
"import java.util.Optional;", import java.util.Locale;
"", import java.util.Optional;
"class A {",
" void m() {", class A {
" systemUTC();", void m() {
" Clock.systemUTC();", systemUTC();
"", Clock.systemUTC();
" Optional<Integer> o1 = empty();",
" Optional<Integer> o2 = Optional.empty();", Optional<Integer> o1 = empty();
"", Optional<Integer> o2 = Optional.empty();
" Object l1 = copyOf(ImmutableList.of());",
" Object l2 = ImmutableList.copyOf(ImmutableList.of());", Object l1 = copyOf(ImmutableList.of());
"", Object l2 = ImmutableList.copyOf(ImmutableList.of());
" Locale lo1 = ROOT;",
" Locale lo2 = Locale.ROOT;", Locale lo1 = ROOT;
"", Locale lo2 = Locale.ROOT;
" Instant i1 = MIN;",
" Instant i2 = MAX;", Instant i1 = MIN;
"", Instant i2 = MAX;
" ImmutableSet.of(min(of()));",
" }", ImmutableSet.of(min(of()));
"", }
" private static final class WithCustomConstant {",
" private static final Instant MIN = Instant.EPOCH;", private static final class WithCustomConstant {
" private static final Instant OTHER = MIN;", private static final Instant MIN = Instant.EPOCH;
" private static final Instant OTHER_MAX = MAX;", private static final Instant OTHER = MIN;
" }", private static final Instant OTHER_MAX = MAX;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import java.time.Clock;", import com.google.common.collect.ImmutableSet;
"import java.time.Instant;", import java.time.Clock;
"import java.util.Collections;", import java.time.Instant;
"import java.util.Locale;", import java.util.Collections;
"import java.util.Optional;", import java.util.Locale;
"", import java.util.Optional;
"class A {",
" void m() {", class A {
" Clock.systemUTC();", void m() {
" Clock.systemUTC();", Clock.systemUTC();
"", Clock.systemUTC();
" Optional<Integer> o1 = Optional.empty();",
" Optional<Integer> o2 = Optional.empty();", Optional<Integer> o1 = Optional.empty();
"", Optional<Integer> o2 = Optional.empty();
" Object l1 = ImmutableList.copyOf(ImmutableList.of());",
" Object l2 = ImmutableList.copyOf(ImmutableList.of());", Object l1 = ImmutableList.copyOf(ImmutableList.of());
"", Object l2 = ImmutableList.copyOf(ImmutableList.of());
" Locale lo1 = Locale.ROOT;",
" Locale lo2 = Locale.ROOT;", Locale lo1 = Locale.ROOT;
"", Locale lo2 = Locale.ROOT;
" Instant i1 = Instant.MIN;",
" Instant i2 = Instant.MAX;", Instant i1 = Instant.MIN;
"", Instant i2 = Instant.MAX;
" ImmutableSet.of(Collections.min(ImmutableSet.of()));",
" }", ImmutableSet.of(Collections.min(ImmutableSet.of()));
"", }
" private static final class WithCustomConstant {",
" private static final Instant MIN = Instant.EPOCH;", private static final class WithCustomConstant {
" private static final Instant OTHER = MIN;", private static final Instant MIN = Instant.EPOCH;
" private static final Instant OTHER_MAX = Instant.MAX;", private static final Instant OTHER = MIN;
" }", private static final Instant OTHER_MAX = Instant.MAX;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,59 +11,61 @@ final class OptionalOrElseGetTest {
CompilationTestHelper.newInstance(OptionalOrElseGet.class, getClass()) CompilationTestHelper.newInstance(OptionalOrElseGet.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.Refaster;", """
"import java.util.Optional;", import com.google.errorprone.refaster.Refaster;
"import java.util.function.Supplier;", import java.util.Optional;
"", import java.util.function.Supplier;
"class A {",
" private final Optional<Object> optional = Optional.empty();", class A {
" private final String string = optional.toString();", private final Optional<Object> optional = Optional.empty();
"", private final String string = optional.toString();
" void m() {",
" Optional.empty().orElse(null);", void m() {
" optional.orElse(null);", Optional.empty().orElse(null);
" optional.orElse(\"constant\");", optional.orElse(null);
" optional.orElse(\"constant\" + 0);", optional.orElse("constant");
" optional.orElse(Boolean.TRUE);", optional.orElse("constant" + 0);
" optional.orElse(string);", optional.orElse(Boolean.TRUE);
" optional.orElse(this.string);", optional.orElse(string);
" optional.orElse(Refaster.anyOf(\"constant\", \"another\"));", optional.orElse(this.string);
" Optional.<Supplier<String>>empty().orElse(() -> \"constant\");", optional.orElse(Refaster.anyOf("constant", "another"));
"", Optional.<Supplier<String>>empty().orElse(() -> "constant");
" // BUG: Diagnostic contains:",
" Optional.empty().orElse(string + \"constant\");", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Optional.empty().orElse(string + "constant");
" optional.orElse(string + \"constant\");", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(string + "constant");
" optional.orElse(\"constant\".toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse("constant".toString());
" optional.orElse(string.toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(string.toString());
" optional.orElse(this.string.toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(this.string.toString());
" optional.orElse(String.valueOf(42));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(String.valueOf(42));
" optional.orElse(string.toString().length());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(string.toString().length());
" optional.orElse(\"constant\".equals(string));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse("constant".equals(string));
" optional.orElse(string.equals(string));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(string.equals(string));
" optional.orElse(this.string.equals(string));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(this.string.equals(string));
" optional.orElse(foo());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(foo());
" optional.orElse(this.foo());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(this.foo());
" optional.orElse(new Object() {});", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", optional.orElse(new Object() {});
" optional.orElse(new int[0].length);", // BUG: Diagnostic contains:
" }", optional.orElse(new int[0].length);
"", }
" private <T> T foo() {",
" return null;", private <T> T foo() {
" }", return null;
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -72,66 +74,70 @@ final class OptionalOrElseGetTest {
BugCheckerRefactoringTestHelper.newInstance(OptionalOrElseGet.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(OptionalOrElseGet.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import java.util.Optional;", """
"", import java.util.Optional;
"class A {",
" private final Optional<Object> optional = Optional.empty();", class A {
" private final String string = optional.toString();", private final Optional<Object> optional = Optional.empty();
"", private final String string = optional.toString();
" void m() {",
" optional.orElse(string + \"constant\");", void m() {
" optional.orElse(\"constant\".toString());", optional.orElse(string + "constant");
" optional.orElse(string.toString());", optional.orElse("constant".toString());
" optional.orElse(this.string.toString());", optional.orElse(string.toString());
" optional.orElse(String.valueOf(42));", optional.orElse(this.string.toString());
" optional.orElse(string.toString().length());", optional.orElse(String.valueOf(42));
" optional.orElse(string.equals(string));", optional.orElse(string.toString().length());
" optional.orElse(foo());", optional.orElse(string.equals(string));
" optional.orElse(this.<Number>foo());", optional.orElse(foo());
" optional.orElse(this.<String, Integer>bar());", optional.orElse(this.<Number>foo());
" optional.orElse(new Object() {});", optional.orElse(this.<String, Integer>bar());
" optional.orElse(new int[0].length);", optional.orElse(new Object() {});
" }", optional.orElse(new int[0].length);
"", }
" private <T> T foo() {",
" return null;", private <T> T foo() {
" }", return null;
"", }
" private <S, T> T bar() {",
" return null;", private <S, T> T bar() {
" }", return null;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import java.util.Optional;", """
"", import java.util.Optional;
"class A {",
" private final Optional<Object> optional = Optional.empty();", class A {
" private final String string = optional.toString();", private final Optional<Object> optional = Optional.empty();
"", private final String string = optional.toString();
" void m() {",
" optional.orElseGet(() -> string + \"constant\");", void m() {
" optional.orElseGet(\"constant\"::toString);", optional.orElseGet(() -> string + "constant");
" optional.orElseGet(string::toString);", optional.orElseGet("constant"::toString);
" optional.orElseGet(this.string::toString);", optional.orElseGet(string::toString);
" optional.orElseGet(() -> String.valueOf(42));", optional.orElseGet(this.string::toString);
" optional.orElseGet(() -> string.toString().length());", optional.orElseGet(() -> String.valueOf(42));
" optional.orElseGet(() -> string.equals(string));", optional.orElseGet(() -> string.toString().length());
" optional.orElseGet(() -> foo());", optional.orElseGet(() -> string.equals(string));
" optional.orElseGet(this::<Number>foo);", optional.orElseGet(() -> foo());
" optional.orElseGet(this::<String, Integer>bar);", optional.orElseGet(this::<Number>foo);
" optional.orElseGet(() -> new Object() {});", optional.orElseGet(this::<String, Integer>bar);
" optional.orElseGet(() -> new int[0].length);", optional.orElseGet(() -> new Object() {});
" }", optional.orElseGet(() -> new int[0].length);
"", }
" private <T> T foo() {",
" return null;", private <T> T foo() {
" }", return null;
"", }
" private <S, T> T bar() {",
" return null;", private <S, T> T bar() {
" }", return null;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -14,21 +14,23 @@ final class RedundantStringConversionTest {
CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass()) CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" private final Object o = new Object();", class A {
" private final String s = o.toString();", private final Object o = new Object();
"", private final String s = o.toString();
" String[] m() {",
" return new String[] {", String[] m() {
" o.toString(),", return new String[] {
" // BUG: Diagnostic contains:", o.toString(),
" s.toString(),", // BUG: Diagnostic contains:
" String.valueOf(o),", s.toString(),
" // BUG: Diagnostic contains:", String.valueOf(o),
" String.valueOf(s),", // BUG: Diagnostic contains:
" };", String.valueOf(s),
" }", };
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -37,59 +39,61 @@ final class RedundantStringConversionTest {
CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass()) CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.math.BigInteger;", """
"import java.util.Objects;", import java.math.BigInteger;
"", import java.util.Objects;
"class A {",
" private final BigInteger i = BigInteger.ZERO;", class A {
"", private final BigInteger i = BigInteger.ZERO;
" void m1() {",
" String s = i.toString();", void m1() {
" // BUG: Diagnostic contains:", String s = i.toString();
" s += this.toString();", // BUG: Diagnostic contains:
" s += super.toString();", s += this.toString();
" // BUG: Diagnostic contains:", s += super.toString();
" s += i.toString();", // BUG: Diagnostic contains:
" s += i.toString(16);", s += i.toString();
" // BUG: Diagnostic contains:", s += i.toString(16);
" s += Objects.toString(i);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += Objects.toString(i);
" s += Objects.toString(null);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += Objects.toString(null);
" s += String.valueOf(i);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += String.valueOf(i);
" s += String.valueOf(0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += String.valueOf(0);
" s += String.valueOf((String) null);", // BUG: Diagnostic contains:
" s += String.valueOf(null);", s += String.valueOf((String) null);
" s += String.valueOf(new char[0]);", s += String.valueOf(null);
" s += String.valueOf(new char[0], 0, 0);", s += String.valueOf(new char[0]);
" // BUG: Diagnostic contains:", s += String.valueOf(new char[0], 0, 0);
" s += Boolean.toString(false);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += Boolean.toString(false);
" s += Byte.toString((byte) 0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += Byte.toString((byte) 0);
" s += Character.toString((char) 0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += Character.toString((char) 0);
" s += Short.toString((short) 0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += Short.toString((short) 0);
" s += Integer.toString(0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += Integer.toString(0);
" s += Long.toString(0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += Long.toString(0);
" s += Float.toString((float) 0.0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s += Float.toString((float) 0.0);
" s += Double.toString(0.0);", // BUG: Diagnostic contains:
" }", s += Double.toString(0.0);
"", }
" void m2() {",
" int i = 0;", void m2() {
" i += 1;", int i = 0;
" i -= 1;", i += 1;
" i *= 1;", i -= 1;
" i /= 1;", i *= 1;
" }", i /= 1;
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -98,93 +102,95 @@ final class RedundantStringConversionTest {
CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass()) CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.math.BigInteger;", """
"", import java.math.BigInteger;
"class A {",
" private final BigInteger i = BigInteger.ZERO;", class A {
" private final String s = i.toString();", private final BigInteger i = BigInteger.ZERO;
"", private final String s = i.toString();
" String[] m1() {",
" return new String[] {", String[] m1() {
" // BUG: Diagnostic contains:", return new String[] {
" s + this.toString(),", // BUG: Diagnostic contains:
" s + super.toString(),", s + this.toString(),
" // BUG: Diagnostic contains:", s + super.toString(),
" s + i.toString(),", // BUG: Diagnostic contains:
" s + i.toString(16),", s + i.toString(),
" // BUG: Diagnostic contains:", s + i.toString(16),
" s + String.valueOf(i),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + String.valueOf(i),
" s + String.valueOf(0),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + String.valueOf(0),
" s + String.valueOf((String) null),", // BUG: Diagnostic contains:
" s + String.valueOf(null),", s + String.valueOf((String) null),
" s + String.valueOf(new char[0]),", s + String.valueOf(null),
" s + String.valueOf(new char[0], 0, 0),", s + String.valueOf(new char[0]),
" //", s + String.valueOf(new char[0], 0, 0),
" 42 + this.toString(),", //
" 42 + super.toString(),", 42 + this.toString(),
" 42 + i.toString(),", 42 + super.toString(),
" 42 + i.toString(16),", 42 + i.toString(),
" 42 + String.valueOf(i),", 42 + i.toString(16),
" // BUG: Diagnostic contains:", 42 + String.valueOf(i),
" 42 + String.valueOf((String) null),", // BUG: Diagnostic contains:
" 42 + String.valueOf(null),", 42 + String.valueOf((String) null),
" 42 + String.valueOf(new char[0]),", 42 + String.valueOf(null),
" 42 + String.valueOf(new char[0], 0, 0),", 42 + String.valueOf(new char[0]),
"", 42 + String.valueOf(new char[0], 0, 0),
" // BUG: Diagnostic contains:",
" this.toString() + s,", // BUG: Diagnostic contains:
" super.toString() + s,", this.toString() + s,
" // BUG: Diagnostic contains:", super.toString() + s,
" i.toString() + s,", // BUG: Diagnostic contains:
" i.toString(16) + s,", i.toString() + s,
" // BUG: Diagnostic contains:", i.toString(16) + s,
" String.valueOf(i) + s,", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.valueOf(i) + s,
" String.valueOf(0) + s,", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.valueOf(0) + s,
" String.valueOf((String) null) + s,", // BUG: Diagnostic contains:
" String.valueOf(null) + s,", String.valueOf((String) null) + s,
" String.valueOf(new char[0]) + s,", String.valueOf(null) + s,
" String.valueOf(new char[0], 0, 0) + s,", String.valueOf(new char[0]) + s,
" //", String.valueOf(new char[0], 0, 0) + s,
" this.toString() + 42,", //
" super.toString() + 42,", this.toString() + 42,
" i.toString() + 42,", super.toString() + 42,
" i.toString(16) + 42,", i.toString() + 42,
" String.valueOf(i) + 42,", i.toString(16) + 42,
" String.valueOf(0) + 42,", String.valueOf(i) + 42,
" // BUG: Diagnostic contains:", String.valueOf(0) + 42,
" String.valueOf((String) null) + 42,", // BUG: Diagnostic contains:
" String.valueOf(null) + 42,", String.valueOf((String) null) + 42,
" String.valueOf(new char[0]) + 42,", String.valueOf(null) + 42,
" String.valueOf(new char[0], 0, 0) + 42,", String.valueOf(new char[0]) + 42,
"", String.valueOf(new char[0], 0, 0) + 42,
" // BUG: Diagnostic contains:",
" this.toString() + this.toString(),", // BUG: Diagnostic contains:
" super.toString() + super.toString(),", this.toString() + this.toString(),
" // BUG: Diagnostic contains:", super.toString() + super.toString(),
" i.toString() + i.toString(),", // BUG: Diagnostic contains:
" i.toString(16) + i.toString(16),", i.toString() + i.toString(),
" // BUG: Diagnostic contains:", i.toString(16) + i.toString(16),
" String.valueOf(i) + String.valueOf(i),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.valueOf(i) + String.valueOf(i),
" String.valueOf(0) + String.valueOf(0),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.valueOf(0) + String.valueOf(0),
" String.valueOf((String) null) + String.valueOf((String) null),", // BUG: Diagnostic contains:
" String.valueOf(null) + String.valueOf(null),", String.valueOf((String) null) + String.valueOf((String) null),
" String.valueOf(new char[0]) + String.valueOf(new char[0]),", String.valueOf(null) + String.valueOf(null),
" String.valueOf(new char[0], 0, 0) + String.valueOf(new char[0], 0, 0),", String.valueOf(new char[0]) + String.valueOf(new char[0]),
" };", String.valueOf(new char[0], 0, 0) + String.valueOf(new char[0], 0, 0),
" }", };
"", }
" int[] m2() {",
" return new int[] {", int[] m2() {
" 1 + 1, 1 - 1, 1 * 1, 1 / 1,", return new int[] {
" };", 1 + 1, 1 - 1, 1 * 1, 1 / 1,
" }", };
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -193,52 +199,54 @@ final class RedundantStringConversionTest {
CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass()) CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.math.BigInteger;", """
"", import java.math.BigInteger;
"class A {",
" private final BigInteger i = BigInteger.ZERO;", class A {
" private final String s = i.toString();", private final BigInteger i = BigInteger.ZERO;
"", private final String s = i.toString();
" void m() {",
" StringBuilder sb = new StringBuilder();", void m() {
"", StringBuilder sb = new StringBuilder();
" sb.append(1);",
" sb.append(i);", sb.append(1);
" // BUG: Diagnostic contains:", sb.append(i);
" sb.append(i.toString());", // BUG: Diagnostic contains:
" sb.append(i.toString(16));", sb.append(i.toString());
" // BUG: Diagnostic contains:", sb.append(i.toString(16));
" sb.append(String.valueOf(i));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", sb.append(String.valueOf(i));
" sb.append(String.valueOf(0));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", sb.append(String.valueOf(0));
" sb.append(String.valueOf((String) null));", // BUG: Diagnostic contains:
" sb.append(String.valueOf(null));", sb.append(String.valueOf((String) null));
" sb.append(String.valueOf(new char[0]));", sb.append(String.valueOf(null));
" sb.append(String.valueOf(new char[0], 0, 0));", sb.append(String.valueOf(new char[0]));
" sb.append(s);", sb.append(String.valueOf(new char[0], 0, 0));
" sb.append(\"constant\");", sb.append(s);
"", sb.append("constant");
" sb.insert(0, 1);",
" sb.insert(0, i);", sb.insert(0, 1);
" // BUG: Diagnostic contains:", sb.insert(0, i);
" sb.insert(0, i.toString());", // BUG: Diagnostic contains:
" sb.insert(0, i.toString(16));", sb.insert(0, i.toString());
" // BUG: Diagnostic contains:", sb.insert(0, i.toString(16));
" sb.insert(0, String.valueOf(i));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", sb.insert(0, String.valueOf(i));
" sb.insert(0, String.valueOf(0));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", sb.insert(0, String.valueOf(0));
" sb.insert(0, String.valueOf((String) null));", // BUG: Diagnostic contains:
" sb.insert(0, String.valueOf(null));", sb.insert(0, String.valueOf((String) null));
" sb.insert(0, String.valueOf(new char[0]));", sb.insert(0, String.valueOf(null));
" sb.insert(0, String.valueOf(new char[0], 0, 0));", sb.insert(0, String.valueOf(new char[0]));
" sb.insert(0, s);", sb.insert(0, String.valueOf(new char[0], 0, 0));
" sb.insert(0, \"constant\");", sb.insert(0, s);
"", sb.insert(0, "constant");
" sb.replace(0, 1, i.toString());",
" }", sb.replace(0, 1, i.toString());
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -248,43 +256,45 @@ final class RedundantStringConversionTest {
CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass()) CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.Formattable;", """
"import java.util.Locale;", import java.util.Formattable;
"", import java.util.Locale;
"class A {",
" private final Locale locale = Locale.ROOT;", class A {
" private final Formattable f = (formatter, flags, width, precision) -> {};", private final Locale locale = Locale.ROOT;
" private final Object o = new Object();", private final Formattable f = (formatter, flags, width, precision) -> {};
" private final String s = o.toString();", private final Object o = new Object();
"", private final String s = o.toString();
" void m() {",
" String.format(s, f);", void m() {
" String.format(s, o);", String.format(s, f);
" String.format(s, s);", String.format(s, o);
" String.format(s, f.toString());", String.format(s, s);
" // BUG: Diagnostic contains:", String.format(s, f.toString());
" String.format(s, o.toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.format(s, o.toString());
" String.format(s, String.valueOf(o));", // BUG: Diagnostic contains:
"", String.format(s, String.valueOf(o));
" String.format(locale, s, f);",
" String.format(locale, s, o);", String.format(locale, s, f);
" String.format(locale, s, s);", String.format(locale, s, o);
" String.format(locale, s, f.toString());", String.format(locale, s, s);
" // BUG: Diagnostic contains:", String.format(locale, s, f.toString());
" String.format(locale, s, o.toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", String.format(locale, s, o.toString());
" String.format(locale, s, String.valueOf(o));", // BUG: Diagnostic contains:
"", String.format(locale, s, String.valueOf(o));
" String.format(o.toString(), o);",
" // BUG: Diagnostic contains:", String.format(o.toString(), o);
" String.format(s.toString(), o);", // BUG: Diagnostic contains:
" String.format(locale.toString(), s, o);", String.format(s.toString(), o);
" String.format(locale, o.toString(), o);", String.format(locale.toString(), s, o);
" // BUG: Diagnostic contains:", String.format(locale, o.toString(), o);
" String.format(locale, s.toString(), o);", // BUG: Diagnostic contains:
" }", String.format(locale, s.toString(), o);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -293,58 +303,60 @@ final class RedundantStringConversionTest {
CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass()) CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static com.google.common.base.Preconditions.checkArgument;", """
"import static com.google.common.base.Preconditions.checkNotNull;", import static com.google.common.base.Preconditions.checkArgument;
"import static com.google.common.base.Preconditions.checkState;", import static com.google.common.base.Preconditions.checkNotNull;
"import static com.google.common.base.Verify.verify;", import static com.google.common.base.Preconditions.checkState;
"import static com.google.common.base.Verify.verifyNotNull;", import static com.google.common.base.Verify.verify;
"", import static com.google.common.base.Verify.verifyNotNull;
"import java.util.Formattable;",
"", import java.util.Formattable;
"class A {",
" private final Formattable f = (formatter, flags, width, precision) -> {};", class A {
" private final Object o = new Object();", private final Formattable f = (formatter, flags, width, precision) -> {};
" private final String s = o.toString();", private final Object o = new Object();
"", private final String s = o.toString();
" void m() {",
" checkState(true, s, f);", void m() {
" // BUG: Diagnostic contains:", checkState(true, s, f);
" checkState(true, s, f.toString());", // BUG: Diagnostic contains:
" checkState(true, f.toString(), f);", checkState(true, s, f.toString());
" // BUG: Diagnostic contains:", checkState(true, f.toString(), f);
" checkState(true, s.toString(), f);", // BUG: Diagnostic contains:
"", checkState(true, s.toString(), f);
" checkArgument(true, s, f);",
" // BUG: Diagnostic contains:", checkArgument(true, s, f);
" checkArgument(true, s, f.toString());", // BUG: Diagnostic contains:
" checkArgument(true, f.toString(), f);", checkArgument(true, s, f.toString());
" // BUG: Diagnostic contains:", checkArgument(true, f.toString(), f);
" checkArgument(true, s.toString(), f);", // BUG: Diagnostic contains:
"", checkArgument(true, s.toString(), f);
" checkNotNull(o, s, f);",
" // BUG: Diagnostic contains:", checkNotNull(o, s, f);
" checkNotNull(o, s, f.toString());", // BUG: Diagnostic contains:
" checkNotNull(o, f.toString(), f);", checkNotNull(o, s, f.toString());
" // BUG: Diagnostic contains:", checkNotNull(o, f.toString(), f);
" checkNotNull(o, s.toString(), f);", // BUG: Diagnostic contains:
" checkNotNull(o.toString(), s, f);", checkNotNull(o, s.toString(), f);
"", checkNotNull(o.toString(), s, f);
" verify(true, s, f);",
" // BUG: Diagnostic contains:", verify(true, s, f);
" verify(true, s, f.toString());", // BUG: Diagnostic contains:
" verify(true, f.toString(), f);", verify(true, s, f.toString());
" // BUG: Diagnostic contains:", verify(true, f.toString(), f);
" verify(true, s.toString(), f);", // BUG: Diagnostic contains:
"", verify(true, s.toString(), f);
" verifyNotNull(o, s, f);",
" // BUG: Diagnostic contains:", verifyNotNull(o, s, f);
" verifyNotNull(o, s, f.toString());", // BUG: Diagnostic contains:
" verifyNotNull(o, f.toString(), f);", verifyNotNull(o, s, f.toString());
" // BUG: Diagnostic contains:", verifyNotNull(o, f.toString(), f);
" verifyNotNull(o, s.toString(), f);", // BUG: Diagnostic contains:
" verifyNotNull(o.toString(), s, f);", verifyNotNull(o, s.toString(), f);
" }", verifyNotNull(o.toString(), s, f);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -353,53 +365,55 @@ final class RedundantStringConversionTest {
CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass()) CompilationTestHelper.newInstance(RedundantStringConversion.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.Formattable;", """
"import org.slf4j.Logger;", import java.util.Formattable;
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"import org.slf4j.Marker;", import org.slf4j.LoggerFactory;
"import org.slf4j.MarkerFactory;", import org.slf4j.Marker;
"", import org.slf4j.MarkerFactory;
"class A {",
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", class A {
"", private static final Logger LOG = LoggerFactory.getLogger(A.class);
" private final Marker marker = MarkerFactory.getMarker(A.class.getName());",
" private final Formattable f = (formatter, flags, width, precision) -> {};", private final Marker marker = MarkerFactory.getMarker(A.class.getName());
" private final Object o = new Object();", private final Formattable f = (formatter, flags, width, precision) -> {};
" private final String s = f.toString();", private final Object o = new Object();
" private final Throwable t = new Throwable();", private final String s = f.toString();
"", private final Throwable t = new Throwable();
" void m() {",
" LOG.trace(s, f);", void m() {
" // BUG: Diagnostic contains:", LOG.trace(s, f);
" LOG.debug(s, f.toString());", // BUG: Diagnostic contains:
" LOG.info(s, t.toString());", LOG.debug(s, f.toString());
" LOG.warn(s, o, t.toString());", LOG.info(s, t.toString());
" // BUG: Diagnostic contains:", LOG.warn(s, o, t.toString());
" LOG.error(s, o.toString(), t.toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.error(s, o.toString(), t.toString());
" LOG.trace(s, t.toString(), o);", // BUG: Diagnostic contains:
"", LOG.trace(s, t.toString(), o);
" LOG.trace(marker, s, f);",
" // BUG: Diagnostic contains:", LOG.trace(marker, s, f);
" LOG.debug(marker, s, f.toString());", // BUG: Diagnostic contains:
" LOG.info(marker, s, t.toString());", LOG.debug(marker, s, f.toString());
" LOG.warn(marker, s, o, t.toString());", LOG.info(marker, s, t.toString());
" // BUG: Diagnostic contains:", LOG.warn(marker, s, o, t.toString());
" LOG.error(marker, s, o.toString(), t.toString());", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.error(marker, s, o.toString(), t.toString());
" LOG.trace(marker, s, t.toString(), o);", // BUG: Diagnostic contains:
"", LOG.trace(marker, s, t.toString(), o);
" LOG.trace(f.toString(), f);",
" // BUG: Diagnostic contains:", LOG.trace(f.toString(), f);
" LOG.debug(s.toString(), f);", // BUG: Diagnostic contains:
" LOG.info(t.toString(), f);", LOG.debug(s.toString(), f);
" LOG.warn(marker.toString(), s, f);", LOG.info(t.toString(), f);
" LOG.error(marker, o.toString(), f);", LOG.warn(marker.toString(), s, f);
" // BUG: Diagnostic contains:", LOG.error(marker, o.toString(), f);
" LOG.trace(marker, s.toString(), f);", // BUG: Diagnostic contains:
" LOG.debug(marker, t.toString(), f);", LOG.trace(marker, s.toString(), f);
" }", LOG.debug(marker, t.toString(), f);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -410,91 +424,93 @@ final class RedundantStringConversionTest {
"-XepOpt:RedundantStringConversion:ExtraConversionMethods=java.lang.Enum#name(),A#name(),A.B#toString(int)") "-XepOpt:RedundantStringConversion:ExtraConversionMethods=java.lang.Enum#name(),A#name(),A.B#toString(int)")
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.math.RoundingMode;", """
"import java.util.Objects;", import java.math.RoundingMode;
"", import java.util.Objects;
"class A {",
" static class B {", class A {
" String name() {", static class B {
" return toString();", String name() {
" }", return toString();
"", }
" static String toString(int i) {",
" return Integer.toString(i);", static String toString(int i) {
" }", return Integer.toString(i);
"", }
" static String toString(int i, int j) {",
" return Integer.toString(i * j);", static String toString(int i, int j) {
" }", return Integer.toString(i * j);
" }", }
"", }
" enum E {",
" ELEM;", enum E {
"", ELEM;
" public String toString() {",
" return \"__\" + name() + \"__\";", public String toString() {
" }", return "__" + name() + "__";
" }", }
"", }
" private final B b = new B();",
" private final String s = b.toString();", private final B b = new B();
"", private final String s = b.toString();
" String[] builtin() {",
" return new String[] {", String[] builtin() {
" // BUG: Diagnostic contains:", return new String[] {
" s + b.toString(),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + b.toString(),
" s + Objects.toString(b),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + Objects.toString(b),
" s + String.valueOf(b),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + String.valueOf(b),
" s + Boolean.toString(false),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + Boolean.toString(false),
" s + Byte.toString((byte) 0),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + Byte.toString((byte) 0),
" s + Character.toString((char) 0),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + Character.toString((char) 0),
" s + Short.toString((short) 0),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + Short.toString((short) 0),
" s + Integer.toString(0),", // BUG: Diagnostic contains:
" s + Integer.toString(0, 16),", s + Integer.toString(0),
" // BUG: Diagnostic contains:", s + Integer.toString(0, 16),
" s + Long.toString(0),", // BUG: Diagnostic contains:
" s + Long.toString(0, 16),", s + Long.toString(0),
" // BUG: Diagnostic contains:", s + Long.toString(0, 16),
" s + Float.toString((float) 0.0),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + Float.toString((float) 0.0),
" s + Double.toString(0.0),", // BUG: Diagnostic contains:
" };", s + Double.toString(0.0),
" }", };
"", }
" String[] custom() {",
" return new String[] {", String[] custom() {
" s + b.name(),", return new String[] {
" // BUG: Diagnostic contains:", s + b.name(),
" s + RoundingMode.UP.name(),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s + RoundingMode.UP.name(),
" s + mode().name(),", // BUG: Diagnostic contains:
" s + A.name(),", s + mode().name(),
" s + A.toString(42),", s + A.name(),
" // BUG: Diagnostic contains:", s + A.toString(42),
" s + B.toString(42),", // BUG: Diagnostic contains:
" s + B.toString(42, 42),", s + B.toString(42),
" };", s + B.toString(42, 42),
" }", };
"", }
" static String name() {",
" return A.class.toString();", static String name() {
" }", return A.class.toString();
"", }
" RoundingMode mode() {",
" return RoundingMode.UP;", RoundingMode mode() {
" }", return RoundingMode.UP;
"", }
" static String toString(int i) {",
" return Integer.toString(i);", static String toString(int i) {
" }", return Integer.toString(i);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -503,32 +519,36 @@ final class RedundantStringConversionTest {
BugCheckerRefactoringTestHelper.newInstance(RedundantStringConversion.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(RedundantStringConversion.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"class A {", """
" private final Object o = new Object();", class A {
" private final String s = o.toString();", private final Object o = new Object();
"", private final String s = o.toString();
" void m() {",
" String v1 = s.toString();", void m() {
" String v2 = \"foo\".toString();", String v1 = s.toString();
" String v3 = v2 + super.toString();", String v2 = "foo".toString();
" String v4 = 42 + String.valueOf((String) null);", String v3 = v2 + super.toString();
" String.format(\"%s\", o.toString());", String v4 = 42 + String.valueOf((String) null);
" }", String.format("%s", o.toString());
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"class A {", """
" private final Object o = new Object();", class A {
" private final String s = o.toString();", private final Object o = new Object();
"", private final String s = o.toString();
" void m() {",
" String v1 = s;", void m() {
" String v2 = \"foo\";", String v1 = s;
" String v3 = v2 + super.toString();", String v2 = "foo";
" String v4 = 42 + (String) null;", String v3 = v2 + super.toString();
" String.format(\"%s\", o);", String v4 = 42 + (String) null;
" }", String.format("%s", o);
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,38 +11,40 @@ final class RedundantStringEscapeTest {
CompilationTestHelper.newInstance(RedundantStringEscape.class, getClass()) CompilationTestHelper.newInstance(RedundantStringEscape.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.Arrays;", """
"import java.util.List;", import java.util.Arrays;
"", import java.util.List;
"class A {",
" List<String> m() {", class A {
" return Arrays.asList(", List<String> m() {
" \"foo\",", return Arrays.asList(
" \"ß\",", "foo",
" \"'\",", "ß",
" \"\\\"\",", "'",
" \"\\\\\",", "\\"",
" \"\\\\'\",", "\\\\",
" \"'\\\\\",", "\\\\'",
" // BUG: Diagnostic contains:", "'\\\\",
" \"\\\\\\'\",", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", "\\\\\\'",
" \"\\'\\\\\",", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", "\\'\\\\",
" \"\\'\",", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", "\\'",
" \"'\\'\",", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", "'\\'",
" \"\\''\",", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", "\\''",
" \"\\'\\'\",", // BUG: Diagnostic contains:
" (", "\\'\\'",
" // BUG: Diagnostic contains:", (
" /* Leading comment. */ \"\\'\" /* Trailing comment. */),", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", /* Leading comment. */ "\\'" /* Trailing comment. */),
" \"\\'foo\\\"bar\\'baz\\\"qux\\'\");", // BUG: Diagnostic contains:
" }", "\\'foo\\"bar\\'baz\\"qux\\'");
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -51,40 +53,44 @@ final class RedundantStringEscapeTest {
BugCheckerRefactoringTestHelper.newInstance(RedundantStringEscape.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(RedundantStringEscape.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import java.util.Arrays;", """
"import java.util.List;", import java.util.Arrays;
"", import java.util.List;
"class A {",
" List<String> m() {", class A {
" return Arrays.asList(", List<String> m() {
" \"\\'\",", return Arrays.asList(
" \"'\\'\",", "\\'",
" \"\\''\",", "'\\'",
" \"\\'\\'\",", "\\''",
" \"\\'ß\\'\",", "\\'\\'",
" (", "\\\\'",
" /* Leading comment. */ \"\\'\" /* Trailing comment. */),", (
" \"\\'foo\\\"bar\\'baz\\\"qux\\'\");", /* Leading comment. */ "\\'" /* Trailing comment. */),
" }", "\\'foo\\"bar\\'baz\\"qux\\'");
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import java.util.Arrays;", """
"import java.util.List;", import java.util.Arrays;
"", import java.util.List;
"class A {",
" List<String> m() {", class A {
" return Arrays.asList(", List<String> m() {
" \"'\",", return Arrays.asList(
" \"''\",", "'",
" \"''\",", "''",
" \"''\",", "''",
" \"'ß'\",", "''",
" (", "'ß'",
" /* Leading comment. */ \"'\" /* Trailing comment. */),", (
" \"'foo\\\"bar'baz\\\"qux'\");", /* Leading comment. */ "'" /* Trailing comment. */),
" }", "'foo\\"bar'baz\\"qux'");
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -9,138 +9,140 @@ final class RequestMappingAnnotationTest {
CompilationTestHelper.newInstance(RequestMappingAnnotation.class, getClass()) CompilationTestHelper.newInstance(RequestMappingAnnotation.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import jakarta.servlet.http.HttpServletRequest;", """
"import jakarta.servlet.http.HttpServletResponse;", import jakarta.servlet.http.HttpServletRequest;
"import java.io.InputStream;", import jakarta.servlet.http.HttpServletResponse;
"import java.time.ZoneId;", import java.io.InputStream;
"import java.util.Locale;", import java.time.ZoneId;
"import java.util.TimeZone;", import java.util.Locale;
"import org.springframework.http.HttpMethod;", import java.util.TimeZone;
"import org.springframework.security.core.annotation.CurrentSecurityContext;", import org.springframework.http.HttpMethod;
"import org.springframework.ui.Model;", import org.springframework.security.core.annotation.CurrentSecurityContext;
"import org.springframework.validation.BindingResult;", import org.springframework.ui.Model;
"import org.springframework.web.bind.annotation.DeleteMapping;", import org.springframework.validation.BindingResult;
"import org.springframework.web.bind.annotation.GetMapping;", import org.springframework.web.bind.annotation.DeleteMapping;
"import org.springframework.web.bind.annotation.PatchMapping;", import org.springframework.web.bind.annotation.GetMapping;
"import org.springframework.web.bind.annotation.PathVariable;", import org.springframework.web.bind.annotation.PatchMapping;
"import org.springframework.web.bind.annotation.PostMapping;", import org.springframework.web.bind.annotation.PathVariable;
"import org.springframework.web.bind.annotation.PutMapping;", import org.springframework.web.bind.annotation.PostMapping;
"import org.springframework.web.bind.annotation.RequestAttribute;", import org.springframework.web.bind.annotation.PutMapping;
"import org.springframework.web.bind.annotation.RequestBody;", import org.springframework.web.bind.annotation.RequestAttribute;
"import org.springframework.web.bind.annotation.RequestHeader;", import org.springframework.web.bind.annotation.RequestBody;
"import org.springframework.web.bind.annotation.RequestMapping;", import org.springframework.web.bind.annotation.RequestHeader;
"import org.springframework.web.bind.annotation.RequestParam;", import org.springframework.web.bind.annotation.RequestMapping;
"import org.springframework.web.bind.annotation.RequestPart;", import org.springframework.web.bind.annotation.RequestParam;
"import org.springframework.web.context.request.NativeWebRequest;", import org.springframework.web.bind.annotation.RequestPart;
"import org.springframework.web.context.request.WebRequest;", import org.springframework.web.context.request.NativeWebRequest;
"import org.springframework.web.server.ServerWebExchange;", import org.springframework.web.context.request.WebRequest;
"import org.springframework.web.util.UriBuilder;", import org.springframework.web.server.ServerWebExchange;
"import org.springframework.web.util.UriComponentsBuilder;", import org.springframework.web.util.UriBuilder;
"", import org.springframework.web.util.UriComponentsBuilder;
"interface A {",
" A noMapping();", interface A {
"", A noMapping();
" A noMapping(String param);",
"", A noMapping(String param);
" @DeleteMapping",
" A properNoParameters();", @DeleteMapping
"", A properNoParameters();
" @GetMapping",
" A properPathVariable(@PathVariable String param);", @GetMapping
"", A properPathVariable(@PathVariable String param);
" @PatchMapping",
" A properRequestAttribute(@RequestAttribute String attribute);", @PatchMapping
"", A properRequestAttribute(@RequestAttribute String attribute);
" @PostMapping",
" A properRequestBody(@RequestBody String body);", @PostMapping
"", A properRequestBody(@RequestBody String body);
" @PutMapping",
" A properRequestHeader(@RequestHeader String header);", @PutMapping
"", A properRequestHeader(@RequestHeader String header);
" @RequestMapping",
" A properRequestParam(@RequestParam String param);", @RequestMapping
"", A properRequestParam(@RequestParam String param);
" @RequestMapping",
" A properRequestPart(@RequestPart String part);", @RequestMapping
"", A properRequestPart(@RequestPart String part);
" @RequestMapping",
" A properCurrentSecurityContext(", @RequestMapping
" @CurrentSecurityContext(expression = \"authentication.name\") String user);", A properCurrentSecurityContext(
"", @CurrentSecurityContext(expression = "authentication.name") String user);
" @RequestMapping",
" A properInputStream(InputStream input);", @RequestMapping
"", A properInputStream(InputStream input);
" @RequestMapping",
" A properZoneId(ZoneId zoneId);", @RequestMapping
"", A properZoneId(ZoneId zoneId);
" @RequestMapping",
" A properLocale(Locale locale);", @RequestMapping
"", A properLocale(Locale locale);
" @RequestMapping",
" A properTimeZone(TimeZone timeZone);", @RequestMapping
"", A properTimeZone(TimeZone timeZone);
" @RequestMapping",
" A properHttpServletRequest(HttpServletRequest request);", @RequestMapping
"", A properHttpServletRequest(HttpServletRequest request);
" @RequestMapping",
" A properHttpServletResponse(HttpServletResponse response);", @RequestMapping
"", A properHttpServletResponse(HttpServletResponse response);
" @RequestMapping",
" A properHttpMethod(HttpMethod method);", @RequestMapping
"", A properHttpMethod(HttpMethod method);
" @RequestMapping",
" A properModel(Model model);", @RequestMapping
"", A properModel(Model model);
" @RequestMapping",
" A properBindingResult(BindingResult result);", @RequestMapping
"", A properBindingResult(BindingResult result);
" @RequestMapping",
" A properNativeWebRequest(NativeWebRequest request);", @RequestMapping
"", A properNativeWebRequest(NativeWebRequest request);
" @RequestMapping",
" A properWebRequest(WebRequest request);", @RequestMapping
"", A properWebRequest(WebRequest request);
" @RequestMapping",
" A properServerWebExchange(ServerWebExchange exchange);", @RequestMapping
"", A properServerWebExchange(ServerWebExchange exchange);
" @RequestMapping",
" A properServerUriBuilder(UriBuilder builder);", @RequestMapping
"", A properServerUriBuilder(UriBuilder builder);
" @RequestMapping",
" A properServerUriComponentsBuilder(UriComponentsBuilder builder);", @RequestMapping
"", A properServerUriComponentsBuilder(UriComponentsBuilder builder);
" @DeleteMapping",
" // BUG: Diagnostic contains:", @DeleteMapping
" A delete(String param);", // BUG: Diagnostic contains:
"", A delete(String param);
" @GetMapping",
" // BUG: Diagnostic contains:", @GetMapping
" A get(String param);", // BUG: Diagnostic contains:
"", A get(String param);
" @PatchMapping",
" // BUG: Diagnostic contains:", @PatchMapping
" A patch(String param);", // BUG: Diagnostic contains:
"", A patch(String param);
" @PostMapping",
" // BUG: Diagnostic contains:", @PostMapping
" A post(String param);", // BUG: Diagnostic contains:
"", A post(String param);
" @PutMapping",
" // BUG: Diagnostic contains:", @PutMapping
" A put(String param);", // BUG: Diagnostic contains:
"", A put(String param);
" @RequestMapping",
" // BUG: Diagnostic contains:", @RequestMapping
" A requestMultiple(String param, String param2);", // BUG: Diagnostic contains:
"", A requestMultiple(String param, String param2);
" @RequestMapping",
" // BUG: Diagnostic contains:", @RequestMapping
" A requestFirstParamViolation(String param, @PathVariable String param2);", // BUG: Diagnostic contains:
"", A requestFirstParamViolation(String param, @PathVariable String param2);
" @RequestMapping",
" // BUG: Diagnostic contains:", @RequestMapping
" A requestSecondParamViolation(@RequestBody String param, String param2);", // BUG: Diagnostic contains:
"}") A requestSecondParamViolation(@RequestBody String param, String param2);
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -9,55 +9,57 @@ final class RequestParamTypeTest {
CompilationTestHelper.newInstance(RequestParamType.class, getClass()) CompilationTestHelper.newInstance(RequestParamType.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableBiMap;", """
"import com.google.common.collect.ImmutableList;", import com.google.common.collect.ImmutableBiMap;
"import com.google.common.collect.ImmutableMap;", import com.google.common.collect.ImmutableList;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableMap;
"import java.util.List;", import com.google.common.collect.ImmutableSet;
"import java.util.Map;", import java.util.List;
"import java.util.Set;", import java.util.Map;
"import org.jspecify.annotations.Nullable;", import java.util.Set;
"import org.springframework.web.bind.annotation.DeleteMapping;", import org.jspecify.annotations.Nullable;
"import org.springframework.web.bind.annotation.GetMapping;", import org.springframework.web.bind.annotation.DeleteMapping;
"import org.springframework.web.bind.annotation.PostMapping;", import org.springframework.web.bind.annotation.GetMapping;
"import org.springframework.web.bind.annotation.PutMapping;", import org.springframework.web.bind.annotation.PostMapping;
"import org.springframework.web.bind.annotation.RequestBody;", import org.springframework.web.bind.annotation.PutMapping;
"import org.springframework.web.bind.annotation.RequestParam;", import org.springframework.web.bind.annotation.RequestBody;
"", import org.springframework.web.bind.annotation.RequestParam;
"interface A {",
" @PostMapping", interface A {
" A properRequestParam(@RequestBody String body);", @PostMapping
"", A properRequestParam(@RequestBody String body);
" @GetMapping",
" A properRequestParam(@RequestParam int param);", @GetMapping
"", A properRequestParam(@RequestParam int param);
" @GetMapping",
" A properRequestParam(@RequestParam List<String> param);", @GetMapping
"", A properRequestParam(@RequestParam List<String> param);
" @PostMapping",
" A properRequestParam(@RequestBody String body, @RequestParam Set<String> param);", @PostMapping
"", A properRequestParam(@RequestBody String body, @RequestParam Set<String> param);
" @PutMapping",
" A properRequestParam(@RequestBody String body, @RequestParam Map<String, String> param);", @PutMapping
"", A properRequestParam(@RequestBody String body, @RequestParam Map<String, String> param);
" @GetMapping",
" // BUG: Diagnostic contains:", @GetMapping
" A get(@RequestParam ImmutableBiMap<String, String> param);", // BUG: Diagnostic contains:
"", A get(@RequestParam ImmutableBiMap<String, String> param);
" @PostMapping",
" // BUG: Diagnostic contains:", @PostMapping
" A post(@Nullable @RequestParam ImmutableList<String> param);", // BUG: Diagnostic contains:
"", A post(@Nullable @RequestParam ImmutableList<String> param);
" @PutMapping",
" // BUG: Diagnostic contains:", @PutMapping
" A put(@RequestBody String body, @RequestParam ImmutableSet<String> param);", // BUG: Diagnostic contains:
"", A put(@RequestBody String body, @RequestParam ImmutableSet<String> param);
" @DeleteMapping",
" // BUG: Diagnostic contains:", @DeleteMapping
" A delete(@RequestBody String body, @RequestParam ImmutableMap<String, String> param);", // BUG: Diagnostic contains:
"", A delete(@RequestBody String body, @RequestParam ImmutableMap<String, String> param);
" void negative(ImmutableSet<Integer> set, ImmutableMap<String, String> map);",
"}") void negative(ImmutableSet<Integer> set, ImmutableMap<String, String> map);
}
""")
.doTest(); .doTest();
} }
@@ -68,47 +70,49 @@ final class RequestParamTypeTest {
"-XepOpt:RequestParamType:SupportedCustomTypes=com.google.common.collect.ImmutableSet,com.google.common.collect.ImmutableSortedMultiset") "-XepOpt:RequestParamType:SupportedCustomTypes=com.google.common.collect.ImmutableSet,com.google.common.collect.ImmutableSortedMultiset")
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableBiMap;", """
"import com.google.common.collect.ImmutableCollection;", import com.google.common.collect.ImmutableBiMap;
"import com.google.common.collect.ImmutableList;", import com.google.common.collect.ImmutableCollection;
"import com.google.common.collect.ImmutableMap;", import com.google.common.collect.ImmutableList;
"import com.google.common.collect.ImmutableMultiset;", import com.google.common.collect.ImmutableMap;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableMultiset;
"import com.google.common.collect.ImmutableSortedMultiset;", import com.google.common.collect.ImmutableSet;
"import com.google.common.collect.ImmutableSortedSet;", import com.google.common.collect.ImmutableSortedMultiset;
"import org.springframework.web.bind.annotation.GetMapping;", import com.google.common.collect.ImmutableSortedSet;
"import org.springframework.web.bind.annotation.RequestParam;", import org.springframework.web.bind.annotation.GetMapping;
"", import org.springframework.web.bind.annotation.RequestParam;
"interface A {",
" @GetMapping", interface A {
" // BUG: Diagnostic contains:", @GetMapping
" A immutableCollection(@RequestParam ImmutableCollection<String> param);", // BUG: Diagnostic contains:
"", A immutableCollection(@RequestParam ImmutableCollection<String> param);
" @GetMapping",
" // BUG: Diagnostic contains:", @GetMapping
" A immutableList(@RequestParam ImmutableList<String> param);", // BUG: Diagnostic contains:
"", A immutableList(@RequestParam ImmutableList<String> param);
" @GetMapping",
" A immutableSet(@RequestParam ImmutableSet<String> param);", @GetMapping
"", A immutableSet(@RequestParam ImmutableSet<String> param);
" @GetMapping",
" A immutableSortedSet(@RequestParam ImmutableSortedSet<String> param);", @GetMapping
"", A immutableSortedSet(@RequestParam ImmutableSortedSet<String> param);
" @GetMapping",
" // BUG: Diagnostic contains:", @GetMapping
" A immutableMultiset(@RequestParam ImmutableMultiset<String> param);", // BUG: Diagnostic contains:
"", A immutableMultiset(@RequestParam ImmutableMultiset<String> param);
" @GetMapping",
" A immutableSortedMultiset(@RequestParam ImmutableSortedMultiset<String> param);", @GetMapping
"", A immutableSortedMultiset(@RequestParam ImmutableSortedMultiset<String> param);
" @GetMapping",
" // BUG: Diagnostic contains:", @GetMapping
" A immutableMap(@RequestParam ImmutableMap<String, String> param);", // BUG: Diagnostic contains:
"", A immutableMap(@RequestParam ImmutableMap<String, String> param);
" @GetMapping",
" // BUG: Diagnostic contains:", @GetMapping
" A immutableBiMap(@RequestParam ImmutableBiMap<String, String> param);", // BUG: Diagnostic contains:
"}") A immutableBiMap(@RequestParam ImmutableBiMap<String, String> param);
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -11,79 +11,81 @@ final class Slf4jLogStatementTest {
CompilationTestHelper.newInstance(Slf4jLogStatement.class, getClass()) CompilationTestHelper.newInstance(Slf4jLogStatement.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import org.slf4j.Logger;", """
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"import org.slf4j.Marker;", import org.slf4j.LoggerFactory;
"import org.slf4j.MarkerFactory;", import org.slf4j.Marker;
"", import org.slf4j.MarkerFactory;
"class A {",
" private static final String FMT0 = \"format-string-without-placeholders\";", class A {
" private static final String FMT1 = \"format-string-with-{}-placeholder\";", private static final String FMT0 = "format-string-without-placeholders";
" private static final String FMT_ERR = \"format-string-with-%s-placeholder\";", private static final String FMT1 = "format-string-with-{}-placeholder";
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", private static final String FMT_ERR = "format-string-with-%s-placeholder";
"", private static final Logger LOG = LoggerFactory.getLogger(A.class);
" private final Marker marker = MarkerFactory.getMarker(A.class.getName());",
" private final Object o = new Object();", private final Marker marker = MarkerFactory.getMarker(A.class.getName());
" private final String s = o.toString();", private final Object o = new Object();
" private final Throwable t = new Throwable();", private final String s = o.toString();
"", private final Throwable t = new Throwable();
" void m() {",
" LOG.trace(s);", void m() {
" LOG.debug(s, o);", LOG.trace(s);
" LOG.info(s, t);", LOG.debug(s, o);
" LOG.warn(s, o, t);", LOG.info(s, t);
" LOG.error(marker, s);", LOG.warn(s, o, t);
" LOG.trace(marker, s, o);", LOG.error(marker, s);
" LOG.debug(marker, s, t);", LOG.trace(marker, s, o);
" LOG.info(marker, s, o, t);", LOG.debug(marker, s, t);
"", LOG.info(marker, s, o, t);
" LOG.warn(FMT0);",
" // BUG: Diagnostic contains: Log statement contains 0 placeholders, but specifies 1 matching", LOG.warn(FMT0);
" // argument(s)", // BUG: Diagnostic contains: Log statement contains 0 placeholders, but specifies 1 matching
" LOG.error(FMT0, o);", // argument(s)
" LOG.trace(FMT0, t);", LOG.error(FMT0, o);
" // BUG: Diagnostic contains:", LOG.trace(FMT0, t);
" LOG.debug(FMT0, o, t);", // BUG: Diagnostic contains:
" LOG.info(marker, FMT0);", LOG.debug(FMT0, o, t);
" // BUG: Diagnostic contains:", LOG.info(marker, FMT0);
" LOG.warn(marker, FMT0, o);", // BUG: Diagnostic contains:
" LOG.error(marker, FMT0, t);", LOG.warn(marker, FMT0, o);
" // BUG: Diagnostic contains:", LOG.error(marker, FMT0, t);
" LOG.trace(marker, FMT0, o, t);", // BUG: Diagnostic contains:
"", LOG.trace(marker, FMT0, o, t);
" // BUG: Diagnostic contains: Log statement contains 1 placeholders, but specifies 0 matching",
" // argument(s)", // BUG: Diagnostic contains: Log statement contains 1 placeholders, but specifies 0 matching
" LOG.debug(FMT1);", // argument(s)
" LOG.info(FMT1, o);", LOG.debug(FMT1);
" // BUG: Diagnostic contains:", LOG.info(FMT1, o);
" LOG.warn(FMT1, t);", // BUG: Diagnostic contains:
" LOG.error(FMT1, o, t);", LOG.warn(FMT1, t);
" // BUG: Diagnostic contains: Log statement contains 1 placeholders, but specifies 2 matching", LOG.error(FMT1, o, t);
" // argument(s)", // BUG: Diagnostic contains: Log statement contains 1 placeholders, but specifies 2 matching
" LOG.trace(FMT1, o, o);", // argument(s)
" // BUG: Diagnostic contains:", LOG.trace(FMT1, o, o);
" LOG.debug(FMT1, o, o, t);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.debug(FMT1, o, o, t);
" LOG.info(marker, FMT1);", // BUG: Diagnostic contains:
" LOG.warn(marker, FMT1, o);", LOG.info(marker, FMT1);
" // BUG: Diagnostic contains:", LOG.warn(marker, FMT1, o);
" LOG.error(marker, FMT1, t);", // BUG: Diagnostic contains:
" LOG.trace(marker, FMT1, o, t);", LOG.error(marker, FMT1, t);
" // BUG: Diagnostic contains:", LOG.trace(marker, FMT1, o, t);
" LOG.debug(marker, FMT1, o, o);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.debug(marker, FMT1, o, o);
" LOG.info(marker, FMT1, o, o, t);", // BUG: Diagnostic contains:
"", LOG.info(marker, FMT1, o, o, t);
" // BUG: Diagnostic contains: SLF4J log statement placeholders are of the form `{}`, not `%s`",
" LOG.warn(FMT_ERR);", // BUG: Diagnostic contains: SLF4J log statement placeholders are of the form `{}`, not `%s`
" // BUG: Diagnostic contains:", LOG.warn(FMT_ERR);
" LOG.error(FMT_ERR, t);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.error(FMT_ERR, t);
" LOG.trace(FMT_ERR, o);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LOG.trace(FMT_ERR, o);
" LOG.debug(FMT_ERR, o, t);", // BUG: Diagnostic contains:
" }", LOG.debug(FMT_ERR, o, t);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -93,50 +95,54 @@ final class Slf4jLogStatementTest {
BugCheckerRefactoringTestHelper.newInstance(Slf4jLogStatement.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(Slf4jLogStatement.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import org.slf4j.Logger;", """
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"import org.slf4j.Marker;", import org.slf4j.LoggerFactory;
"import org.slf4j.MarkerFactory;", import org.slf4j.Marker;
"", import org.slf4j.MarkerFactory;
"class A {",
" private static final String FMT_ERR = \"format-string-with-%s-placeholder\";", class A {
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", private static final String FMT_ERR = "format-string-with-%s-placeholder";
"", private static final Logger LOG = LoggerFactory.getLogger(A.class);
" private final Marker marker = MarkerFactory.getMarker(A.class.getName());",
" private final Object o = new Object();", private final Marker marker = MarkerFactory.getMarker(A.class.getName());
" private final String s = o.toString();", private final Object o = new Object();
" private final Throwable t = new Throwable();", private final String s = o.toString();
"", private final Throwable t = new Throwable();
" void m() {",
" LOG.error(FMT_ERR, o);", void m() {
" LOG.error(\"format-string-with-'%s'-placeholder\", o);", LOG.error(FMT_ERR, o);
" LOG.error(\"format-string-with-\\\"%s\\\"-placeholder\", o);", LOG.error("format-string-with-'%s'-placeholder", o);
" LOG.error(\"format-string-with-%s\" + \"-placeholder\", o);", LOG.error("format-string-with-\\"%s\\"-placeholder", o);
" }", LOG.error("format-string-with-%s" + "-placeholder", o);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import org.slf4j.Logger;", """
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"import org.slf4j.Marker;", import org.slf4j.LoggerFactory;
"import org.slf4j.MarkerFactory;", import org.slf4j.Marker;
"", import org.slf4j.MarkerFactory;
"class A {",
" private static final String FMT_ERR = \"format-string-with-%s-placeholder\";", class A {
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", private static final String FMT_ERR = "format-string-with-%s-placeholder";
"", private static final Logger LOG = LoggerFactory.getLogger(A.class);
" private final Marker marker = MarkerFactory.getMarker(A.class.getName());",
" private final Object o = new Object();", private final Marker marker = MarkerFactory.getMarker(A.class.getName());
" private final String s = o.toString();", private final Object o = new Object();
" private final Throwable t = new Throwable();", private final String s = o.toString();
"", private final Throwable t = new Throwable();
" void m() {",
" LOG.error(FMT_ERR, o);", void m() {
" LOG.error(\"format-string-with-'{}'-placeholder\", o);", LOG.error(FMT_ERR, o);
" LOG.error(\"format-string-with-\\\"{}\\\"-placeholder\", o);", LOG.error("format-string-with-'{}'-placeholder", o);
" LOG.error(\"format-string-with-{}\" + \"-placeholder\", o);", LOG.error("format-string-with-\\"{}\\"-placeholder", o);
" }", LOG.error("format-string-with-{}" + "-placeholder", o);
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,123 +11,125 @@ final class Slf4jLoggerDeclarationTest {
CompilationTestHelper.newInstance(Slf4jLoggerDeclaration.class, getClass()) CompilationTestHelper.newInstance(Slf4jLoggerDeclaration.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static java.lang.Class.forName;", """
"", import static java.lang.Class.forName;
"import org.slf4j.Logger;",
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"", import org.slf4j.LoggerFactory;
"class A {",
" private static final long serialVersionUID = 1L;", class A {
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", private static final long serialVersionUID = 1L;
"", private static final Logger LOG = LoggerFactory.getLogger(A.class);
" abstract static class DynamicLogger {",
" private final Logger log = LoggerFactory.getLogger(getClass());", abstract static class DynamicLogger {
" }", private final Logger log = LoggerFactory.getLogger(getClass());
"", }
" abstract static class DynamicLoggerWithExplicitThis {",
" private final Logger log = LoggerFactory.getLogger(this.getClass());", abstract static class DynamicLoggerWithExplicitThis {
" }", private final Logger log = LoggerFactory.getLogger(this.getClass());
"", }
" static final class StaticLogger {",
" private static final Logger LOG = LoggerFactory.getLogger(StaticLogger.class);", static final class StaticLogger {
" }", private static final Logger LOG = LoggerFactory.getLogger(StaticLogger.class);
"", }
" static final class StaticLoggerWithCustomIdentifier {",
" private static final Logger LOG = LoggerFactory.getLogger(\"custom-identifier\");", static final class StaticLoggerWithCustomIdentifier {
" }", private static final Logger LOG = LoggerFactory.getLogger("custom-identifier");
"", }
" interface StaticLoggerForInterface {",
" Logger LOG = LoggerFactory.getLogger(StaticLoggerForInterface.class);", interface StaticLoggerForInterface {
" }", Logger LOG = LoggerFactory.getLogger(StaticLoggerForInterface.class);
"", }
" abstract static class DynamicLoggerForWrongTypeWithoutReceiver {",
" // BUG: Diagnostic contains:", abstract static class DynamicLoggerForWrongTypeWithoutReceiver {
" private final Logger log = LoggerFactory.getLogger(forName(\"A.class\"));", // BUG: Diagnostic contains:
"", private final Logger log = LoggerFactory.getLogger(forName("A.class"));
" DynamicLoggerForWrongTypeWithoutReceiver() throws ClassNotFoundException {}",
" }", DynamicLoggerForWrongTypeWithoutReceiver() throws ClassNotFoundException {}
"", }
" abstract static class DynamicLoggerForWrongTypeWithoutSymbol {",
" // BUG: Diagnostic contains:", abstract static class DynamicLoggerForWrongTypeWithoutSymbol {
" private final Logger log = LoggerFactory.getLogger(\"foo\".getClass());", // BUG: Diagnostic contains:
" }", private final Logger log = LoggerFactory.getLogger("foo".getClass());
"", }
" abstract static class DynamicLoggerForWrongTypeWithSymbol {",
" // BUG: Diagnostic contains:", abstract static class DynamicLoggerForWrongTypeWithSymbol {
" private final Logger log = LoggerFactory.getLogger(new A().getClass());", // BUG: Diagnostic contains:
" }", private final Logger log = LoggerFactory.getLogger(new A().getClass());
"", }
" static final class NonAbstractDynamicLogger {",
" // BUG: Diagnostic contains:", static final class NonAbstractDynamicLogger {
" private final Logger log = LoggerFactory.getLogger(getClass());", // BUG: Diagnostic contains:
" }", private final Logger log = LoggerFactory.getLogger(getClass());
"", }
" abstract static class DynamicLoggerWithMissingModifier {",
" // BUG: Diagnostic contains:", abstract static class DynamicLoggerWithMissingModifier {
" final Logger log = LoggerFactory.getLogger(getClass());", // BUG: Diagnostic contains:
" }", final Logger log = LoggerFactory.getLogger(getClass());
"", }
" abstract static class DynamicLoggerWithExcessModifier {",
" // BUG: Diagnostic contains:", abstract static class DynamicLoggerWithExcessModifier {
" private final transient Logger log = LoggerFactory.getLogger(getClass());", // BUG: Diagnostic contains:
" }", private final transient Logger log = LoggerFactory.getLogger(getClass());
"", }
" abstract static class MisnamedDynamicLogger {",
" // BUG: Diagnostic contains:", abstract static class MisnamedDynamicLogger {
" private final Logger LOG = LoggerFactory.getLogger(getClass());", // BUG: Diagnostic contains:
" }", private final Logger LOG = LoggerFactory.getLogger(getClass());
"", }
" static final class StaticLoggerWithMissingModifier {",
" // BUG: Diagnostic contains:", static final class StaticLoggerWithMissingModifier {
" static final Logger LOG = LoggerFactory.getLogger(StaticLoggerWithMissingModifier.class);", // BUG: Diagnostic contains:
" }", static final Logger LOG = LoggerFactory.getLogger(StaticLoggerWithMissingModifier.class);
"", }
" static final class StaticLoggerWithExcessModifier {",
" // BUG: Diagnostic contains:", static final class StaticLoggerWithExcessModifier {
" private static final transient Logger LOG =", // BUG: Diagnostic contains:
" LoggerFactory.getLogger(StaticLoggerWithExcessModifier.class);", private static final transient Logger LOG =
" }", LoggerFactory.getLogger(StaticLoggerWithExcessModifier.class);
"", }
" static final class MisnamedStaticLogger {",
" // BUG: Diagnostic contains:", static final class MisnamedStaticLogger {
" private static final Logger log = LoggerFactory.getLogger(MisnamedStaticLogger.class);", // BUG: Diagnostic contains:
" }", private static final Logger log = LoggerFactory.getLogger(MisnamedStaticLogger.class);
"", }
" static final class StaticLoggerWithIncorrectIdentifier {",
" // BUG: Diagnostic contains:", static final class StaticLoggerWithIncorrectIdentifier {
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", // BUG: Diagnostic contains:
" }", private static final Logger LOG = LoggerFactory.getLogger(A.class);
"", }
" static final class StaticLoggerWithCustomIdentifierAndMissingModifier {",
" // BUG: Diagnostic contains:", static final class StaticLoggerWithCustomIdentifierAndMissingModifier {
" static final Logger LOG = LoggerFactory.getLogger(\"custom-identifier\");", // BUG: Diagnostic contains:
" }", static final Logger LOG = LoggerFactory.getLogger("custom-identifier");
"", }
" static final class StaticLoggerWithCustomIdentifierAndExcessModifier {",
" // BUG: Diagnostic contains:", static final class StaticLoggerWithCustomIdentifierAndExcessModifier {
" private static final transient Logger LOG = LoggerFactory.getLogger(\"custom-identifier\");", // BUG: Diagnostic contains:
" }", private static final transient Logger LOG = LoggerFactory.getLogger("custom-identifier");
"", }
" static final class MisnamedStaticLoggerWithCustomIdentifier {",
" // BUG: Diagnostic contains:", static final class MisnamedStaticLoggerWithCustomIdentifier {
" private static final Logger log = LoggerFactory.getLogger(\"custom-identifier\");", // BUG: Diagnostic contains:
" }", private static final Logger log = LoggerFactory.getLogger("custom-identifier");
"", }
" interface StaticLoggerForInterfaceWithExcessModifier {",
" // BUG: Diagnostic contains:", interface StaticLoggerForInterfaceWithExcessModifier {
" static Logger LOG = LoggerFactory.getLogger(StaticLoggerForInterfaceWithExcessModifier.class);", // BUG: Diagnostic contains:
" }", static Logger LOG = LoggerFactory.getLogger(StaticLoggerForInterfaceWithExcessModifier.class);
"", }
" interface MisnamedStaticLoggerForInterface {",
" // BUG: Diagnostic contains:", interface MisnamedStaticLoggerForInterface {
" Logger log = LoggerFactory.getLogger(MisnamedStaticLoggerForInterface.class);", // BUG: Diagnostic contains:
" }", Logger log = LoggerFactory.getLogger(MisnamedStaticLoggerForInterface.class);
"", }
" interface StaticLoggerForInterfaceWithIncorrectIdentifier {",
" // BUG: Diagnostic contains:", interface StaticLoggerForInterfaceWithIncorrectIdentifier {
" Logger LOG = LoggerFactory.getLogger(A.class);", // BUG: Diagnostic contains:
" }", Logger LOG = LoggerFactory.getLogger(A.class);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -136,52 +138,56 @@ final class Slf4jLoggerDeclarationTest {
BugCheckerRefactoringTestHelper.newInstance(Slf4jLoggerDeclaration.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(Slf4jLoggerDeclaration.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import org.slf4j.Logger;", """
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"", import org.slf4j.LoggerFactory;
"class A {",
" static Logger foo = LoggerFactory.getLogger(Logger.class);", class A {
"", static Logger foo = LoggerFactory.getLogger(Logger.class);
" abstract static class DynamicLogger {",
" transient Logger BAR = LoggerFactory.getLogger(getClass());", abstract static class DynamicLogger {
" }", transient Logger BAR = LoggerFactory.getLogger(getClass());
"", }
" static final class StaticLogger {",
" transient Logger baz = LoggerFactory.getLogger(LoggerFactory.class);", static final class StaticLogger {
" }", transient Logger baz = LoggerFactory.getLogger(LoggerFactory.class);
"", }
" static final class StaticLoggerWithCustomIdentifier {",
" transient Logger qux = LoggerFactory.getLogger(\"custom-identifier\");", static final class StaticLoggerWithCustomIdentifier {
" }", transient Logger qux = LoggerFactory.getLogger("custom-identifier");
"", }
" interface StaticLoggerForInterface {",
" public static final Logger quux = LoggerFactory.getLogger(A.class);", interface StaticLoggerForInterface {
" }", public static final Logger quux = LoggerFactory.getLogger(A.class);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import org.slf4j.Logger;", """
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"", import org.slf4j.LoggerFactory;
"class A {",
" private static final Logger LOG = LoggerFactory.getLogger(A.class);", class A {
"", private static final Logger LOG = LoggerFactory.getLogger(A.class);
" abstract static class DynamicLogger {",
" private final Logger log = LoggerFactory.getLogger(getClass());", abstract static class DynamicLogger {
" }", private final Logger log = LoggerFactory.getLogger(getClass());
"", }
" static final class StaticLogger {",
" private static final Logger LOG = LoggerFactory.getLogger(StaticLogger.class);", static final class StaticLogger {
" }", private static final Logger LOG = LoggerFactory.getLogger(StaticLogger.class);
"", }
" static final class StaticLoggerWithCustomIdentifier {",
" private static final Logger LOG = LoggerFactory.getLogger(\"custom-identifier\");", static final class StaticLoggerWithCustomIdentifier {
" }", private static final Logger LOG = LoggerFactory.getLogger("custom-identifier");
"", }
" interface StaticLoggerForInterface {",
" Logger LOG = LoggerFactory.getLogger(StaticLoggerForInterface.class);", interface StaticLoggerForInterface {
" }", Logger LOG = LoggerFactory.getLogger(StaticLoggerForInterface.class);
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -191,28 +197,32 @@ final class Slf4jLoggerDeclarationTest {
.setArgs("-XepOpt:Slf4jLoggerDeclaration:CanonicalStaticLoggerName=FOO_BAR") .setArgs("-XepOpt:Slf4jLoggerDeclaration:CanonicalStaticLoggerName=FOO_BAR")
.addInputLines( .addInputLines(
"A.java", "A.java",
"import org.slf4j.Logger;", """
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"", import org.slf4j.LoggerFactory;
"class A {",
" transient Logger LOG = LoggerFactory.getLogger(Logger.class);", class A {
"", transient Logger LOG = LoggerFactory.getLogger(Logger.class);
" abstract static class DynamicLogger {",
" transient Logger log = LoggerFactory.getLogger(getClass());", abstract static class DynamicLogger {
" }", transient Logger log = LoggerFactory.getLogger(getClass());
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import org.slf4j.Logger;", """
"import org.slf4j.LoggerFactory;", import org.slf4j.Logger;
"", import org.slf4j.LoggerFactory;
"class A {",
" private static final Logger FOO_BAR = LoggerFactory.getLogger(A.class);", class A {
"", private static final Logger FOO_BAR = LoggerFactory.getLogger(A.class);
" abstract static class DynamicLogger {",
" private final Logger fooBar = LoggerFactory.getLogger(getClass());", abstract static class DynamicLogger {
" }", private final Logger fooBar = LoggerFactory.getLogger(getClass());
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,75 +11,77 @@ final class SpringMvcAnnotationTest {
CompilationTestHelper.newInstance(SpringMvcAnnotation.class, getClass()) CompilationTestHelper.newInstance(SpringMvcAnnotation.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static org.springframework.web.bind.annotation.RequestMethod.DELETE;", """
"import static org.springframework.web.bind.annotation.RequestMethod.GET;", import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
"import static org.springframework.web.bind.annotation.RequestMethod.HEAD;", import static org.springframework.web.bind.annotation.RequestMethod.GET;
"import static org.springframework.web.bind.annotation.RequestMethod.PATCH;", import static org.springframework.web.bind.annotation.RequestMethod.HEAD;
"import static org.springframework.web.bind.annotation.RequestMethod.POST;", import static org.springframework.web.bind.annotation.RequestMethod.PATCH;
"import static org.springframework.web.bind.annotation.RequestMethod.PUT;", import static org.springframework.web.bind.annotation.RequestMethod.POST;
"", import static org.springframework.web.bind.annotation.RequestMethod.PUT;
"import org.springframework.web.bind.annotation.DeleteMapping;",
"import org.springframework.web.bind.annotation.GetMapping;", import org.springframework.web.bind.annotation.DeleteMapping;
"import org.springframework.web.bind.annotation.PatchMapping;", import org.springframework.web.bind.annotation.GetMapping;
"import org.springframework.web.bind.annotation.PostMapping;", import org.springframework.web.bind.annotation.PatchMapping;
"import org.springframework.web.bind.annotation.PutMapping;", import org.springframework.web.bind.annotation.PostMapping;
"import org.springframework.web.bind.annotation.RequestMapping;", import org.springframework.web.bind.annotation.PutMapping;
"import org.springframework.web.bind.annotation.RequestMethod;", import org.springframework.web.bind.annotation.RequestMapping;
"", import org.springframework.web.bind.annotation.RequestMethod;
"interface A {",
" @RequestMapping", interface A {
" A simple();", @RequestMapping
"", A simple();
" @RequestMapping(method = {})",
" A explicitDefault();", @RequestMapping(method = {})
"", A explicitDefault();
" // BUG: Diagnostic contains:",
" @RequestMapping(method = RequestMethod.GET)", // BUG: Diagnostic contains:
" A get();", @RequestMapping(method = RequestMethod.GET)
"", A get();
" // BUG: Diagnostic contains:",
" @RequestMapping(method = {RequestMethod.POST})", // BUG: Diagnostic contains:
" A post();", @RequestMapping(method = {RequestMethod.POST})
"", A post();
" // BUG: Diagnostic contains:",
" @RequestMapping(method = {PUT})", // BUG: Diagnostic contains:
" A put();", @RequestMapping(method = {PUT})
"", A put();
" // BUG: Diagnostic contains:",
" @RequestMapping(method = {DELETE})", // BUG: Diagnostic contains:
" A delete();", @RequestMapping(method = {DELETE})
"", A delete();
" // BUG: Diagnostic contains:",
" @RequestMapping(method = {PATCH})", // BUG: Diagnostic contains:
" A patch();", @RequestMapping(method = {PATCH})
"", A patch();
" @RequestMapping(method = HEAD)",
" A head();", @RequestMapping(method = HEAD)
"", A head();
" @RequestMapping(method = RequestMethod.OPTIONS)",
" A options();", @RequestMapping(method = RequestMethod.OPTIONS)
"", A options();
" @RequestMapping(method = {GET, POST})",
" A simpleMix();", @RequestMapping(method = {GET, POST})
"", A simpleMix();
" @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})",
" A verboseMix();", @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
"", A verboseMix();
" @DeleteMapping",
" A properDelete();", @DeleteMapping
"", A properDelete();
" @GetMapping",
" A properGet();", @GetMapping
"", A properGet();
" @PatchMapping",
" A properPatch();", @PatchMapping
"", A properPatch();
" @PostMapping",
" A properPost();", @PostMapping
"", A properPost();
" @PutMapping",
" A properPut();", @PutMapping
"}") A properPut();
}
""")
.doTest(); .doTest();
} }
@@ -88,66 +90,70 @@ final class SpringMvcAnnotationTest {
BugCheckerRefactoringTestHelper.newInstance(SpringMvcAnnotation.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(SpringMvcAnnotation.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static org.springframework.web.bind.annotation.RequestMethod.PATCH;", """
"import static org.springframework.web.bind.annotation.RequestMethod.POST;", import static org.springframework.web.bind.annotation.RequestMethod.PATCH;
"import static org.springframework.web.bind.annotation.RequestMethod.PUT;", import static org.springframework.web.bind.annotation.RequestMethod.POST;
"", import static org.springframework.web.bind.annotation.RequestMethod.PUT;
"import org.springframework.web.bind.annotation.RequestMapping;",
"import org.springframework.web.bind.annotation.RequestMethod;", import org.springframework.web.bind.annotation.RequestMapping;
"", import org.springframework.web.bind.annotation.RequestMethod;
"interface A {",
" @RequestMapping(method = RequestMethod.GET)", interface A {
" A simple();", @RequestMapping(method = RequestMethod.GET)
"", A simple();
" @RequestMapping(path = \"/foo/bar\", method = POST)",
" A prefixed();", @RequestMapping(path = "/foo/bar", method = POST)
"", A prefixed();
" @RequestMapping(",
" method = {RequestMethod.DELETE},", @RequestMapping(
" path = \"/foo/bar\")", method = {RequestMethod.DELETE},
" A suffixed();", path = "/foo/bar")
"", A suffixed();
" @RequestMapping(",
" path = \"/foo/bar\",", @RequestMapping(
" method = {PUT},", path = "/foo/bar",
" consumes = {\"a\", \"b\"})", method = {PUT},
" A surrounded();", consumes = {"a", "b"})
"", A surrounded();
" @RequestMapping(method = {PATCH})",
" A curly();", @RequestMapping(method = {PATCH})
"}") A curly();
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static org.springframework.web.bind.annotation.RequestMethod.PATCH;", """
"import static org.springframework.web.bind.annotation.RequestMethod.POST;", import static org.springframework.web.bind.annotation.RequestMethod.PATCH;
"import static org.springframework.web.bind.annotation.RequestMethod.PUT;", import static org.springframework.web.bind.annotation.RequestMethod.POST;
"", import static org.springframework.web.bind.annotation.RequestMethod.PUT;
"import org.springframework.web.bind.annotation.DeleteMapping;",
"import org.springframework.web.bind.annotation.GetMapping;", import org.springframework.web.bind.annotation.DeleteMapping;
"import org.springframework.web.bind.annotation.PatchMapping;", import org.springframework.web.bind.annotation.GetMapping;
"import org.springframework.web.bind.annotation.PostMapping;", import org.springframework.web.bind.annotation.PatchMapping;
"import org.springframework.web.bind.annotation.PutMapping;", import org.springframework.web.bind.annotation.PostMapping;
"import org.springframework.web.bind.annotation.RequestMapping;", import org.springframework.web.bind.annotation.PutMapping;
"import org.springframework.web.bind.annotation.RequestMethod;", import org.springframework.web.bind.annotation.RequestMapping;
"", import org.springframework.web.bind.annotation.RequestMethod;
"interface A {",
" @GetMapping()", interface A {
" A simple();", @GetMapping()
"", A simple();
" @PostMapping(path = \"/foo/bar\")",
" A prefixed();", @PostMapping(path = "/foo/bar")
"", A prefixed();
" @DeleteMapping(path = \"/foo/bar\")",
" A suffixed();", @DeleteMapping(path = "/foo/bar")
"", A suffixed();
" @PutMapping(",
" path = \"/foo/bar\",", @PutMapping(
" consumes = {\"a\", \"b\"})", path = "/foo/bar",
" A surrounded();", consumes = {"a", "b"})
"", A surrounded();
" @PatchMapping()",
" A curly();", @PatchMapping()
"}") A curly();
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -34,93 +34,95 @@ final class StaticImportTest {
CompilationTestHelper.newInstance(StaticImport.class, getClass()) CompilationTestHelper.newInstance(StaticImport.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static com.google.common.collect.ImmutableMap.toImmutableMap;", """
"import static com.google.common.collect.ImmutableSet.toImmutableSet;", import static com.google.common.collect.ImmutableMap.toImmutableMap;
"import static java.nio.charset.StandardCharsets.UTF_8;", import static com.google.common.collect.ImmutableSet.toImmutableSet;
"import static java.util.function.Predicate.not;", import static java.nio.charset.StandardCharsets.UTF_8;
"import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;", import static java.util.function.Predicate.not;
"", import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
"import com.fasterxml.jackson.annotation.JsonCreator;",
"import com.google.common.base.Predicates;", import com.fasterxml.jackson.annotation.JsonCreator;
"import com.google.common.collect.ImmutableMap;", import com.google.common.base.Predicates;
"import com.google.common.collect.ImmutableMultiset;", import com.google.common.collect.ImmutableMap;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableMultiset;
"import com.google.errorprone.refaster.ImportPolicy;", import com.google.common.collect.ImmutableSet;
"import com.google.errorprone.refaster.annotation.UseImportPolicy;", import com.google.errorprone.refaster.ImportPolicy;
"import com.mongodb.client.model.Filters;", import com.google.errorprone.refaster.annotation.UseImportPolicy;
"import java.nio.charset.StandardCharsets;", import com.mongodb.client.model.Filters;
"import java.time.ZoneOffset;", import java.nio.charset.StandardCharsets;
"import java.util.Optional;", import java.time.ZoneOffset;
"import java.util.UUID;", import java.util.Optional;
"import java.util.function.Predicate;", import java.util.UUID;
"import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;", import java.util.function.Predicate;
"import org.springframework.http.MediaType;", import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
"", import org.springframework.http.MediaType;
"class A {",
" void m() {", class A {
" // BUG: Diagnostic contains:", void m() {
" ImmutableMap.toImmutableMap(v -> v, v -> v);", // BUG: Diagnostic contains:
" ImmutableMap.<String, String, String>toImmutableMap(v -> v, v -> v);", ImmutableMap.toImmutableMap(v -> v, v -> v);
" toImmutableMap(v -> v, v -> v);", ImmutableMap.<String, String, String>toImmutableMap(v -> v, v -> v);
"", toImmutableMap(v -> v, v -> v);
" // BUG: Diagnostic contains:",
" ImmutableSet.toImmutableSet();", // BUG: Diagnostic contains:
" ImmutableSet.<String>toImmutableSet();", ImmutableSet.toImmutableSet();
" toImmutableSet();", ImmutableSet.<String>toImmutableSet();
"", toImmutableSet();
" // Not flagged because we define `#toImmutableMultiset` below.",
" ImmutableMultiset.toImmutableMultiset();", // Not flagged because we define `#toImmutableMultiset` below.
" ImmutableMultiset.<String>toImmutableMultiset();", ImmutableMultiset.toImmutableMultiset();
" toImmutableMultiset();", ImmutableMultiset.<String>toImmutableMultiset();
"", toImmutableMultiset();
" // BUG: Diagnostic contains:",
" Predicate.not(null);", // BUG: Diagnostic contains:
" not(null);", Predicate.not(null);
"", not(null);
" // BUG: Diagnostic contains:",
" Predicates.alwaysTrue();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Predicates.alwaysTrue();
" Predicates.alwaysFalse();", // BUG: Diagnostic contains:
" // Not flagged because of `java.util.function.Predicate.not` import.", Predicates.alwaysFalse();
" Predicates.not(null);", // Not flagged because of `java.util.function.Predicate.not` import.
"", Predicates.not(null);
" // BUG: Diagnostic contains:",
" UUID uuid = UUID.randomUUID();", // BUG: Diagnostic contains:
"", UUID uuid = UUID.randomUUID();
" // BUG: Diagnostic contains:",
" Object o1 = StandardCharsets.UTF_8;", // BUG: Diagnostic contains:
" Object o2 = UTF_8;", Object o1 = StandardCharsets.UTF_8;
"", Object o2 = UTF_8;
" // BUG: Diagnostic contains:",
" Object e1 = WebEnvironment.RANDOM_PORT;", // BUG: Diagnostic contains:
" Object e2 = RANDOM_PORT;", Object e1 = WebEnvironment.RANDOM_PORT;
"", Object e2 = RANDOM_PORT;
" // Not flagged because `MediaType.ALL` is exempted.",
" MediaType t1 = MediaType.ALL;", // Not flagged because `MediaType.ALL` is exempted.
" // BUG: Diagnostic contains:", MediaType t1 = MediaType.ALL;
" MediaType t2 = MediaType.APPLICATION_JSON;", // BUG: Diagnostic contains:
"", MediaType t2 = MediaType.APPLICATION_JSON;
" // BUG: Diagnostic contains:",
" Filters.empty();", // BUG: Diagnostic contains:
" Optional.empty();", Filters.empty();
"", Optional.empty();
" // BUG: Diagnostic contains:",
" ZoneOffset zo1 = ZoneOffset.UTC;", // BUG: Diagnostic contains:
" ZoneOffset zo2 = ZoneOffset.MIN;", ZoneOffset zo1 = ZoneOffset.UTC;
" }", ZoneOffset zo2 = ZoneOffset.MIN;
"", }
" // BUG: Diagnostic contains:",
" @JsonCreator(mode = JsonCreator.Mode.DELEGATING)", // BUG: Diagnostic contains:
" private static A jsonCreator(int a) {", @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
" return new A();", private static A jsonCreator(int a) {
" }", return new A();
"", }
" // BUG: Diagnostic contains:",
" @UseImportPolicy(ImportPolicy.IMPORT_TOP_LEVEL)", // BUG: Diagnostic contains:
" void refasterAfterTemplate() {}", @UseImportPolicy(ImportPolicy.IMPORT_TOP_LEVEL)
"", void refasterAfterTemplate() {}
" void toImmutableMultiset() {}",
"}") void toImmutableMultiset() {}
}
""")
.doTest(); .doTest();
} }
@@ -129,167 +131,171 @@ final class StaticImportTest {
BugCheckerRefactoringTestHelper.newInstance(StaticImport.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(StaticImport.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static java.util.function.Predicate.not;", """
"", import static java.util.function.Predicate.not;
"import com.fasterxml.jackson.annotation.JsonCreator;",
"import com.google.common.base.Predicates;", import com.fasterxml.jackson.annotation.JsonCreator;
"import com.google.common.collect.ImmutableMap;", import com.google.common.base.Predicates;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableMap;
"import com.google.errorprone.BugPattern;", import com.google.common.collect.ImmutableSet;
"import com.google.errorprone.BugPattern.SeverityLevel;", import com.google.errorprone.BugPattern;
"import java.nio.charset.StandardCharsets;", import com.google.errorprone.BugPattern.SeverityLevel;
"import java.util.ArrayList;", import java.nio.charset.StandardCharsets;
"import java.util.Collections;", import java.util.ArrayList;
"import java.util.Objects;", import java.util.Collections;
"import java.util.regex.Pattern;", import java.util.Objects;
"import org.junit.jupiter.params.provider.Arguments;", import java.util.regex.Pattern;
"import org.springframework.boot.test.context.SpringBootTest;", import org.junit.jupiter.params.provider.Arguments;
"import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;", import org.springframework.boot.test.context.SpringBootTest;
"import org.springframework.format.annotation.DateTimeFormat;", import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
"import org.springframework.format.annotation.DateTimeFormat.ISO;", import org.springframework.format.annotation.DateTimeFormat;
"import org.springframework.http.MediaType;", import org.springframework.format.annotation.DateTimeFormat.ISO;
"", import org.springframework.http.MediaType;
"class A {",
" void m1() {", class A {
" ImmutableMap.toImmutableMap(v -> v, v -> v);", void m1() {
" ImmutableMap.<String, String, String>toImmutableMap(v -> v, v -> v);", ImmutableMap.toImmutableMap(v -> v, v -> v);
"", ImmutableMap.<String, String, String>toImmutableMap(v -> v, v -> v);
" ImmutableSet.toImmutableSet();",
" ImmutableSet.<String>toImmutableSet();", ImmutableSet.toImmutableSet();
"", ImmutableSet.<String>toImmutableSet();
" Collections.disjoint(ImmutableSet.of(), ImmutableSet.of());",
" Collections.reverse(new ArrayList<>());", Collections.disjoint(ImmutableSet.of(), ImmutableSet.of());
"", Collections.reverse(new ArrayList<>());
" Predicates.not(null);",
" not(null);", Predicates.not(null);
"", not(null);
" Arguments.arguments(\"foo\");",
"", Arguments.arguments("foo");
" Objects.requireNonNull(\"bar\");",
"", Objects.requireNonNull("bar");
" Object o = StandardCharsets.UTF_8;",
"", Object o = StandardCharsets.UTF_8;
" ImmutableSet.of(",
" MediaType.ALL,", ImmutableSet.of(
" MediaType.APPLICATION_XHTML_XML,", MediaType.ALL,
" MediaType.TEXT_HTML,", MediaType.APPLICATION_XHTML_XML,
" MediaType.valueOf(\"image/webp\"));", MediaType.TEXT_HTML,
"", MediaType.valueOf("image/webp"));
" Pattern.compile(\"\", Pattern.CASE_INSENSITIVE);",
" }", Pattern.compile("", Pattern.CASE_INSENSITIVE);
"", }
" void m2(",
" @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String date,", void m2(
" @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) String dateTime,", @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String date,
" @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) String time) {}", @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) String dateTime,
"", @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) String time) {}
" void m3(",
" @DateTimeFormat(iso = ISO.DATE) String date,", void m3(
" @DateTimeFormat(iso = ISO.DATE_TIME) String dateTime,", @DateTimeFormat(iso = ISO.DATE) String date,
" @DateTimeFormat(iso = ISO.TIME) String time) {}", @DateTimeFormat(iso = ISO.DATE_TIME) String dateTime,
"", @DateTimeFormat(iso = ISO.TIME) String time) {}
" @JsonCreator(mode = JsonCreator.Mode.DELEGATING)",
" private static A jsonCreator(int a) {", @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
" return new A();", private static A jsonCreator(int a) {
" }", return new A();
"", }
" @BugPattern(",
" summary = \"\",", @BugPattern(
" linkType = BugPattern.LinkType.NONE,", summary = "",
" severity = SeverityLevel.SUGGESTION,", linkType = BugPattern.LinkType.NONE,
" tags = BugPattern.StandardTags.SIMPLIFICATION)", severity = SeverityLevel.SUGGESTION,
" static final class TestBugPattern {}", tags = BugPattern.StandardTags.SIMPLIFICATION)
"", static final class TestBugPattern {}
" @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)",
" final class Test {}", @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
"}") final class Test {}
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static com.fasterxml.jackson.annotation.JsonCreator.Mode.DELEGATING;", """
"import static com.google.common.collect.ImmutableMap.toImmutableMap;", import static com.fasterxml.jackson.annotation.JsonCreator.Mode.DELEGATING;
"import static com.google.common.collect.ImmutableSet.toImmutableSet;", import static com.google.common.collect.ImmutableMap.toImmutableMap;
"import static com.google.errorprone.BugPattern.LinkType.NONE;", import static com.google.common.collect.ImmutableSet.toImmutableSet;
"import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;", import static com.google.errorprone.BugPattern.LinkType.NONE;
"import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;", import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
"import static java.nio.charset.StandardCharsets.UTF_8;", import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
"import static java.util.Collections.disjoint;", import static java.nio.charset.StandardCharsets.UTF_8;
"import static java.util.Collections.reverse;", import static java.util.Collections.disjoint;
"import static java.util.Objects.requireNonNull;", import static java.util.Collections.reverse;
"import static java.util.function.Predicate.not;", import static java.util.Objects.requireNonNull;
"import static java.util.regex.Pattern.CASE_INSENSITIVE;", import static java.util.function.Predicate.not;
"import static org.junit.jupiter.params.provider.Arguments.arguments;", import static java.util.regex.Pattern.CASE_INSENSITIVE;
"import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;", import static org.junit.jupiter.params.provider.Arguments.arguments;
"import static org.springframework.format.annotation.DateTimeFormat.ISO.DATE;", import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
"import static org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME;", import static org.springframework.format.annotation.DateTimeFormat.ISO.DATE;
"import static org.springframework.format.annotation.DateTimeFormat.ISO.TIME;", import static org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME;
"import static org.springframework.http.MediaType.APPLICATION_XHTML_XML;", import static org.springframework.format.annotation.DateTimeFormat.ISO.TIME;
"import static org.springframework.http.MediaType.TEXT_HTML;", import static org.springframework.http.MediaType.APPLICATION_XHTML_XML;
"", import static org.springframework.http.MediaType.TEXT_HTML;
"import com.fasterxml.jackson.annotation.JsonCreator;",
"import com.google.common.base.Predicates;", import com.fasterxml.jackson.annotation.JsonCreator;
"import com.google.common.collect.ImmutableMap;", import com.google.common.base.Predicates;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableMap;
"import com.google.errorprone.BugPattern;", import com.google.common.collect.ImmutableSet;
"import com.google.errorprone.BugPattern.SeverityLevel;", import com.google.errorprone.BugPattern;
"import java.nio.charset.StandardCharsets;", import com.google.errorprone.BugPattern.SeverityLevel;
"import java.util.ArrayList;", import java.nio.charset.StandardCharsets;
"import java.util.Collections;", import java.util.ArrayList;
"import java.util.Objects;", import java.util.Collections;
"import java.util.regex.Pattern;", import java.util.Objects;
"import org.junit.jupiter.params.provider.Arguments;", import java.util.regex.Pattern;
"import org.springframework.boot.test.context.SpringBootTest;", import org.junit.jupiter.params.provider.Arguments;
"import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;", import org.springframework.boot.test.context.SpringBootTest;
"import org.springframework.format.annotation.DateTimeFormat;", import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
"import org.springframework.format.annotation.DateTimeFormat.ISO;", import org.springframework.format.annotation.DateTimeFormat;
"import org.springframework.http.MediaType;", import org.springframework.format.annotation.DateTimeFormat.ISO;
"", import org.springframework.http.MediaType;
"class A {",
" void m1() {", class A {
" toImmutableMap(v -> v, v -> v);", void m1() {
" ImmutableMap.<String, String, String>toImmutableMap(v -> v, v -> v);", toImmutableMap(v -> v, v -> v);
"", ImmutableMap.<String, String, String>toImmutableMap(v -> v, v -> v);
" toImmutableSet();",
" ImmutableSet.<String>toImmutableSet();", toImmutableSet();
"", ImmutableSet.<String>toImmutableSet();
" disjoint(ImmutableSet.of(), ImmutableSet.of());",
" reverse(new ArrayList<>());", disjoint(ImmutableSet.of(), ImmutableSet.of());
"", reverse(new ArrayList<>());
" Predicates.not(null);",
" not(null);", Predicates.not(null);
"", not(null);
" arguments(\"foo\");",
"", arguments("foo");
" requireNonNull(\"bar\");",
"", requireNonNull("bar");
" Object o = UTF_8;",
"", Object o = UTF_8;
" ImmutableSet.of(",
" MediaType.ALL, APPLICATION_XHTML_XML, TEXT_HTML, MediaType.valueOf(\"image/webp\"));", ImmutableSet.of(
"", MediaType.ALL, APPLICATION_XHTML_XML, TEXT_HTML, MediaType.valueOf("image/webp"));
" Pattern.compile(\"\", CASE_INSENSITIVE);",
" }", Pattern.compile("", CASE_INSENSITIVE);
"", }
" void m2(",
" @DateTimeFormat(iso = DATE) String date,", void m2(
" @DateTimeFormat(iso = DATE_TIME) String dateTime,", @DateTimeFormat(iso = DATE) String date,
" @DateTimeFormat(iso = TIME) String time) {}", @DateTimeFormat(iso = DATE_TIME) String dateTime,
"", @DateTimeFormat(iso = TIME) String time) {}
" void m3(",
" @DateTimeFormat(iso = DATE) String date,", void m3(
" @DateTimeFormat(iso = DATE_TIME) String dateTime,", @DateTimeFormat(iso = DATE) String date,
" @DateTimeFormat(iso = TIME) String time) {}", @DateTimeFormat(iso = DATE_TIME) String dateTime,
"", @DateTimeFormat(iso = TIME) String time) {}
" @JsonCreator(mode = DELEGATING)",
" private static A jsonCreator(int a) {", @JsonCreator(mode = DELEGATING)
" return new A();", private static A jsonCreator(int a) {
" }", return new A();
"", }
" @BugPattern(summary = \"\", linkType = NONE, severity = SUGGESTION, tags = SIMPLIFICATION)",
" static final class TestBugPattern {}", @BugPattern(summary = "", linkType = NONE, severity = SUGGESTION, tags = SIMPLIFICATION)
"", static final class TestBugPattern {}
" @SpringBootTest(webEnvironment = RANDOM_PORT)",
" final class Test {}", @SpringBootTest(webEnvironment = RANDOM_PORT)
"}") final class Test {}
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -14,43 +14,45 @@ final class StringJoinTest {
.expectErrorMessage("join", m -> m.contains("Prefer `String#join` over `String#format`")) .expectErrorMessage("join", m -> m.contains("Prefer `String#join` over `String#format`"))
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.Formattable;", """
"import java.util.Locale;", import java.util.Formattable;
"", import java.util.Locale;
"class A {",
" void m() {", class A {
" String.join(\"-\", getClass().getName());", void m() {
" String.format(getClass().getName(), getClass().getName());", String.join("-", getClass().getName());
" String.format(Locale.ROOT, \"%s\", getClass().getName());", String.format(getClass().getName(), getClass().getName());
" String.format(\"%20s\", getClass().getName());", String.format(Locale.ROOT, "%s", getClass().getName());
" // BUG: Diagnostic matches: valueOf", String.format("%20s", getClass().getName());
" String.format(\"%s\", getClass().getName());", // BUG: Diagnostic matches: valueOf
" // BUG: Diagnostic matches: valueOf", String.format("%s", getClass().getName());
" String.format(\"%s\", hashCode());", // BUG: Diagnostic matches: valueOf
" String.format(\"%s\", (Formattable) null);", String.format("%s", hashCode());
" String.format(\"-%s\", getClass().getName());", String.format("%s", (Formattable) null);
" String.format(\"%s-\", getClass().getName());", String.format("-%s", getClass().getName());
" String.format(\"-%s-\", getClass().getName());", String.format("%s-", getClass().getName());
" // BUG: Diagnostic matches: join", String.format("-%s-", getClass().getName());
" String.format(\"%s%s\", getClass().getName(), getClass().getName());", // BUG: Diagnostic matches: join
" // BUG: Diagnostic matches: join", String.format("%s%s", getClass().getName(), getClass().getName());
" String.format(\"%s%s\", getClass().getName(), hashCode());", // BUG: Diagnostic matches: join
" // BUG: Diagnostic matches: join", String.format("%s%s", getClass().getName(), hashCode());
" String.format(\"%s%s\", hashCode(), getClass().getName());", // BUG: Diagnostic matches: join
" String.format(\"%s%s\", getClass().getName(), (Formattable) null);", String.format("%s%s", hashCode(), getClass().getName());
" String.format(\"%s%s\", (Formattable) null, getClass().getName());", String.format("%s%s", getClass().getName(), (Formattable) null);
" String.format(\"%s%s\", getClass().getName());", String.format("%s%s", (Formattable) null, getClass().getName());
" // BUG: Diagnostic matches: join", String.format("%s%s", getClass().getName());
" String.format(\"%s-%s\", getClass().getName(), getClass().getName());", // BUG: Diagnostic matches: join
" // BUG: Diagnostic matches: join", String.format("%s-%s", getClass().getName(), getClass().getName());
" String.format(\"%saa%s\", getClass().getName(), getClass().getName());", // BUG: Diagnostic matches: join
" String.format(\"%s%%%s\", getClass().getName(), getClass().getName());", String.format("%saa%s", getClass().getName(), getClass().getName());
" // BUG: Diagnostic matches: join", String.format("%s%%%s", getClass().getName(), getClass().getName());
" String.format(\"%s_%s_%s\", getClass().getName(), getClass().getName(), getClass().getName());", // BUG: Diagnostic matches: join
" String.format(\"%s_%s_%s\", getClass().getName(), getClass().getName());", String.format("%s_%s_%s", getClass().getName(), getClass().getName(), getClass().getName());
" String.format(\"%s_%s-%s\", getClass().getName(), getClass().getName(), getClass().getName());", String.format("%s_%s_%s", getClass().getName(), getClass().getName());
" }", String.format("%s_%s-%s", getClass().getName(), getClass().getName(), getClass().getName());
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -59,32 +61,36 @@ final class StringJoinTest {
BugCheckerRefactoringTestHelper.newInstance(StringJoin.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(StringJoin.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" String.format(\"%s\", getClass().getName());", void m() {
" String.format(\"%s%s\", getClass().getName(), getClass().getName());", String.format("%s", getClass().getName());
" String.format(\"%s%s\", getClass().getName(), hashCode());", String.format("%s%s", getClass().getName(), getClass().getName());
" String.format(\"%s%s\", hashCode(), getClass().getName());", String.format("%s%s", getClass().getName(), hashCode());
" String.format(\"%s-%s\", getClass().getName(), getClass().getName());", String.format("%s%s", hashCode(), getClass().getName());
" String.format(\"%saa%s\", getClass().getName(), getClass().getName());", String.format("%s-%s", getClass().getName(), getClass().getName());
" String.format(\"%s\\\"%s\", getClass().getName(), getClass().getName());", String.format("%saa%s", getClass().getName(), getClass().getName());
" String.format(\"%s_%s_%s\", getClass().getName(), getClass().getName(), getClass().getName());", String.format("%s\\"%s", getClass().getName(), getClass().getName());
" }", String.format("%s_%s_%s", getClass().getName(), getClass().getName(), getClass().getName());
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" String.valueOf(getClass().getName());", void m() {
" String.join(\"\", getClass().getName(), getClass().getName());", String.valueOf(getClass().getName());
" String.join(\"\", getClass().getName(), String.valueOf(hashCode()));", String.join("", getClass().getName(), getClass().getName());
" String.join(\"\", String.valueOf(hashCode()), getClass().getName());", String.join("", getClass().getName(), String.valueOf(hashCode()));
" String.join(\"-\", getClass().getName(), getClass().getName());", String.join("", String.valueOf(hashCode()), getClass().getName());
" String.join(\"aa\", getClass().getName(), getClass().getName());", String.join("-", getClass().getName(), getClass().getName());
" String.join(\"\\\"\", getClass().getName(), getClass().getName());", String.join("aa", getClass().getName(), getClass().getName());
" String.join(\"_\", getClass().getName(), getClass().getName(), getClass().getName());", String.join("\\"", getClass().getName(), getClass().getName());
" }", String.join("_", getClass().getName(), getClass().getName(), getClass().getName());
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -9,110 +9,112 @@ final class TimeZoneUsageTest {
CompilationTestHelper.newInstance(TimeZoneUsage.class, getClass()) CompilationTestHelper.newInstance(TimeZoneUsage.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static java.time.ZoneOffset.UTC;", """
"", import static java.time.ZoneOffset.UTC;
"import java.time.Clock;",
"import java.time.Duration;", import java.time.Clock;
"import java.time.Instant;", import java.time.Duration;
"import java.time.LocalDate;", import java.time.Instant;
"import java.time.LocalDateTime;", import java.time.LocalDate;
"import java.time.LocalTime;", import java.time.LocalDateTime;
"import java.time.OffsetDateTime;", import java.time.LocalTime;
"import java.time.OffsetTime;", import java.time.OffsetDateTime;
"import java.time.ZoneId;", import java.time.OffsetTime;
"import java.time.ZonedDateTime;", import java.time.ZoneId;
"", import java.time.ZonedDateTime;
"class A {",
" void m() {", class A {
" Clock clock = Clock.fixed(Instant.EPOCH, UTC);", void m() {
" clock.instant();", Clock clock = Clock.fixed(Instant.EPOCH, UTC);
" clock.millis();", clock.instant();
" Clock.offset(clock, Duration.ZERO);", clock.millis();
" Clock.tick(clock, Duration.ZERO);", Clock.offset(clock, Duration.ZERO);
"", Clock.tick(clock, Duration.ZERO);
" // BUG: Diagnostic contains:",
" Clock.systemUTC();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Clock.systemUTC();
" Clock.systemDefaultZone();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Clock.systemDefaultZone();
" Clock.system(UTC);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Clock.system(UTC);
" Clock.tickMillis(UTC);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Clock.tickMillis(UTC);
" Clock.tickMinutes(UTC);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Clock.tickMinutes(UTC);
" Clock.tickSeconds(UTC);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Clock.tickSeconds(UTC);
" clock.getZone();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", clock.getZone();
" clock.withZone(UTC);", // BUG: Diagnostic contains:
"", clock.withZone(UTC);
" // BUG: Diagnostic contains:",
" Instant.now();", // BUG: Diagnostic contains:
" // This is equivalent to `clock.instant()`, which is fine.", Instant.now();
" Instant.now(clock);", // This is equivalent to `clock.instant()`, which is fine.
"", Instant.now(clock);
" // BUG: Diagnostic contains:",
" LocalDate.now();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LocalDate.now();
" LocalDate.now(clock);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LocalDate.now(clock);
" LocalDate.now(UTC);", // BUG: Diagnostic contains:
"", LocalDate.now(UTC);
" // BUG: Diagnostic contains:",
" LocalDateTime.now();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LocalDateTime.now();
" LocalDateTime.now(clock);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LocalDateTime.now(clock);
" LocalDateTime.now(UTC);", // BUG: Diagnostic contains:
"", LocalDateTime.now(UTC);
" // BUG: Diagnostic contains:",
" LocalTime.now();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LocalTime.now();
" LocalTime.now(clock);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", LocalTime.now(clock);
" LocalTime.now(UTC);", // BUG: Diagnostic contains:
"", LocalTime.now(UTC);
" // BUG: Diagnostic contains:",
" OffsetDateTime.now();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", OffsetDateTime.now();
" OffsetDateTime.now(clock);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", OffsetDateTime.now(clock);
" OffsetDateTime.now(UTC);", // BUG: Diagnostic contains:
"", OffsetDateTime.now(UTC);
" // BUG: Diagnostic contains:",
" OffsetTime.now();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", OffsetTime.now();
" OffsetTime.now(clock);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", OffsetTime.now(clock);
" OffsetTime.now(UTC);", // BUG: Diagnostic contains:
"", OffsetTime.now(UTC);
" // BUG: Diagnostic contains:",
" ZonedDateTime.now();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ZonedDateTime.now();
" ZonedDateTime.now(clock);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ZonedDateTime.now(clock);
" ZonedDateTime.now(UTC);", // BUG: Diagnostic contains:
" }", ZonedDateTime.now(UTC);
"", }
" abstract class ForwardingClock extends Clock {",
" private final Clock clock;", abstract class ForwardingClock extends Clock {
"", private final Clock clock;
" ForwardingClock(Clock clock) {",
" this.clock = clock;", ForwardingClock(Clock clock) {
" }", this.clock = clock;
"", }
" @Override",
" public ZoneId getZone() {", @Override
" return clock.getZone();", public ZoneId getZone() {
" }", return clock.getZone();
"", }
" @Override",
" public Clock withZone(ZoneId zone) {", @Override
" return clock.withZone(zone);", public Clock withZone(ZoneId zone) {
" }", return clock.withZone(zone);
" }", }
"}") }
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -11,308 +11,310 @@ final class MethodReferenceUsageTest {
CompilationTestHelper.newInstance(MethodReferenceUsage.class, getClass()) CompilationTestHelper.newInstance(MethodReferenceUsage.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.Streams;", """
"import java.util.HashMap;", import com.google.common.collect.Streams;
"import java.util.Map;", import java.util.HashMap;
"import java.util.function.IntConsumer;", import java.util.Map;
"import java.util.function.IntFunction;", import java.util.function.IntConsumer;
"import java.util.stream.Stream;", import java.util.function.IntFunction;
"", import java.util.stream.Stream;
"class A {",
" private final Stream<Integer> s = Stream.of(1);", class A {
" private final Map<Integer, Integer> m = new HashMap<>();", private final Stream<Integer> s = Stream.of(1);
" private final Runnable thrower =", private final Map<Integer, Integer> m = new HashMap<>();
" () -> {", private final Runnable thrower =
" throw new RuntimeException();", () -> {
" };", throw new RuntimeException();
"", };
" void unaryExternalStaticFunctionCalls() {",
" s.forEach(String::valueOf);", void unaryExternalStaticFunctionCalls() {
" // BUG: Diagnostic contains:", s.forEach(String::valueOf);
" s.forEach(v -> String.valueOf(v));", // BUG: Diagnostic contains:
" s.forEach(", s.forEach(v -> String.valueOf(v));
" // BUG: Diagnostic contains:", s.forEach(
" (v) -> {", // BUG: Diagnostic contains:
" String.valueOf(v);", (v) -> {
" });", String.valueOf(v);
" s.forEach(", });
" // BUG: Diagnostic contains:", s.forEach(
" (Integer v) -> {", // BUG: Diagnostic contains:
" {", (Integer v) -> {
" String.valueOf(v);", {
" }", String.valueOf(v);
" });", }
" s.forEach(", });
" v -> {", s.forEach(
" String.valueOf(v);", v -> {
" String.valueOf(v);", String.valueOf(v);
" });", String.valueOf(v);
"", });
" s.map(String::valueOf);",
" // BUG: Diagnostic contains:", s.map(String::valueOf);
" s.map(v -> String.valueOf(v));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", s.map(v -> String.valueOf(v));
" s.map((v) -> (String.valueOf(v)));", // BUG: Diagnostic contains:
" s.map(", s.map((v) -> (String.valueOf(v)));
" // BUG: Diagnostic contains:", s.map(
" (Integer v) -> {", // BUG: Diagnostic contains:
" return String.valueOf(v);", (Integer v) -> {
" });", return String.valueOf(v);
" s.map(", });
" // BUG: Diagnostic contains:", s.map(
" (final Integer v) -> {", // BUG: Diagnostic contains:
" return (String.valueOf(v));", (final Integer v) -> {
" });", return (String.valueOf(v));
" s.map(", });
" v -> {", s.map(
" String.valueOf(v);", v -> {
" return String.valueOf(v);", String.valueOf(v);
" });", return String.valueOf(v);
"", });
" s.findFirst().orElseGet(() -> Integer.valueOf(\"0\"));",
" m.forEach((k, v) -> String.valueOf(v));", s.findFirst().orElseGet(() -> Integer.valueOf("0"));
" m.forEach((k, v) -> String.valueOf(k));", m.forEach((k, v) -> String.valueOf(v));
" }", m.forEach((k, v) -> String.valueOf(k));
"", }
" void binaryExternalInstanceFunctionCalls() {",
" m.forEach(m::put);", void binaryExternalInstanceFunctionCalls() {
" // BUG: Diagnostic contains:", m.forEach(m::put);
" m.forEach((k, v) -> m.put(k, v));", // BUG: Diagnostic contains:
" m.forEach((k, v) -> m.put(v, k));", m.forEach((k, v) -> m.put(k, v));
" m.forEach(", m.forEach((k, v) -> m.put(v, k));
" // BUG: Diagnostic contains:", m.forEach(
" (Integer k, Integer v) -> {", // BUG: Diagnostic contains:
" m.put(k, v);", (Integer k, Integer v) -> {
" });", m.put(k, v);
" m.forEach(", });
" (k, v) -> {", m.forEach(
" m.put(k, k);", (k, v) -> {
" });", m.put(k, k);
" m.forEach(", });
" // BUG: Diagnostic contains:", m.forEach(
" (final Integer k, final Integer v) -> {", // BUG: Diagnostic contains:
" {", (final Integer k, final Integer v) -> {
" m.put(k, v);", {
" }", m.put(k, v);
" });", }
" m.forEach(", });
" (k, v) -> {", m.forEach(
" {", (k, v) -> {
" m.put(v, v);", {
" }", m.put(v, v);
" });", }
" m.forEach((k, v) -> new HashMap<Integer, Integer>().put(k, v));", });
" m.forEach(", m.forEach((k, v) -> new HashMap<Integer, Integer>().put(k, v));
" (k, v) -> {", m.forEach(
" m.put(k, v);", (k, v) -> {
" m.put(k, v);", m.put(k, v);
" });", m.put(k, v);
"", });
" Streams.zip(s, s, m::put);",
" // BUG: Diagnostic contains:", Streams.zip(s, s, m::put);
" Streams.zip(s, s, (a, b) -> m.put(a, b));", // BUG: Diagnostic contains:
" Streams.zip(s, s, (a, b) -> m.put(b, a));", Streams.zip(s, s, (a, b) -> m.put(a, b));
" // BUG: Diagnostic contains:", Streams.zip(s, s, (a, b) -> m.put(b, a));
" Streams.zip(s, s, (Integer a, Integer b) -> (m.put(a, b)));", // BUG: Diagnostic contains:
" Streams.zip(s, s, (a, b) -> (m.put(a, a)));", Streams.zip(s, s, (Integer a, Integer b) -> (m.put(a, b)));
" Streams.zip(", Streams.zip(s, s, (a, b) -> (m.put(a, a)));
" s,", Streams.zip(
" s,", s,
" // BUG: Diagnostic contains:", s,
" (final Integer a, final Integer b) -> {", // BUG: Diagnostic contains:
" return m.put(a, b);", (final Integer a, final Integer b) -> {
" });", return m.put(a, b);
" Streams.zip(", });
" s,", Streams.zip(
" s,", s,
" (a, b) -> {", s,
" return m.put(b, b);", (a, b) -> {
" });", return m.put(b, b);
" Streams.zip(", });
" s,", Streams.zip(
" s,", s,
" // BUG: Diagnostic contains:", s,
" (a, b) -> {", // BUG: Diagnostic contains:
" return (m.put(a, b));", (a, b) -> {
" });", return (m.put(a, b));
" Streams.zip(", });
" s,", Streams.zip(
" s,", s,
" (a, b) -> {", s,
" return (m.put(b, a));", (a, b) -> {
" });", return (m.put(b, a));
" Streams.zip(", });
" s,", Streams.zip(
" s,", s,
" (a, b) -> {", s,
" m.put(a, b);", (a, b) -> {
" return m.put(a, b);", m.put(a, b);
" });", return m.put(a, b);
" }", });
"", }
" void nullaryExternalInstanceFunctionCalls() {",
" s.map(Integer::doubleValue);", void nullaryExternalInstanceFunctionCalls() {
" // BUG: Diagnostic contains:", s.map(Integer::doubleValue);
" s.map(i -> i.doubleValue());", // BUG: Diagnostic contains:
" s.map(i -> i.toString());", s.map(i -> i.doubleValue());
" s.map(i -> s.toString());", s.map(i -> i.toString());
"", s.map(i -> s.toString());
" // BUG: Diagnostic contains:",
" Stream.of(int.class).filter(c -> c.isEnum());", // BUG: Diagnostic contains:
" Stream.of((Class<?>) int.class).filter(Class::isEnum);", Stream.of(int.class).filter(c -> c.isEnum());
" // BUG: Diagnostic contains:", Stream.of((Class<?>) int.class).filter(Class::isEnum);
" Stream.of((Class<?>) int.class).filter(c -> c.isEnum());", // BUG: Diagnostic contains:
" }", Stream.of((Class<?>) int.class).filter(c -> c.isEnum());
"", }
" void localFunctionCalls() {",
" s.forEach(v -> ivoid0());", void localFunctionCalls() {
" s.forEach(v -> iint0());", s.forEach(v -> ivoid0());
" s.forEach(v -> svoid0());", s.forEach(v -> iint0());
" s.forEach(v -> sint0());", s.forEach(v -> svoid0());
"", s.forEach(v -> sint0());
" s.forEach(this::ivoid1);",
" // BUG: Diagnostic contains:", s.forEach(this::ivoid1);
" s.forEach(v -> ivoid1(v));", // BUG: Diagnostic contains:
" s.forEach(", s.forEach(v -> ivoid1(v));
" // BUG: Diagnostic contains:", s.forEach(
" v -> {", // BUG: Diagnostic contains:
" ivoid1(v);", v -> {
" });", ivoid1(v);
" s.forEach(this::iint1);", });
" // BUG: Diagnostic contains:", s.forEach(this::iint1);
" s.forEach(v -> iint1(v));", // BUG: Diagnostic contains:
" s.forEach(", s.forEach(v -> iint1(v));
" // BUG: Diagnostic contains:", s.forEach(
" v -> {", // BUG: Diagnostic contains:
" iint1(v);", v -> {
" });", iint1(v);
"", });
" s.forEach(A::svoid1);",
" // BUG: Diagnostic contains:", s.forEach(A::svoid1);
" s.forEach(v -> svoid1(v));", // BUG: Diagnostic contains:
" s.forEach(", s.forEach(v -> svoid1(v));
" // BUG: Diagnostic contains:", s.forEach(
" v -> {", // BUG: Diagnostic contains:
" svoid1(v);", v -> {
" });", svoid1(v);
" s.forEach(A::sint1);", });
" // BUG: Diagnostic contains:", s.forEach(A::sint1);
" s.forEach(v -> sint1(v));", // BUG: Diagnostic contains:
" s.forEach(", s.forEach(v -> sint1(v));
" // BUG: Diagnostic contains:", s.forEach(
" v -> {", // BUG: Diagnostic contains:
" sint1(v);", v -> {
" });", sint1(v);
"", });
" s.forEach(v -> ivoid2(v, v));",
" s.forEach(v -> iint2(v, v));", s.forEach(v -> ivoid2(v, v));
" s.forEach(v -> svoid2(v, v));", s.forEach(v -> iint2(v, v));
" s.forEach(v -> sint2(v, v));", s.forEach(v -> svoid2(v, v));
"", s.forEach(v -> sint2(v, v));
" m.forEach((k, v) -> ivoid0());",
" m.forEach((k, v) -> iint0());", m.forEach((k, v) -> ivoid0());
" m.forEach((k, v) -> svoid0());", m.forEach((k, v) -> iint0());
" m.forEach((k, v) -> sint0());", m.forEach((k, v) -> svoid0());
"", m.forEach((k, v) -> sint0());
" m.forEach(this::ivoid2);",
" // BUG: Diagnostic contains:", m.forEach(this::ivoid2);
" m.forEach((k, v) -> ivoid2(k, v));", // BUG: Diagnostic contains:
" m.forEach(", m.forEach((k, v) -> ivoid2(k, v));
" // BUG: Diagnostic contains:", m.forEach(
" (k, v) -> {", // BUG: Diagnostic contains:
" ivoid2(k, v);", (k, v) -> {
" });", ivoid2(k, v);
" m.forEach(this::iint2);", });
" // BUG: Diagnostic contains:", m.forEach(this::iint2);
" m.forEach((k, v) -> iint2(k, v));", // BUG: Diagnostic contains:
" m.forEach(", m.forEach((k, v) -> iint2(k, v));
" // BUG: Diagnostic contains:", m.forEach(
" (k, v) -> {", // BUG: Diagnostic contains:
" iint2(k, v);", (k, v) -> {
" });", iint2(k, v);
"", });
" m.forEach(A::svoid2);",
" // BUG: Diagnostic contains:", m.forEach(A::svoid2);
" m.forEach((k, v) -> svoid2(k, v));", // BUG: Diagnostic contains:
" m.forEach(", m.forEach((k, v) -> svoid2(k, v));
" // BUG: Diagnostic contains:", m.forEach(
" (k, v) -> {", // BUG: Diagnostic contains:
" svoid2(k, v);", (k, v) -> {
" });", svoid2(k, v);
" m.forEach(A::sint2);", });
" // BUG: Diagnostic contains:", m.forEach(A::sint2);
" m.forEach((k, v) -> sint2(k, v));", // BUG: Diagnostic contains:
" m.forEach(", m.forEach((k, v) -> sint2(k, v));
" // BUG: Diagnostic contains:", m.forEach(
" (k, v) -> {", // BUG: Diagnostic contains:
" sint2(k, v);", (k, v) -> {
" });", sint2(k, v);
" }", });
"", }
" void functionCallsWhoseReplacementWouldBeAmbiguous() {",
" receiver(", void functionCallsWhoseReplacementWouldBeAmbiguous() {
" i -> {", receiver(
" Integer.toString(i);", i -> {
" });", Integer.toString(i);
" }", });
"", }
" void assortedOtherEdgeCases() {",
" s.forEach(v -> String.valueOf(v.toString()));", void assortedOtherEdgeCases() {
" TernaryOp o1 = (a, b, c) -> String.valueOf(a);", s.forEach(v -> String.valueOf(v.toString()));
" TernaryOp o2 = (a, b, c) -> String.valueOf(b);", TernaryOp o1 = (a, b, c) -> String.valueOf(a);
" TernaryOp o3 = (a, b, c) -> String.valueOf(c);", TernaryOp o2 = (a, b, c) -> String.valueOf(b);
" TernaryOp o4 = (a, b, c) -> c.concat(a);", TernaryOp o3 = (a, b, c) -> String.valueOf(c);
" TernaryOp o5 = (a, b, c) -> c.concat(b);", TernaryOp o4 = (a, b, c) -> c.concat(a);
" TernaryOp o6 = (a, b, c) -> a.concat(c);", TernaryOp o5 = (a, b, c) -> c.concat(b);
" TernaryOp o7 = (a, b, c) -> b.concat(c);", TernaryOp o6 = (a, b, c) -> a.concat(c);
" }", TernaryOp o7 = (a, b, c) -> b.concat(c);
"", }
" void receiver(IntFunction<?> op) {}",
"", void receiver(IntFunction<?> op) {}
" void receiver(IntConsumer op) {}",
"", void receiver(IntConsumer op) {}
" void ivoid0() {}",
"", void ivoid0() {}
" void ivoid1(int a) {}",
"", void ivoid1(int a) {}
" void ivoid2(int a, int b) {}",
"", void ivoid2(int a, int b) {}
" int iint0() {",
" return 0;", int iint0() {
" }", return 0;
"", }
" int iint1(int a) {",
" return 0;", int iint1(int a) {
" }", return 0;
"", }
" int iint2(int a, int b) {",
" return 0;", int iint2(int a, int b) {
" }", return 0;
"", }
" static void svoid0() {}",
"", static void svoid0() {}
" static void svoid1(int a) {}",
"", static void svoid1(int a) {}
" static void svoid2(int a, int b) {}",
"", static void svoid2(int a, int b) {}
" static void svoid3(int a, int b, int c) {}",
"", static void svoid3(int a, int b, int c) {}
" static int sint0() {",
" return 0;", static int sint0() {
" }", return 0;
"", }
" static int sint1(int a) {",
" return 0;", static int sint1(int a) {
" }", return 0;
"", }
" static int sint2(int a, int b) {",
" return 0;", static int sint2(int a, int b) {
" }", return 0;
"", }
" interface TernaryOp {",
" String collect(String a, String b, String c);", interface TernaryOp {
" }", String collect(String a, String b, String c);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -321,111 +323,115 @@ final class MethodReferenceUsageTest {
BugCheckerRefactoringTestHelper.newInstance(MethodReferenceUsage.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(MethodReferenceUsage.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import static java.util.Collections.emptyList;", """
"", import static java.util.Collections.emptyList;
"import java.util.Collections;",
"import java.util.List;", import java.util.Collections;
"import java.util.Map;", import java.util.List;
"import java.util.function.IntSupplier;", import java.util.Map;
"import java.util.function.Supplier;", import java.util.function.IntSupplier;
"import java.util.stream.Stream;", import java.util.function.Supplier;
"", import java.util.stream.Stream;
"class A {",
" static class B extends A {", class A {
" final A a = new B();", static class B extends A {
" final B b = new B();", final A a = new B();
"", final B b = new B();
" IntSupplier intSup;",
" Supplier<List<?>> listSup;", IntSupplier intSup;
"", Supplier<List<?>> listSup;
" void m() {",
" intSup = () -> a.iint0();", void m() {
" intSup = () -> b.iint0();", intSup = () -> a.iint0();
" intSup = () -> this.iint0();", intSup = () -> b.iint0();
" intSup = () -> super.iint0();", intSup = () -> this.iint0();
"", intSup = () -> super.iint0();
" intSup = () -> a.sint0();",
" intSup = () -> b.sint0();", intSup = () -> a.sint0();
" intSup = () -> this.sint0();", intSup = () -> b.sint0();
" intSup = () -> super.sint0();", intSup = () -> this.sint0();
" intSup = () -> A.sint0();", intSup = () -> super.sint0();
" intSup = () -> B.sint0();", intSup = () -> A.sint0();
"", intSup = () -> B.sint0();
" listSup = () -> Collections.emptyList();",
" listSup = () -> emptyList();", listSup = () -> Collections.emptyList();
"", listSup = () -> emptyList();
" Stream.of((Class<?>) int.class).filter(c -> c.isEnum());",
" Stream.of((Map<?, ?>) null).map(Map::keySet).map(s -> s.size());", Stream.of((Class<?>) int.class).filter(c -> c.isEnum());
" }", Stream.of((Map<?, ?>) null).map(Map::keySet).map(s -> s.size());
"", }
" @Override",
" int iint0() {", @Override
" return 0;", int iint0() {
" }", return 0;
" }", }
"", }
" int iint0() {",
" return 0;", int iint0() {
" }", return 0;
"", }
" static int sint0() {",
" return 0;", static int sint0() {
" }", return 0;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import static java.util.Collections.emptyList;", """
"", import static java.util.Collections.emptyList;
"import java.util.Collections;",
"import java.util.List;", import java.util.Collections;
"import java.util.Map;", import java.util.List;
"import java.util.Set;", import java.util.Map;
"import java.util.function.IntSupplier;", import java.util.Set;
"import java.util.function.Supplier;", import java.util.function.IntSupplier;
"import java.util.stream.Stream;", import java.util.function.Supplier;
"", import java.util.stream.Stream;
"class A {",
" static class B extends A {", class A {
" final A a = new B();", static class B extends A {
" final B b = new B();", final A a = new B();
"", final B b = new B();
" IntSupplier intSup;",
" Supplier<List<?>> listSup;", IntSupplier intSup;
"", Supplier<List<?>> listSup;
" void m() {",
" intSup = a::iint0;", void m() {
" intSup = b::iint0;", intSup = a::iint0;
" intSup = this::iint0;", intSup = b::iint0;
" intSup = super::iint0;", intSup = this::iint0;
"", intSup = super::iint0;
" intSup = () -> a.sint0();",
" intSup = () -> b.sint0();", intSup = () -> a.sint0();
" intSup = () -> this.sint0();", intSup = () -> b.sint0();
" intSup = () -> super.sint0();", intSup = () -> this.sint0();
" intSup = A::sint0;", intSup = () -> super.sint0();
" intSup = B::sint0;", intSup = A::sint0;
"", intSup = B::sint0;
" listSup = Collections::emptyList;",
" listSup = Collections::emptyList;", listSup = Collections::emptyList;
"", listSup = Collections::emptyList;
" Stream.of((Class<?>) int.class).filter(Class::isEnum);",
" Stream.of((Map<?, ?>) null).map(Map::keySet).map(Set::size);", Stream.of((Class<?>) int.class).filter(Class::isEnum);
" }", Stream.of((Map<?, ?>) null).map(Map::keySet).map(Set::size);
"", }
" @Override",
" int iint0() {", @Override
" return 0;", int iint0() {
" }", return 0;
" }", }
"", }
" int iint0() {",
" return 0;", int iint0() {
" }", return 0;
"", }
" static int sint0() {",
" return 0;", static int sint0() {
" }", return 0;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,44 +11,46 @@ final class AssociativeMethodInvocationTest {
CompilationTestHelper.newInstance(AssociativeMethodInvocation.class, getClass()) CompilationTestHelper.newInstance(AssociativeMethodInvocation.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"import com.google.errorprone.matchers.Matchers;", import com.google.common.collect.ImmutableList;
"import com.google.errorprone.refaster.Refaster;", import com.google.errorprone.matchers.Matchers;
"", import com.google.errorprone.refaster.Refaster;
"class A {",
" void m() {", class A {
" Matchers.allOf();", void m() {
" Matchers.anyOf();", Matchers.allOf();
" Refaster.anyOf();", Matchers.anyOf();
"", Refaster.anyOf();
" Matchers.allOf((t, s) -> true);",
" Matchers.anyOf((t, s) -> true);", Matchers.allOf((t, s) -> true);
" Refaster.anyOf(0);", Matchers.anyOf((t, s) -> true);
"", Refaster.anyOf(0);
" Matchers.allOf(Matchers.anyOf((t, s) -> true));",
" Matchers.anyOf(Matchers.allOf((t, s) -> true));", Matchers.allOf(Matchers.anyOf((t, s) -> true));
" Refaster.anyOf(Matchers.allOf((t, s) -> true));", Matchers.anyOf(Matchers.allOf((t, s) -> true));
"", Refaster.anyOf(Matchers.allOf((t, s) -> true));
" // BUG: Diagnostic contains:",
" Matchers.allOf(Matchers.allOf((t, s) -> true));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Matchers.allOf(Matchers.allOf((t, s) -> true));
" Matchers.anyOf(Matchers.anyOf((t, s) -> true));", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Matchers.anyOf(Matchers.anyOf((t, s) -> true));
" Refaster.anyOf(Refaster.anyOf(0));", // BUG: Diagnostic contains:
"", Refaster.anyOf(Refaster.anyOf(0));
" Matchers.allOf(Matchers.allOf(ImmutableList.of((t, s) -> true)));",
" Matchers.anyOf(Matchers.anyOf(ImmutableList.of((t, s) -> true)));", Matchers.allOf(Matchers.allOf(ImmutableList.of((t, s) -> true)));
"", Matchers.anyOf(Matchers.anyOf(ImmutableList.of((t, s) -> true)));
" // BUG: Diagnostic contains:",
" Matchers.allOf(", // BUG: Diagnostic contains:
" (t, s) -> true, Matchers.allOf((t, s) -> false, (t, s) -> true), (t, s) -> false);", Matchers.allOf(
" // BUG: Diagnostic contains:", (t, s) -> true, Matchers.allOf((t, s) -> false, (t, s) -> true), (t, s) -> false);
" Matchers.anyOf(", // BUG: Diagnostic contains:
" (t, s) -> true, Matchers.anyOf((t, s) -> false, (t, s) -> true), (t, s) -> false);", Matchers.anyOf(
" // BUG: Diagnostic contains:", (t, s) -> true, Matchers.anyOf((t, s) -> false, (t, s) -> true), (t, s) -> false);
" Refaster.anyOf(0, Refaster.anyOf(1, 2), 3);", // BUG: Diagnostic contains:
" }", Refaster.anyOf(0, Refaster.anyOf(1, 2), 3);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -57,54 +59,58 @@ final class AssociativeMethodInvocationTest {
BugCheckerRefactoringTestHelper.newInstance(AssociativeMethodInvocation.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(AssociativeMethodInvocation.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.errorprone.matchers.Matchers;", """
"import com.google.errorprone.refaster.Refaster;", import com.google.errorprone.matchers.Matchers;
"", import com.google.errorprone.refaster.Refaster;
"class A {",
" void m() {", class A {
" Matchers.allOf(Matchers.allOf());", void m() {
" Matchers.anyOf(Matchers.anyOf());", Matchers.allOf(Matchers.allOf());
" Refaster.anyOf(Refaster.anyOf());", Matchers.anyOf(Matchers.anyOf());
"", Refaster.anyOf(Refaster.anyOf());
" Matchers.allOf(Matchers.allOf((t, s) -> true));",
" Matchers.anyOf(Matchers.anyOf((t, s) -> true));", Matchers.allOf(Matchers.allOf((t, s) -> true));
" Refaster.anyOf(Refaster.anyOf(0));", Matchers.anyOf(Matchers.anyOf((t, s) -> true));
"", Refaster.anyOf(Refaster.anyOf(0));
" Matchers.allOf(",
" Matchers.anyOf(),", Matchers.allOf(
" Matchers.allOf((t, s) -> false, (t, s) -> true),", Matchers.anyOf(),
" Matchers.allOf(),", Matchers.allOf((t, s) -> false, (t, s) -> true),
" Matchers.anyOf((t, s) -> false));", Matchers.allOf(),
" Matchers.anyOf(", Matchers.anyOf((t, s) -> false));
" Matchers.allOf(),", Matchers.anyOf(
" Matchers.anyOf((t, s) -> false, (t, s) -> true),", Matchers.allOf(),
" Matchers.anyOf(),", Matchers.anyOf((t, s) -> false, (t, s) -> true),
" Matchers.allOf((t, s) -> false));", Matchers.anyOf(),
" Refaster.anyOf(Matchers.allOf(), Refaster.anyOf(1, 2), Matchers.anyOf());", Matchers.allOf((t, s) -> false));
" }", Refaster.anyOf(Matchers.allOf(), Refaster.anyOf(1, 2), Matchers.anyOf());
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.errorprone.matchers.Matchers;", """
"import com.google.errorprone.refaster.Refaster;", import com.google.errorprone.matchers.Matchers;
"", import com.google.errorprone.refaster.Refaster;
"class A {",
" void m() {", class A {
" Matchers.allOf();", void m() {
" Matchers.anyOf();", Matchers.allOf();
" Refaster.anyOf();", Matchers.anyOf();
"", Refaster.anyOf();
" Matchers.allOf((t, s) -> true);",
" Matchers.anyOf((t, s) -> true);", Matchers.allOf((t, s) -> true);
" Refaster.anyOf(0);", Matchers.anyOf((t, s) -> true);
"", Refaster.anyOf(0);
" Matchers.allOf(",
" Matchers.anyOf(), (t, s) -> false, (t, s) -> true, Matchers.anyOf((t, s) -> false));", Matchers.allOf(
" Matchers.anyOf(", Matchers.anyOf(), (t, s) -> false, (t, s) -> true, Matchers.anyOf((t, s) -> false));
" Matchers.allOf(), (t, s) -> false, (t, s) -> true, Matchers.allOf((t, s) -> false));", Matchers.anyOf(
" Refaster.anyOf(Matchers.allOf(), 1, 2, Matchers.anyOf());", Matchers.allOf(), (t, s) -> false, (t, s) -> true, Matchers.allOf((t, s) -> false));
" }", Refaster.anyOf(Matchers.allOf(), 1, 2, Matchers.anyOf());
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,121 +11,141 @@ final class BugPatternLinkTest {
CompilationTestHelper.newInstance(BugPatternLink.class, getClass()) CompilationTestHelper.newInstance(BugPatternLink.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.errorprone.BugPattern;", """
"", import com.google.errorprone.BugPattern;
"@BugPattern(summary = \"Class in default package\", severity = BugPattern.SeverityLevel.ERROR)",
"class A {}") @BugPattern(summary = "Class in default package", severity = BugPattern.SeverityLevel.ERROR)
class A {}
""")
.addSourceLines( .addSourceLines(
"com/example/B.java", "com/example/B.java",
"package com.example;", """
"", package com.example;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"@BugPattern(summary = \"Class in custom package\", severity = BugPattern.SeverityLevel.ERROR)",
"class B {}") @BugPattern(summary = "Class in custom package", severity = BugPattern.SeverityLevel.ERROR)
class B {}
""")
.addSourceLines( .addSourceLines(
"tech/picnic/errorprone/C.java", "tech/picnic/errorprone/C.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"@BugPattern(",
" summary = \"Class explicitly without link\",", @BugPattern(
" linkType = BugPattern.LinkType.NONE,", summary = "Class explicitly without link",
" severity = BugPattern.SeverityLevel.ERROR)", linkType = BugPattern.LinkType.NONE,
"class C {}") severity = BugPattern.SeverityLevel.ERROR)
class C {}
""")
.addSourceLines( .addSourceLines(
"tech/picnic/errorprone/subpackage/D.java", "tech/picnic/errorprone/subpackage/D.java",
"package tech.picnic.errorprone.subpackage;", """
"", package tech.picnic.errorprone.subpackage;
"import com.google.errorprone.BugPattern;",
"import tech.picnic.errorprone.utils.Documentation;", import com.google.errorprone.BugPattern;
"", import tech.picnic.errorprone.utils.Documentation;
"@BugPattern(",
" summary = \"Error Prone Support class in subpackage with proper link\",", @BugPattern(
" link = Documentation.BUG_PATTERNS_BASE_URL + \"D\",", summary = "Error Prone Support class in subpackage with proper link",
" linkType = BugPattern.LinkType.CUSTOM,", link = Documentation.BUG_PATTERNS_BASE_URL + "D",
" severity = BugPattern.SeverityLevel.ERROR)", linkType = BugPattern.LinkType.CUSTOM,
"class D {}") severity = BugPattern.SeverityLevel.ERROR)
class D {}
""")
.addSourceLines( .addSourceLines(
"tech/picnic/errorprone/E.java", "tech/picnic/errorprone/E.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import static com.google.errorprone.BugPattern.LinkType.CUSTOM;",
"import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;", import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
"import static tech.picnic.errorprone.utils.Documentation.BUG_PATTERNS_BASE_URL;", import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
"", import static tech.picnic.errorprone.utils.Documentation.BUG_PATTERNS_BASE_URL;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"@BugPattern(",
" summary = \"Error Prone Support class with proper link and static imports\",", @BugPattern(
" link = BUG_PATTERNS_BASE_URL + \"E\",", summary = "Error Prone Support class with proper link and static imports",
" linkType = CUSTOM,", link = BUG_PATTERNS_BASE_URL + "E",
" severity = ERROR)", linkType = CUSTOM,
"class E {}") severity = ERROR)
class E {}
""")
.addSourceLines( .addSourceLines(
"tech/picnic/errorprone/F.java", "tech/picnic/errorprone/F.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"class F {",
" @BugPattern(", class F {
" summary = \"Nested Error Prone Support class\",", @BugPattern(
" severity = BugPattern.SeverityLevel.ERROR)", summary = "Nested Error Prone Support class",
" class Inner {}", severity = BugPattern.SeverityLevel.ERROR)
"}") class Inner {}
}
""")
.addSourceLines( .addSourceLines(
"tech/picnic/errorprone/G.java", "tech/picnic/errorprone/G.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"// BUG: Diagnostic contains:",
"@BugPattern(", // BUG: Diagnostic contains:
" summary = \"Error Prone Support class lacking link\",", @BugPattern(
" severity = BugPattern.SeverityLevel.ERROR)", summary = "Error Prone Support class lacking link",
"class G {}") severity = BugPattern.SeverityLevel.ERROR)
class G {}
""")
.addSourceLines( .addSourceLines(
"tech/picnic/errorprone/H.java", "tech/picnic/errorprone/H.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import com.google.errorprone.BugPattern;",
"import tech.picnic.errorprone.utils.Documentation;", import com.google.errorprone.BugPattern;
"", import tech.picnic.errorprone.utils.Documentation;
"// BUG: Diagnostic contains:",
"@BugPattern(", // BUG: Diagnostic contains:
" summary = \"Error Prone Support class with incorrect link\",", @BugPattern(
" link = Documentation.BUG_PATTERNS_BASE_URL + \"NotH\",", summary = "Error Prone Support class with incorrect link",
" linkType = BugPattern.LinkType.CUSTOM,", link = Documentation.BUG_PATTERNS_BASE_URL + "NotH",
" severity = BugPattern.SeverityLevel.ERROR)", linkType = BugPattern.LinkType.CUSTOM,
"class H {}") severity = BugPattern.SeverityLevel.ERROR)
class H {}
""")
.addSourceLines( .addSourceLines(
"tech/picnic/errorprone/I.java", "tech/picnic/errorprone/I.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"// BUG: Diagnostic contains:",
"@BugPattern(", // BUG: Diagnostic contains:
" summary = \"Error Prone Support class with non-canonical link\",", @BugPattern(
" link = \"https://error-prone.picnic.tech/bugpatterns/I\",", summary = "Error Prone Support class with non-canonical link",
" linkType = BugPattern.LinkType.CUSTOM,", link = "https://error-prone.picnic.tech/bugpatterns/I",
" severity = BugPattern.SeverityLevel.ERROR)", linkType = BugPattern.LinkType.CUSTOM,
"class I {}") severity = BugPattern.SeverityLevel.ERROR)
class I {}
""")
.addSourceLines( .addSourceLines(
"tech/picnic/errorprone/J.java", "tech/picnic/errorprone/J.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"// BUG: Diagnostic contains:",
"@BugPattern(", // BUG: Diagnostic contains:
" summary = \"Error Prone Support class in with non-canonical link\",", @BugPattern(
" link = \"https://error-prone.picnic.tech/bugpatterns/\" + \"J\",", summary = "Error Prone Support class in with non-canonical link",
" linkType = BugPattern.LinkType.CUSTOM,", link = "https://error-prone.picnic.tech/bugpatterns/" + "J",
" severity = BugPattern.SeverityLevel.ERROR)", linkType = BugPattern.LinkType.CUSTOM,
"class J {}") severity = BugPattern.SeverityLevel.ERROR)
class J {}
""")
.doTest(); .doTest();
} }
@@ -134,60 +154,68 @@ final class BugPatternLinkTest {
BugCheckerRefactoringTestHelper.newInstance(BugPatternLink.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(BugPatternLink.class, getClass())
.addInputLines( .addInputLines(
"tech/picnic/errorprone/A.java", "tech/picnic/errorprone/A.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"@BugPattern(",
" summary = \"Error Prone Support class lacking link\",", @BugPattern(
" severity = BugPattern.SeverityLevel.ERROR)", summary = "Error Prone Support class lacking link",
"class A {}") severity = BugPattern.SeverityLevel.ERROR)
class A {}
""")
.addOutputLines( .addOutputLines(
"tech/picnic/errorprone/A.java", "tech/picnic/errorprone/A.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import static com.google.errorprone.BugPattern.LinkType.CUSTOM;",
"import static tech.picnic.errorprone.utils.Documentation.BUG_PATTERNS_BASE_URL;", import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
"", import static tech.picnic.errorprone.utils.Documentation.BUG_PATTERNS_BASE_URL;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"@BugPattern(",
" link = BUG_PATTERNS_BASE_URL + \"A\",", @BugPattern(
" linkType = CUSTOM,", link = BUG_PATTERNS_BASE_URL + "A",
" summary = \"Error Prone Support class lacking link\",", linkType = CUSTOM,
" severity = BugPattern.SeverityLevel.ERROR)", summary = "Error Prone Support class lacking link",
"class A {}") severity = BugPattern.SeverityLevel.ERROR)
class A {}
""")
.addInputLines( .addInputLines(
"tech/picnic/errorprone/B.java", "tech/picnic/errorprone/B.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import static com.google.errorprone.BugPattern.LinkType.CUSTOM;",
"import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;", import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
"", import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"@BugPattern(",
" summary = \"Error Prone Support class with incorrect link\",", @BugPattern(
" link = \"Not the right link\",", summary = "Error Prone Support class with incorrect link",
" linkType = CUSTOM,", link = "Not the right link",
" severity = ERROR)", linkType = CUSTOM,
"class B {}") severity = ERROR)
class B {}
""")
.addOutputLines( .addOutputLines(
"tech/picnic/errorprone/B.java", "tech/picnic/errorprone/B.java",
"package tech.picnic.errorprone;", """
"", package tech.picnic.errorprone;
"import static com.google.errorprone.BugPattern.LinkType.CUSTOM;",
"import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;", import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
"import static tech.picnic.errorprone.utils.Documentation.BUG_PATTERNS_BASE_URL;", import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
"", import static tech.picnic.errorprone.utils.Documentation.BUG_PATTERNS_BASE_URL;
"import com.google.errorprone.BugPattern;",
"", import com.google.errorprone.BugPattern;
"@BugPattern(",
" summary = \"Error Prone Support class with incorrect link\",", @BugPattern(
" link = BUG_PATTERNS_BASE_URL + \"B\",", summary = "Error Prone Support class with incorrect link",
" linkType = CUSTOM,", link = BUG_PATTERNS_BASE_URL + "B",
" severity = ERROR)", linkType = CUSTOM,
"class B {}") severity = ERROR)
class B {}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -21,68 +21,70 @@ final class ErrorProneRuntimeClasspathTest {
"This type may not be on the runtime classpath; use a string literal instead")) "This type may not be on the runtime classpath; use a string literal instead"))
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", import com.google.common.collect.ImmutableList;
"import com.google.errorprone.BugPattern;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugPattern;
"import org.junit.jupiter.api.Test;", import com.google.errorprone.CompilationTestHelper;
"", import org.junit.jupiter.api.Test;
"class A {",
" @SuppressWarnings(\"java.lang.String\")", class A {
" void m(Object o) {", @SuppressWarnings("java.lang.String")
" m(null);", void m(Object o) {
" m(0);", m(null);
" m(getClass().getName());", m(0);
" m(getClass().getCanonicalName());", m(getClass().getName());
" m(\"\");", m(getClass().getCanonicalName());
" m(\"foo\");", m("");
" m(\"java.util.\");", m("foo");
"", m("java.util.");
" m(\"org.junit.jupiter.api.Test\");",
" m(\"org.junit.jupiter.api.Test.toString\");", m("org.junit.jupiter.api.Test");
" m(\"com.google.errorprone.CompilationTestHelper\");", m("org.junit.jupiter.api.Test.toString");
" m(\"com.google.errorprone.CompilationTestHelper.toString\");", m("com.google.errorprone.CompilationTestHelper");
" m(\"com.google.errorprone.BugCheckerRefactoringTestHelper.ExpectOutput\");", m("com.google.errorprone.CompilationTestHelper.toString");
" m(\"com.google.errorprone.BugCheckerRefactoringTestHelper.ExpectOutput.toString\");", m("com.google.errorprone.BugCheckerRefactoringTestHelper.ExpectOutput");
" m(\"com.google.errorprone.NonExistent\");", m("com.google.errorprone.BugCheckerRefactoringTestHelper.ExpectOutput.toString");
" m(\"com.google.common.NonExistent.toString\");", m("com.google.errorprone.NonExistent");
" m(\"java.lang.NonExistent\");", m("com.google.common.NonExistent.toString");
" m(\"com.google.common.collect.ImmutableEnumSet\");", m("java.lang.NonExistent");
" // BUG: Diagnostic matches: USE_CLASS_REFERENCE", m("com.google.common.collect.ImmutableEnumSet");
" m(\"com.google.errorprone.BugPattern\");", // BUG: Diagnostic matches: USE_CLASS_REFERENCE
" // BUG: Diagnostic matches: USE_CLASS_REFERENCE", m("com.google.errorprone.BugPattern");
" m(\"com.google.errorprone.util.ErrorProneToken\");", // BUG: Diagnostic matches: USE_CLASS_REFERENCE
" // BUG: Diagnostic matches: USE_CLASS_REFERENCE", m("com.google.errorprone.util.ErrorProneToken");
" m(\"com.google.common.collect.ImmutableList\");", // BUG: Diagnostic matches: USE_CLASS_REFERENCE
" // BUG: Diagnostic matches: USE_CLASS_REFERENCE", m("com.google.common.collect.ImmutableList");
" m(\"java.lang.String\");", // BUG: Diagnostic matches: USE_CLASS_REFERENCE
" // BUG: Diagnostic matches: USE_CLASS_REFERENCE", m("java.lang.String");
" m(\"java.lang.String.toString\");", // BUG: Diagnostic matches: USE_CLASS_REFERENCE
"", m("java.lang.String.toString");
" m(BugPattern.class.getCanonicalName());",
" m(ImmutableList.class.getCanonicalName());", m(BugPattern.class.getCanonicalName());
" m(String.class.getCanonicalName());", m(ImmutableList.class.getCanonicalName());
" m(void.class.getCanonicalName());", m(String.class.getCanonicalName());
" m(boolean.class.getCanonicalName());", m(void.class.getCanonicalName());
" m(byte.class.getCanonicalName());", m(boolean.class.getCanonicalName());
" m(char.class.getCanonicalName());", m(byte.class.getCanonicalName());
" m(short.class.getCanonicalName());", m(char.class.getCanonicalName());
" m(int.class.getCanonicalName());", m(short.class.getCanonicalName());
" m(long.class.getCanonicalName());", m(int.class.getCanonicalName());
" m(float.class.getCanonicalName());", m(long.class.getCanonicalName());
" m(double.class.getCanonicalName());", m(float.class.getCanonicalName());
" m(java.lang.Iterable.class.getCanonicalName());", m(double.class.getCanonicalName());
" m(CompilationTestHelper.class.toString());", m(java.lang.Iterable.class.getCanonicalName());
" // BUG: Diagnostic matches: USE_STRING_LITERAL", m(CompilationTestHelper.class.toString());
" m(CompilationTestHelper.class.getCanonicalName());", // BUG: Diagnostic matches: USE_STRING_LITERAL
" // BUG: Diagnostic matches: USE_STRING_LITERAL", m(CompilationTestHelper.class.getCanonicalName());
" m(BugCheckerRefactoringTestHelper.ExpectOutput.class.getCanonicalName());", // BUG: Diagnostic matches: USE_STRING_LITERAL
" // BUG: Diagnostic matches: USE_STRING_LITERAL", m(BugCheckerRefactoringTestHelper.ExpectOutput.class.getCanonicalName());
" m(Test.class.getCanonicalName());", // BUG: Diagnostic matches: USE_STRING_LITERAL
" // BUG: Diagnostic matches: USE_STRING_LITERAL", m(Test.class.getCanonicalName());
" m(org.junit.jupiter.api.Nested.class.getCanonicalName());", // BUG: Diagnostic matches: USE_STRING_LITERAL
" }", m(org.junit.jupiter.api.Nested.class.getCanonicalName());
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -91,47 +93,51 @@ final class ErrorProneRuntimeClasspathTest {
BugCheckerRefactoringTestHelper.newInstance(ErrorProneRuntimeClasspath.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(ErrorProneRuntimeClasspath.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import org.junit.jupiter.api.Test;", import com.google.errorprone.CompilationTestHelper;
"", import org.junit.jupiter.api.Test;
"class A {",
" void m(Object o) {", class A {
" m(\"com.google.errorprone.BugPattern\");", void m(Object o) {
" m(\"com.google.errorprone.util.ErrorProneToken\");", m("com.google.errorprone.BugPattern");
" m(\"com.google.common.collect.ImmutableList\");", m("com.google.errorprone.util.ErrorProneToken");
" m(\"java.lang.String\");", m("com.google.common.collect.ImmutableList");
" m(\"java.lang.String.toString\");", m("java.lang.String");
"", m("java.lang.String.toString");
" m(CompilationTestHelper.class.getCanonicalName());",
" m(BugCheckerRefactoringTestHelper.ExpectOutput.class.getCanonicalName());", m(CompilationTestHelper.class.getCanonicalName());
" m(Test.class.getCanonicalName());", m(BugCheckerRefactoringTestHelper.ExpectOutput.class.getCanonicalName());
" m(org.junit.jupiter.api.Nested.class.getCanonicalName());", m(Test.class.getCanonicalName());
" }", m(org.junit.jupiter.api.Nested.class.getCanonicalName());
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", import com.google.common.collect.ImmutableList;
"import com.google.errorprone.BugPattern;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugPattern;
"import com.google.errorprone.util.ErrorProneToken;", import com.google.errorprone.CompilationTestHelper;
"import org.junit.jupiter.api.Test;", import com.google.errorprone.util.ErrorProneToken;
"", import org.junit.jupiter.api.Test;
"class A {",
" void m(Object o) {", class A {
" m(BugPattern.class.getCanonicalName());", void m(Object o) {
" m(ErrorProneToken.class.getCanonicalName());", m(BugPattern.class.getCanonicalName());
" m(ImmutableList.class.getCanonicalName());", m(ErrorProneToken.class.getCanonicalName());
" m(String.class.getCanonicalName());", m(ImmutableList.class.getCanonicalName());
" m(String.class.getCanonicalName() + \".toString\");", m(String.class.getCanonicalName());
"", m(String.class.getCanonicalName() + ".toString");
" m(\"com.google.errorprone.CompilationTestHelper\");",
" m(\"com.google.errorprone.BugCheckerRefactoringTestHelper.ExpectOutput\");", m("com.google.errorprone.CompilationTestHelper");
" m(\"org.junit.jupiter.api.Test\");", m("com.google.errorprone.BugCheckerRefactoringTestHelper.ExpectOutput");
" m(\"org.junit.jupiter.api.Nested\");", m("org.junit.jupiter.api.Test");
" }", m("org.junit.jupiter.api.Nested");
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,142 +11,146 @@ final class ExhaustiveRefasterTypeMigrationTest {
CompilationTestHelper.newInstance(ExhaustiveRefasterTypeMigration.class, getClass()) CompilationTestHelper.newInstance(ExhaustiveRefasterTypeMigration.class, getClass())
.addSourceLines( .addSourceLines(
"Util.java", "Util.java",
"class Util {", """
" public static int CONSTANT = 42;", class Util {
"", public static int CONSTANT = 42;
" public static void publicStaticVoidMethod() {}",
"", public static void publicStaticVoidMethod() {}
" static void packagePrivateStaticVoidMethod() {}",
"", static void packagePrivateStaticVoidMethod() {}
" protected static void protectedStaticVoidMethod() {}",
"", protected static void protectedStaticVoidMethod() {}
" private static void privateStaticVoidMethod() {}",
"", private static void privateStaticVoidMethod() {}
" public static int publicStaticIntMethod2() {",
" return 0;", public static int publicStaticIntMethod2() {
" }", return 0;
"", }
" public String publicStringMethodWithArg(int arg) {",
" return String.valueOf(arg);", public String publicStringMethodWithArg(int arg) {
" }", return String.valueOf(arg);
"}") }
}
""")
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.annotation.AfterTemplate;", """
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", import com.google.errorprone.refaster.annotation.AfterTemplate;
"import tech.picnic.errorprone.refaster.annotation.TypeMigration;", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"", import tech.picnic.errorprone.refaster.annotation.TypeMigration;
"class A {",
" class UnannotatedEmptyClass {}", class A {
"", class UnannotatedEmptyClass {}
" // BUG: Diagnostic contains: Migration of type 'int' is unsupported",
" @TypeMigration(of = int.class)", // BUG: Diagnostic contains: Migration of type 'int' is unsupported
" class AnnotatedWithPrimitive {}", @TypeMigration(of = int.class)
"", class AnnotatedWithPrimitive {}
" @TypeMigration(",
" of = Util.class,", @TypeMigration(
" unmigratedMethods = {", of = Util.class,
" \"publicStaticIntMethod2()\",", unmigratedMethods = {
" \"publicStringMethodWithArg(int)\",", "publicStaticIntMethod2()",
" \"publicStaticVoidMethod()\"", "publicStringMethodWithArg(int)",
" })", "publicStaticVoidMethod()"
" class AnnotatedEmptyClass {}", })
"", class AnnotatedEmptyClass {}
" @TypeMigration(",
" of = Util.class,", @TypeMigration(
" unmigratedMethods = {", of = Util.class,
" \"publicStaticVoidMethod()\",", unmigratedMethods = {
" \"publicStringMethodWithArg(int)\",", "publicStaticVoidMethod()",
" \"publicStaticIntMethod2()\"", "publicStringMethodWithArg(int)",
" })", "publicStaticIntMethod2()"
" class AnnotatedEmptyClassWithUnsortedMethodListing {}", })
"", class AnnotatedEmptyClassWithUnsortedMethodListing {}
" class UnannotatedTemplate {",
" @BeforeTemplate", class UnannotatedTemplate {
" void before(int value) {", @BeforeTemplate
" Util.publicStaticVoidMethod();", void before(int value) {
" Util.publicStaticIntMethod2();", Util.publicStaticVoidMethod();
" new Util().publicStringMethodWithArg(value);", Util.publicStaticIntMethod2();
" }", new Util().publicStringMethodWithArg(value);
" }", }
"", }
" @TypeMigration(",
" of = Util.class,", @TypeMigration(
" unmigratedMethods = {", of = Util.class,
" \"publicStaticIntMethod2()\",", unmigratedMethods = {
" \"publicStringMethodWithArg(int)\",", "publicStaticIntMethod2()",
" \"publicStaticVoidMethod()\"", "publicStringMethodWithArg(int)",
" })", "publicStaticVoidMethod()"
" class AnnotatedWithoutBeforeTemplate {", })
" {", class AnnotatedWithoutBeforeTemplate {
" Util.publicStaticIntMethod2();", {
" }", Util.publicStaticIntMethod2();
"", }
" @AfterTemplate",
" void after(int value) {", @AfterTemplate
" Util.publicStaticVoidMethod();", void after(int value) {
" new Util().publicStringMethodWithArg(value);", Util.publicStaticVoidMethod();
" }", new Util().publicStringMethodWithArg(value);
" }", }
"", }
" @TypeMigration(of = Util.class)",
" class AnnotatedFullyMigrated {", @TypeMigration(of = Util.class)
" @BeforeTemplate", class AnnotatedFullyMigrated {
" void before() {", @BeforeTemplate
" new Util().publicStringMethodWithArg(Util.publicStaticIntMethod2());", void before() {
" }", new Util().publicStringMethodWithArg(Util.publicStaticIntMethod2());
"", }
" @BeforeTemplate",
" void before2() {", @BeforeTemplate
" Util.publicStaticVoidMethod();", void before2() {
" }", Util.publicStaticVoidMethod();
" }", }
"", }
" @TypeMigration(of = Util.class, unmigratedMethods = \"publicStringMethodWithArg(int)\")",
" class AnnotatedPartiallyMigrated {", @TypeMigration(of = Util.class, unmigratedMethods = "publicStringMethodWithArg(int)")
" @BeforeTemplate", class AnnotatedPartiallyMigrated {
" void before() {", @BeforeTemplate
" Util.publicStaticVoidMethod();", void before() {
" Util.publicStaticIntMethod2();", Util.publicStaticVoidMethod();
" }", Util.publicStaticIntMethod2();
" }", }
"", }
" // BUG: Diagnostic contains: The set of unmigrated methods listed by the `@TypeMigration`",
" // annotation must be minimal yet exhaustive", // BUG: Diagnostic contains: The set of unmigrated methods listed by the `@TypeMigration`
" @TypeMigration(of = Util.class, unmigratedMethods = \"publicStringMethodWithArg(int)\")", // annotation must be minimal yet exhaustive
" class AnnotatedWithIncompleteMethodListing {", @TypeMigration(of = Util.class, unmigratedMethods = "publicStringMethodWithArg(int)")
" @BeforeTemplate", class AnnotatedWithIncompleteMethodListing {
" void before() {", @BeforeTemplate
" Util.publicStaticIntMethod2();", void before() {
" }", Util.publicStaticIntMethod2();
" }", }
"", }
" // BUG: Diagnostic contains: The set of unmigrated methods listed by the `@TypeMigration`",
" // annotation must be minimal yet exhaustive", // BUG: Diagnostic contains: The set of unmigrated methods listed by the `@TypeMigration`
" @TypeMigration(", // annotation must be minimal yet exhaustive
" of = Util.class,", @TypeMigration(
" unmigratedMethods = {\"publicStaticIntMethod2()\", \"publicStringMethodWithArg(int)\"})", of = Util.class,
" class AnnotatedWithMigratedMethodReference {", unmigratedMethods = {"publicStaticIntMethod2()", "publicStringMethodWithArg(int)"})
" @BeforeTemplate", class AnnotatedWithMigratedMethodReference {
" void before() {", @BeforeTemplate
" Util.publicStaticVoidMethod();", void before() {
" Util.publicStaticIntMethod2();", Util.publicStaticVoidMethod();
" }", Util.publicStaticIntMethod2();
" }", }
"", }
" // BUG: Diagnostic contains: The set of unmigrated methods listed by the `@TypeMigration`",
" // annotation must be minimal yet exhaustive", // BUG: Diagnostic contains: The set of unmigrated methods listed by the `@TypeMigration`
" @TypeMigration(", // annotation must be minimal yet exhaustive
" of = Util.class,", @TypeMigration(
" unmigratedMethods = {\"extra\", \"publicStringMethodWithArg(int)\"})", of = Util.class,
" class AnnotatedWithUnknownMethodReference {", unmigratedMethods = {"extra", "publicStringMethodWithArg(int)"})
" @BeforeTemplate", class AnnotatedWithUnknownMethodReference {
" void before() {", @BeforeTemplate
" Util.publicStaticVoidMethod();", void before() {
" Util.publicStaticIntMethod2();", Util.publicStaticVoidMethod();
" }", Util.publicStaticIntMethod2();
" }", }
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -155,109 +159,115 @@ final class ExhaustiveRefasterTypeMigrationTest {
BugCheckerRefactoringTestHelper.newInstance(ExhaustiveRefasterTypeMigration.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(ExhaustiveRefasterTypeMigration.class, getClass())
.addInputLines( .addInputLines(
"Util.java", "Util.java",
"public final class Util {", """
" public static void publicStaticVoidMethod() {}", public final class Util {
"", public static void publicStaticVoidMethod() {}
" public static int publicStaticIntMethod2() {",
" return 0;", public static int publicStaticIntMethod2() {
" }", return 0;
"", }
" public String publicStringMethodWithArg(int arg) {",
" return String.valueOf(arg);", public String publicStringMethodWithArg(int arg) {
" }", return String.valueOf(arg);
"", }
" public String publicStringMethodWithArg(String arg) {",
" return arg;", public String publicStringMethodWithArg(String arg) {
" }", return arg;
"}") }
}
""")
.expectUnchanged() .expectUnchanged()
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"import tech.picnic.errorprone.refaster.annotation.TypeMigration;", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"", import tech.picnic.errorprone.refaster.annotation.TypeMigration;
"class A {",
" @TypeMigration(of = Util.class)", class A {
" class AnnotatedWithoutMethodListing {", @TypeMigration(of = Util.class)
" {", class AnnotatedWithoutMethodListing {
" new Util().publicStringMethodWithArg(1);", {
" }", new Util().publicStringMethodWithArg(1);
"", }
" @BeforeTemplate",
" void before() {", @BeforeTemplate
" Util.publicStaticIntMethod2();", void before() {
" }", Util.publicStaticIntMethod2();
" }", }
"", }
" @TypeMigration(",
" of = Util.class,", @TypeMigration(
" unmigratedMethods = {\"publicStaticIntMethod2()\", \"extra\", \"publicStringMethodWithArg(int)\"})", of = Util.class,
" class AnnotatedWithIncorrectMethodReference {", unmigratedMethods = {"publicStaticIntMethod2()", "extra", "publicStringMethodWithArg(int)"})
" @BeforeTemplate", class AnnotatedWithIncorrectMethodReference {
" void before() {", @BeforeTemplate
" new Util().publicStringMethodWithArg(\"1\");", void before() {
" Util.publicStaticVoidMethod();", new Util().publicStringMethodWithArg("1");
" Util.publicStaticIntMethod2();", Util.publicStaticVoidMethod();
" }", Util.publicStaticIntMethod2();
" }", }
"", }
" @TypeMigration(",
" of = Util.class,", @TypeMigration(
" unmigratedMethods = {\"publicStaticVoidMethod()\", \"publicStaticVoidMethod()\"})", of = Util.class,
" class AnnotatedWithDuplicateMethodReference {", unmigratedMethods = {"publicStaticVoidMethod()", "publicStaticVoidMethod()"})
" @BeforeTemplate", class AnnotatedWithDuplicateMethodReference {
" void before() {", @BeforeTemplate
" new Util().publicStringMethodWithArg(1);", void before() {
" new Util().publicStringMethodWithArg(\"1\");", new Util().publicStringMethodWithArg(1);
" Util.publicStaticIntMethod2();", new Util().publicStringMethodWithArg("1");
" }", Util.publicStaticIntMethod2();
" }", }
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"import tech.picnic.errorprone.refaster.annotation.TypeMigration;", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"", import tech.picnic.errorprone.refaster.annotation.TypeMigration;
"class A {",
" @TypeMigration(", class A {
" unmigratedMethods = {", @TypeMigration(
" \"publicStaticVoidMethod()\",", unmigratedMethods = {
" \"publicStringMethodWithArg(int)\",", "publicStaticVoidMethod()",
" \"publicStringMethodWithArg(String)\",", "publicStringMethodWithArg(int)",
" \"Util()\"", "publicStringMethodWithArg(String)",
" },", "Util()"
" of = Util.class)", },
" class AnnotatedWithoutMethodListing {", of = Util.class)
" {", class AnnotatedWithoutMethodListing {
" new Util().publicStringMethodWithArg(1);", {
" }", new Util().publicStringMethodWithArg(1);
"", }
" @BeforeTemplate",
" void before() {", @BeforeTemplate
" Util.publicStaticIntMethod2();", void before() {
" }", Util.publicStaticIntMethod2();
" }", }
"", }
" @TypeMigration(of = Util.class, unmigratedMethods = \"publicStringMethodWithArg(int)\")",
" class AnnotatedWithIncorrectMethodReference {", @TypeMigration(of = Util.class, unmigratedMethods = "publicStringMethodWithArg(int)")
" @BeforeTemplate", class AnnotatedWithIncorrectMethodReference {
" void before() {", @BeforeTemplate
" new Util().publicStringMethodWithArg(\"1\");", void before() {
" Util.publicStaticVoidMethod();", new Util().publicStringMethodWithArg("1");
" Util.publicStaticIntMethod2();", Util.publicStaticVoidMethod();
" }", Util.publicStaticIntMethod2();
" }", }
"", }
" @TypeMigration(of = Util.class, unmigratedMethods = \"publicStaticVoidMethod()\")",
" class AnnotatedWithDuplicateMethodReference {", @TypeMigration(of = Util.class, unmigratedMethods = "publicStaticVoidMethod()")
" @BeforeTemplate", class AnnotatedWithDuplicateMethodReference {
" void before() {", @BeforeTemplate
" new Util().publicStringMethodWithArg(1);", void before() {
" new Util().publicStringMethodWithArg(\"1\");", new Util().publicStringMethodWithArg(1);
" Util.publicStaticIntMethod2();", new Util().publicStringMethodWithArg("1");
" }", Util.publicStaticIntMethod2();
" }", }
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,23 +11,25 @@ final class RefasterAnyOfUsageTest {
CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass()) CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.Refaster;", """
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", import com.google.errorprone.refaster.Refaster;
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"class A {",
" @BeforeTemplate", class A {
" String before(String str) {", @BeforeTemplate
" // BUG: Diagnostic contains:", String before(String str) {
" Refaster.anyOf();", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", Refaster.anyOf();
" return Refaster.anyOf(str);", // BUG: Diagnostic contains:
" }", return Refaster.anyOf(str);
"", }
" @BeforeTemplate",
" Object before2(String str, Object obj) {", @BeforeTemplate
" return Refaster.anyOf(str, obj);", Object before2(String str, Object obj) {
" }", return Refaster.anyOf(str, obj);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -36,28 +38,32 @@ final class RefasterAnyOfUsageTest {
BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.Refaster;", """
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", import com.google.errorprone.refaster.Refaster;
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"class A {",
" @BeforeTemplate", class A {
" String before(String str) {", @BeforeTemplate
" Refaster.anyOf();", String before(String str) {
" return Refaster.anyOf(str);", Refaster.anyOf();
" }", return Refaster.anyOf(str);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.Refaster;", """
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", import com.google.errorprone.refaster.Refaster;
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"class A {",
" @BeforeTemplate", class A {
" String before(String str) {", @BeforeTemplate
" Refaster.anyOf();", String before(String str) {
" return str;", Refaster.anyOf();
" }", return str;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,44 +11,46 @@ final class RefasterMethodParameterOrderTest {
CompilationTestHelper.newInstance(RefasterMethodParameterOrder.class, getClass()) CompilationTestHelper.newInstance(RefasterMethodParameterOrder.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;", """
"import static org.assertj.core.api.Assertions.assertThat;", import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
"", import static org.assertj.core.api.Assertions.assertThat;
"import com.google.errorprone.refaster.annotation.AfterTemplate;",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", import com.google.errorprone.refaster.annotation.AfterTemplate;
"import com.google.errorprone.refaster.annotation.Placeholder;", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"import com.google.errorprone.refaster.annotation.UseImportPolicy;", import com.google.errorprone.refaster.annotation.Placeholder;
"import java.util.Map;", import com.google.errorprone.refaster.annotation.UseImportPolicy;
"", import java.util.Map;
"class A {",
" class UnusedLexicographicallyOrderedParameters {", class A {
" @BeforeTemplate", class UnusedLexicographicallyOrderedParameters {
" void singleParam(int a) {}", @BeforeTemplate
"", void singleParam(int a) {}
" @BeforeTemplate",
" void twoParams(int a, int b) {}", @BeforeTemplate
"", void twoParams(int a, int b) {}
" @Placeholder",
" void notATemplateMethod(int b, int a) {}", @Placeholder
" }", void notATemplateMethod(int b, int a) {}
"", }
" class NonParameterValueIdentifierIsIgnored<K, V> {",
" @AfterTemplate", class NonParameterValueIdentifierIsIgnored<K, V> {
" @UseImportPolicy(value = STATIC_IMPORT_ALWAYS)", @AfterTemplate
" void after(Map<K, V> map, V value) {", @UseImportPolicy(value = STATIC_IMPORT_ALWAYS)
" assertThat(map).containsValue(value);", void after(Map<K, V> map, V value) {
" }", assertThat(map).containsValue(value);
" }", }
"", }
" // BUG: Diagnostic contains:",
" class UnusedLexicographicallyUnorderedParameters {", // BUG: Diagnostic contains:
" @BeforeTemplate", class UnusedLexicographicallyUnorderedParameters {
" void foo(int a, int b) {}", @BeforeTemplate
"", void foo(int a, int b) {}
" @BeforeTemplate",
" void bar(int b, int a) {}", @BeforeTemplate
" }", void bar(int b, int a) {}
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -57,74 +59,78 @@ final class RefasterMethodParameterOrderTest {
BugCheckerRefactoringTestHelper.newInstance(RefasterMethodParameterOrder.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(RefasterMethodParameterOrder.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.annotation.AfterTemplate;", """
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", import com.google.errorprone.refaster.annotation.AfterTemplate;
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"class A {",
" class UnusedUnsortedParameters {", class A {
" @BeforeTemplate", class UnusedUnsortedParameters {
" void before(int b, int a) {}", @BeforeTemplate
" }", void before(int b, int a) {}
"", }
" class UnsortedParametersWithoutAfterTemplate {",
" @BeforeTemplate", class UnsortedParametersWithoutAfterTemplate {
" int before(int a, int b, int c, int d) {", @BeforeTemplate
" return b + a + d + b + c;", int before(int a, int b, int c, int d) {
" }", return b + a + d + b + c;
" }", }
"", }
" class UnsortedParametersWithMultipleMethodsAndParameterCounts {",
" @BeforeTemplate", class UnsortedParametersWithMultipleMethodsAndParameterCounts {
" int before(int b, int a, int g, int f, int d) {", @BeforeTemplate
" return f + a + g + b + d;", int before(int b, int a, int g, int f, int d) {
" }", return f + a + g + b + d;
"", }
" @AfterTemplate",
" int after(int a, int b) {", @AfterTemplate
" return b + a;", int after(int a, int b) {
" }", return b + a;
"", }
" @AfterTemplate",
" int after2(int a, int d, int f) {", @AfterTemplate
" return d + a + f;", int after2(int a, int d, int f) {
" }", return d + a + f;
" }", }
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.annotation.AfterTemplate;", """
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", import com.google.errorprone.refaster.annotation.AfterTemplate;
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"class A {",
" class UnusedUnsortedParameters {", class A {
" @BeforeTemplate", class UnusedUnsortedParameters {
" void before(int a, int b) {}", @BeforeTemplate
" }", void before(int a, int b) {}
"", }
" class UnsortedParametersWithoutAfterTemplate {",
" @BeforeTemplate", class UnsortedParametersWithoutAfterTemplate {
" int before(int b, int a, int d, int c) {", @BeforeTemplate
" return b + a + d + b + c;", int before(int b, int a, int d, int c) {
" }", return b + a + d + b + c;
" }", }
"", }
" class UnsortedParametersWithMultipleMethodsAndParameterCounts {",
" @BeforeTemplate", class UnsortedParametersWithMultipleMethodsAndParameterCounts {
" int before(int d, int a, int f, int b, int g) {", @BeforeTemplate
" return f + a + g + b + d;", int before(int d, int a, int f, int b, int g) {
" }", return f + a + g + b + d;
"", }
" @AfterTemplate",
" int after(int a, int b) {", @AfterTemplate
" return b + a;", int after(int a, int b) {
" }", return b + a;
"", }
" @AfterTemplate",
" int after2(int d, int a, int f) {", @AfterTemplate
" return d + a + f;", int after2(int d, int a, int f) {
" }", return d + a + f;
" }", }
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -11,121 +11,129 @@ final class RefasterRuleModifiersTest {
CompilationTestHelper.newInstance(RefasterRuleModifiers.class, getClass()) CompilationTestHelper.newInstance(RefasterRuleModifiers.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"final class A {",
" @BeforeTemplate", final class A {
" String before(String str) {", @BeforeTemplate
" return str;", String before(String str) {
" }", return str;
"", }
" String nonRefasterMethod(String str) {",
" return str;", String nonRefasterMethod(String str) {
" }", return str;
"", }
" static final class Inner {",
" @BeforeTemplate", static final class Inner {
" String before(String str) {", @BeforeTemplate
" return str;", String before(String str) {
" }", return str;
" }", }
"}") }
}
""")
.addSourceLines( .addSourceLines(
"B.java", "B.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"import com.google.errorprone.refaster.annotation.Placeholder;", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"", import com.google.errorprone.refaster.annotation.Placeholder;
"abstract class B<I, O> {",
" @Placeholder", abstract class B<I, O> {
" abstract O someFunction(I input);", @Placeholder
"", abstract O someFunction(I input);
" @BeforeTemplate",
" String before(I input) {", @BeforeTemplate
" return String.valueOf(someFunction(input));", String before(I input) {
" }", return String.valueOf(someFunction(input));
"", }
" abstract static class Inner<I, O> {",
" @Placeholder", abstract static class Inner<I, O> {
" abstract O someFunction(I input);", @Placeholder
"", abstract O someFunction(I input);
" @BeforeTemplate",
" String before(I input) {", @BeforeTemplate
" return String.valueOf(someFunction(input));", String before(I input) {
" }", return String.valueOf(someFunction(input));
" }", }
"}") }
}
""")
.addSourceLines( .addSourceLines(
"C.java", "C.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"// BUG: Diagnostic contains:",
"class C {", // BUG: Diagnostic contains:
" @BeforeTemplate", class C {
" // BUG: Diagnostic contains:", @BeforeTemplate
" final String beforeFinal(String str) {", // BUG: Diagnostic contains:
" return str;", final String beforeFinal(String str) {
" }", return str;
"", }
" @BeforeTemplate",
" // BUG: Diagnostic contains:", @BeforeTemplate
" private String beforePrivate(String str) {", // BUG: Diagnostic contains:
" return str;", private String beforePrivate(String str) {
" }", return str;
"", }
" @BeforeTemplate",
" // BUG: Diagnostic contains:", @BeforeTemplate
" public String beforePublic(String str) {", // BUG: Diagnostic contains:
" return str;", public String beforePublic(String str) {
" }", return str;
"", }
" @BeforeTemplate",
" // BUG: Diagnostic contains:", @BeforeTemplate
" static String beforeStatic(String str) {", // BUG: Diagnostic contains:
" return str;", static String beforeStatic(String str) {
" }", return str;
"", }
" @BeforeTemplate",
" // BUG: Diagnostic contains:", @BeforeTemplate
" synchronized String beforeSynchronized(String str) {", // BUG: Diagnostic contains:
" return str;", synchronized String beforeSynchronized(String str) {
" }", return str;
"", }
" // BUG: Diagnostic contains:",
" abstract static class AbstractInner {", // BUG: Diagnostic contains:
" @BeforeTemplate", abstract static class AbstractInner {
" String before(String str) {", @BeforeTemplate
" return str;", String before(String str) {
" }", return str;
" }", }
"", }
" // BUG: Diagnostic contains:",
" static class NonFinalInner {", // BUG: Diagnostic contains:
" @BeforeTemplate", static class NonFinalInner {
" String before(String str) {", @BeforeTemplate
" return str;", String before(String str) {
" }", return str;
" }", }
"", }
" // BUG: Diagnostic contains:",
" final class NonStaticInner {", // BUG: Diagnostic contains:
" @BeforeTemplate", final class NonStaticInner {
" String before(String str) {", @BeforeTemplate
" return str;", String before(String str) {
" }", return str;
" }", }
"}") }
}
""")
.addSourceLines( .addSourceLines(
"D.java", "D.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"// BUG: Diagnostic contains:",
"abstract class D {", // BUG: Diagnostic contains:
" @BeforeTemplate", abstract class D {
" // BUG: Diagnostic contains:", @BeforeTemplate
" protected String beforeProtected(String str) {", // BUG: Diagnostic contains:
" return str;", protected String beforeProtected(String str) {
" }", return str;
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -134,70 +142,78 @@ final class RefasterRuleModifiersTest {
BugCheckerRefactoringTestHelper.newInstance(RefasterRuleModifiers.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(RefasterRuleModifiers.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"class A {",
" @BeforeTemplate", class A {
" private static String before(String str) {", @BeforeTemplate
" return str;", private static String before(String str) {
" }", return str;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"final class A {",
" @BeforeTemplate", final class A {
" String before(String str) {", @BeforeTemplate
" return str;", String before(String str) {
" }", return str;
"}") }
}
""")
.addInputLines( .addInputLines(
"B.java", "B.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"import com.google.errorprone.refaster.annotation.Placeholder;", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"", import com.google.errorprone.refaster.annotation.Placeholder;
"final class B {",
" abstract class WithoutPlaceholder {", final class B {
" @BeforeTemplate", abstract class WithoutPlaceholder {
" protected synchronized String before(String str) {", @BeforeTemplate
" return str;", protected synchronized String before(String str) {
" }", return str;
" }", }
"", }
" abstract class WithPlaceholder<I, O> {",
" @Placeholder", abstract class WithPlaceholder<I, O> {
" public abstract O someFunction(I input);", @Placeholder
"", public abstract O someFunction(I input);
" @BeforeTemplate",
" public final String before(I input) {", @BeforeTemplate
" return String.valueOf(someFunction(input));", public final String before(I input) {
" }", return String.valueOf(someFunction(input));
" }", }
"}") }
}
""")
.addOutputLines( .addOutputLines(
"B.java", "B.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;", """
"import com.google.errorprone.refaster.annotation.Placeholder;", import com.google.errorprone.refaster.annotation.BeforeTemplate;
"", import com.google.errorprone.refaster.annotation.Placeholder;
"final class B {",
" static final class WithoutPlaceholder {", final class B {
" @BeforeTemplate", static final class WithoutPlaceholder {
" String before(String str) {", @BeforeTemplate
" return str;", String before(String str) {
" }", return str;
" }", }
"", }
" abstract static class WithPlaceholder<I, O> {",
" @Placeholder", abstract static class WithPlaceholder<I, O> {
" abstract O someFunction(I input);", @Placeholder
"", abstract O someFunction(I input);
" @BeforeTemplate",
" String before(I input) {", @BeforeTemplate
" return String.valueOf(someFunction(input));", String before(I input) {
" }", return String.valueOf(someFunction(input));
" }", }
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -18,62 +18,64 @@ final class TestHelperSourceFormatTest {
CompilationTestHelper.newInstance(TestHelperSourceFormat.class, getClass()) CompilationTestHelper.newInstance(TestHelperSourceFormat.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
"import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;", import com.google.errorprone.CompilationTestHelper;
"", import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;
"class A {",
" void m() {", class A {
" CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())", void m() {
" // BUG: Diagnostic contains: No source code provided", CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" .addSourceLines(\"A.java\")", // BUG: Diagnostic contains: No source code provided
" // BUG: Diagnostic contains: Source code is malformed:", .addSourceLines("A.java")
" .addSourceLines(\"B.java\", \"class B {\")", // BUG: Diagnostic contains: Source code is malformed:
" // BUG: Diagnostic contains: Test code should be specified using a single text block", .addSourceLines("B.java", "class B {")
" .addSourceLines(\"C.java\", \"class C {}\")", // BUG: Diagnostic contains: Test code should be specified using a single text block
" // Malformed code, but not compile-time constant, so not flagged.", .addSourceLines("C.java", "class C {}")
" .addSourceLines(\"D.java\", \"class D {\" + getClass())", // Malformed code, but not compile-time constant, so not flagged.
" // BUG: Diagnostic contains: Test code should follow the Google Java style", .addSourceLines("D.java", "class D {" + getClass())
" .addSourceLines(\"E.java\", \"class E { }\")", // BUG: Diagnostic contains: Test code should follow the Google Java style
" // Well-formed code, so not flagged.", .addSourceLines("E.java", "class E { }")
" .addSourceLines(", // Well-formed code, so not flagged.
" \"F.java\",", .addSourceLines(
" \"\"\"", "F.java",
" class F {}", ""\"
" \"\"\")", class F {}
" // BUG: Diagnostic contains: Test code should follow the Google Java style (pay attention to", ""\")
" // trailing newlines)", // BUG: Diagnostic contains: Test code should follow the Google Java style (pay attention to
" .addSourceLines(", // trailing newlines)
" \"G.java\",", .addSourceLines(
" \"\"\"", "G.java",
" class G {}\"\"\")", ""\"
" .doTest();", class G {}""\")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())",
" // BUG: Diagnostic contains: Test code should follow the Google Java style", BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" .addInputLines(\"in/A.java\", \"class A { }\")", // BUG: Diagnostic contains: Test code should follow the Google Java style
" // BUG: Diagnostic contains: Test code should follow the Google Java style", .addInputLines("in/A.java", "class A { }")
" .addOutputLines(\"out/A.java\", \"class A { }\")", // BUG: Diagnostic contains: Test code should follow the Google Java style
" // BUG: Diagnostic contains: Test code should follow the Google Java style", .addOutputLines("out/A.java", "class A { }")
" .addInputLines(", // BUG: Diagnostic contains: Test code should follow the Google Java style
" \"in/B.java\",", .addInputLines(
" \"\"\"", "in/B.java",
" import java.util.Map;", ""\"
"", import java.util.Map;
" class B {}",
" \"\"\")", class B {}
" // Unused import, but in an output file, so not flagged.", ""\")
" .addOutputLines(", // Unused import, but in an output file, so not flagged.
" \"out/B.java\",", .addOutputLines(
" \"\"\"", "out/B.java",
" import java.util.Map;", ""\"
"", import java.util.Map;
" class B {}",
" \"\"\")", class B {}
" .doTest(TestMode.TEXT_MATCH);", ""\")
" }", .doTest(TestMode.TEXT_MATCH);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -84,47 +86,49 @@ final class TestHelperSourceFormatTest {
.setArgs("-XepOpt:TestHelperSourceFormat:AvoidTextBlocks=true") .setArgs("-XepOpt:TestHelperSourceFormat:AvoidTextBlocks=true")
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
"import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;", import com.google.errorprone.CompilationTestHelper;
"", import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;
"class A {",
" void m() {", class A {
" CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())", void m() {
" // BUG: Diagnostic contains: No source code provided", CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" .addSourceLines(\"A.java\")", // BUG: Diagnostic contains: No source code provided
" // BUG: Diagnostic contains: Source code is malformed:", .addSourceLines("A.java")
" .addSourceLines(\"B.java\", \"class B {\")", // BUG: Diagnostic contains: Source code is malformed:
" // Well-formed code, so not flagged.", .addSourceLines("B.java", "class B {")
" .addSourceLines(\"C.java\", \"class C {}\")", // Well-formed code, so not flagged.
" // Malformed code, but not compile-time constant, so not flagged.", .addSourceLines("C.java", "class C {}")
" .addSourceLines(\"D.java\", \"class D {\" + getClass())", // Malformed code, but not compile-time constant, so not flagged.
" // BUG: Diagnostic contains: Test code should follow the Google Java style", .addSourceLines("D.java", "class D {" + getClass())
" .addSourceLines(\"E.java\", \"class E { }\")", // BUG: Diagnostic contains: Test code should follow the Google Java style
" // BUG: Diagnostic contains: Test code should not be specified using a single text block", .addSourceLines("E.java", "class E { }")
" .addSourceLines(", // BUG: Diagnostic contains: Test code should not be specified using a single text block
" \"F.java\",", .addSourceLines(
" \"\"\"", "F.java",
" class F {}", ""\"
" \"\"\")", class F {}
" // BUG: Diagnostic contains: Test code should follow the Google Java style (pay attention to", ""\")
" // trailing newlines)", // BUG: Diagnostic contains: Test code should follow the Google Java style (pay attention to
" .addSourceLines(\"G.java\", \"class G {}\", \"\")", // trailing newlines)
" .doTest();", .addSourceLines("G.java", "class G {}", "")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())",
" // BUG: Diagnostic contains: Test code should follow the Google Java style", BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" .addInputLines(\"A.java\", \"class A { }\")", // BUG: Diagnostic contains: Test code should follow the Google Java style
" // BUG: Diagnostic contains: Test code should follow the Google Java style", .addInputLines("A.java", "class A { }")
" .addOutputLines(\"A.java\", \"class A { }\")", // BUG: Diagnostic contains: Test code should follow the Google Java style
" // BUG: Diagnostic contains: Test code should follow the Google Java style", .addOutputLines("A.java", "class A { }")
" .addInputLines(\"B.java\", \"import java.util.Map;\", \"\", \"class B {}\")", // BUG: Diagnostic contains: Test code should follow the Google Java style
" // Unused import, but in an output file, so not flagged.", .addInputLines("B.java", "import java.util.Map;", "", "class B {}")
" .addOutputLines(\"B.java\", \"import java.util.Map;\", \"\", \"class B {}\")", // Unused import, but in an output file, so not flagged.
" .doTest(TestMode.TEXT_MATCH);", .addOutputLines("B.java", "import java.util.Map;", "", "class B {}")
" }", .doTest(TestMode.TEXT_MATCH);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -140,91 +144,95 @@ final class TestHelperSourceFormatTest {
BugCheckerRefactoringTestHelper.newInstance(TestHelperSourceFormat.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(TestHelperSourceFormat.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
"import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;", import com.google.errorprone.CompilationTestHelper;
"", import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;
"class A {",
" void m() {", class A {
" CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())", void m() {
" .addSourceLines(", CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" \"A.java\",", .addSourceLines(
" \"\"\"", "A.java",
" import java.util.Map;", ""\"
" import java.util.Collection;", import java.util.Map;
" import java.util.List;", import java.util.Collection;
"", import java.util.List;
" interface A extends List<A>, Map<A,A> { }\"\"\")",
" .addSourceLines(\"B.java\", \"class B {}\")", interface A extends List<A>, Map<A,A> { }""\")
" .doTest();", .addSourceLines("B.java", "class B {}")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())",
" .addInputLines(", BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" \"in/A.java\",", .addInputLines(
" \"\"\"", "in/A.java",
" import java.util.Map;", ""\"
" import java.util.Collection;", import java.util.Map;
" import java.util.List;", import java.util.Collection;
"", import java.util.List;
" interface A extends List<A>, Map<A,A> { }\"\"\")",
" .addOutputLines(", interface A extends List<A>, Map<A,A> { }""\")
" \"out/A.java\",", .addOutputLines(
" \"\"\"", "out/A.java",
" import java.util.Map;", ""\"
" import java.util.Collection;", import java.util.Map;
" import java.util.List;", import java.util.Collection;
"", import java.util.List;
" interface A extends List<A>, Map<A,A> { }\"\"\")",
" .doTest(TestMode.TEXT_MATCH);", interface A extends List<A>, Map<A,A> { }""\")
" }", .doTest(TestMode.TEXT_MATCH);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"out/A.java", "out/A.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
"import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;", import com.google.errorprone.CompilationTestHelper;
"", import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;
"class A {",
" void m() {", class A {
" CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())", void m() {
" .addSourceLines(", CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" \"A.java\",", .addSourceLines(
" \"\"\"", "A.java",
" import java.util.List;", ""\"
" import java.util.Map;", import java.util.List;
"", import java.util.Map;
" interface A extends List<A>, Map<A, A> {}",
" \"\"\")", interface A extends List<A>, Map<A, A> {}
" .addSourceLines(", ""\")
" \"B.java\",", .addSourceLines(
" \"\"\"", "B.java",
" class B {}", ""\"
" \"\"\")", class B {}
" .doTest();", ""\")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())",
" .addInputLines(", BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" \"in/A.java\",", .addInputLines(
" \"\"\"", "in/A.java",
" import java.util.List;", ""\"
" import java.util.Map;", import java.util.List;
"", import java.util.Map;
" interface A extends List<A>, Map<A, A> {}",
" \"\"\")", interface A extends List<A>, Map<A, A> {}
" .addOutputLines(", ""\")
" \"out/A.java\",", .addOutputLines(
" \"\"\"", "out/A.java",
" import java.util.Collection;", ""\"
" import java.util.List;", import java.util.Collection;
" import java.util.Map;", import java.util.List;
"", import java.util.Map;
" interface A extends List<A>, Map<A, A> {}",
" \"\"\")", interface A extends List<A>, Map<A, A> {}
" .doTest(TestMode.TEXT_MATCH);", ""\")
" }", .doTest(TestMode.TEXT_MATCH);
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -238,76 +246,80 @@ final class TestHelperSourceFormatTest {
.setArgs("-XepOpt:TestHelperSourceFormat:AvoidTextBlocks=true") .setArgs("-XepOpt:TestHelperSourceFormat:AvoidTextBlocks=true")
.addInputLines( .addInputLines(
"in/A.java", "in/A.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
"import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;", import com.google.errorprone.CompilationTestHelper;
"", import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;
"class A {",
" void m() {", class A {
" CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())", void m() {
" .addSourceLines(", CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" \"A.java\",", .addSourceLines(
" \"import java.util.Map;\",", "A.java",
" \"import java.util.Collection;\",", "import java.util.Map;",
" \"import java.util.List;\",", "import java.util.Collection;",
" \"\",", "import java.util.List;",
" \"interface A extends List<A>, Map<A,A> { }\")", "",
" .doTest();", "interface A extends List<A>, Map<A,A> { }")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())",
" .addInputLines(", BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" \"A.java\",", .addInputLines(
" \"import java.util.Map;\",", "A.java",
" \"import java.util.Collection;\",", "import java.util.Map;",
" \"import java.util.List;\",", "import java.util.Collection;",
" \"\",", "import java.util.List;",
" \"interface A extends List<A>, Map<A,A> { }\")", "",
" .addOutputLines(", "interface A extends List<A>, Map<A,A> { }")
" \"A.java\",", .addOutputLines(
" \"import java.util.Map;\",", "A.java",
" \"import java.util.Collection;\",", "import java.util.Map;",
" \"import java.util.List;\",", "import java.util.Collection;",
" \"\",", "import java.util.List;",
" \"interface A extends List<A>, Map<A,A> { }\")", "",
" .doTest(TestMode.TEXT_MATCH);", "interface A extends List<A>, Map<A,A> { }")
" }", .doTest(TestMode.TEXT_MATCH);
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;", """
"import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;", import com.google.errorprone.BugCheckerRefactoringTestHelper;
"import com.google.errorprone.CompilationTestHelper;", import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
"import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;", import com.google.errorprone.CompilationTestHelper;
"", import tech.picnic.errorprone.guidelines.bugpatterns.RefasterAnyOfUsage;
"class A {",
" void m() {", class A {
" CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())", void m() {
" .addSourceLines(", CompilationTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" \"A.java\",", .addSourceLines(
" \"import java.util.List;\",", "A.java",
" \"import java.util.Map;\",", "import java.util.List;",
" \"\",", "import java.util.Map;",
" \"interface A extends List<A>, Map<A, A> {}\")", "",
" .doTest();", "interface A extends List<A>, Map<A, A> {}")
"", .doTest();
" BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())",
" .addInputLines(", BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsage.class, getClass())
" \"A.java\",", .addInputLines(
" \"import java.util.List;\",", "A.java",
" \"import java.util.Map;\",", "import java.util.List;",
" \"\",", "import java.util.Map;",
" \"interface A extends List<A>, Map<A, A> {}\")", "",
" .addOutputLines(", "interface A extends List<A>, Map<A, A> {}")
" \"A.java\",", .addOutputLines(
" \"import java.util.Collection;\",", "A.java",
" \"import java.util.List;\",", "import java.util.Collection;",
" \"import java.util.Map;\",", "import java.util.List;",
" \"\",", "import java.util.Map;",
" \"interface A extends List<A>, Map<A, A> {}\")", "",
" .doTest(TestMode.TEXT_MATCH);", "interface A extends List<A>, Map<A, A> {}")
" }", .doTest(TestMode.TEXT_MATCH);
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -19,26 +19,28 @@ final class UnqualifiedSuggestedFixImportTest {
"Prefer `SuggestedFixes#qualifyStaticImport` over direct invocation of `SuggestedFix.Builder#addStaticImport`")) "Prefer `SuggestedFixes#qualifyStaticImport` over direct invocation of `SuggestedFix.Builder#addStaticImport`"))
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.errorprone.fixes.SuggestedFix;", """
"", import com.google.errorprone.fixes.SuggestedFix;
"class A {",
" void m() {", class A {
" System.out.println(\"foo\");", void m() {
" addImport(\"bar\");", System.out.println("foo");
" addStaticImport(\"baz\");", addImport("bar");
"", addStaticImport("baz");
" SuggestedFix.Builder builder = SuggestedFix.builder();",
" // BUG: Diagnostic matches: IMPORT", SuggestedFix.Builder builder = SuggestedFix.builder();
" builder.addImport(\"java.lang.String\");", // BUG: Diagnostic matches: IMPORT
" // BUG: Diagnostic matches: STATIC_IMPORT", builder.addImport("java.lang.String");
" builder.addStaticImport(\"java.lang.String.toString\");", // BUG: Diagnostic matches: STATIC_IMPORT
" builder.build();", builder.addStaticImport("java.lang.String.toString");
" }", builder.build();
"", }
" private void addImport(String s) {}",
"", private void addImport(String s) {}
" private void addStaticImport(String s) {}",
"}") private void addStaticImport(String s) {}
}
""")
.doTest(); .doTest();
} }
} }

View File

@@ -19,64 +19,66 @@ final class ConflictDetectionTest {
CompilationTestHelper.newInstance(RenameBlockerFlagger.class, getClass()) CompilationTestHelper.newInstance(RenameBlockerFlagger.class, getClass())
.addSourceLines( .addSourceLines(
"pkg/A.java", "pkg/A.java",
"package pkg;", """
"", package pkg;
"import static pkg.A.StaticType.method3t;",
"import static pkg.A.StaticType.method4t;", import static pkg.A.StaticType.method3t;
"", import static pkg.A.StaticType.method4t;
"import pkg.A.method4t;",
"", import pkg.A.method4t;
"class A {",
" void method1() {", class A {
" method4(method4t.class);", void method1() {
" }", method4(method4t.class);
"", }
" // BUG: Diagnostic contains: a method named `method2t` is already defined in this class or a",
" // supertype", // BUG: Diagnostic contains: a method named `method2t` is already defined in this class or a
" void method2() {}", // supertype
"", void method2() {}
" void method2t() {}",
"", void method2t() {}
" // BUG: Diagnostic contains: another method named `method3t` is in scope",
" void method3() {}", // BUG: Diagnostic contains: another method named `method3t` is in scope
"", void method3() {}
" void method4(Object o) {}",
"", void method4(Object o) {}
" // BUG: Diagnostic contains: `int` is not a valid identifier",
" void in() {}", // BUG: Diagnostic contains: `int` is not a valid identifier
"", void in() {}
" class InstanceType {",
" void m() {", class InstanceType {
" System.out.println(method3t());", void m() {
" }", System.out.println(method3t());
" }", }
"", }
" static class StaticType {",
" static int method3t() {", static class StaticType {
" return 0;", static int method3t() {
" }", return 0;
"", }
" static void method4t() {",
" method4t();", static void method4t() {
" }", method4t();
" }", }
"", }
" record RecordType() {",
" void m() {", record RecordType() {
" method4t();", void m() {
" }", method4t();
" }", }
"", }
" enum EnumType {",
" ELEM;", enum EnumType {
"", ELEM;
" void m() {",
" method4t();", void m() {
" }", method4t();
" }", }
"", }
" class method4t {}",
"}") class method4t {}
}
""")
.doTest(); .doTest();
} }

View File

@@ -51,153 +51,165 @@ final class MethodMatcherFactoryTest {
CompilationTestHelper.newInstance(MatchedMethodsFlagger.class, getClass()) CompilationTestHelper.newInstance(MatchedMethodsFlagger.class, getClass())
.addSourceLines( .addSourceLines(
"com/example/A.java", "com/example/A.java",
"package com.example;", """
"", package com.example;
"public class A {",
" public void m1() {}", public class A {
"", public void m1() {}
" public void m1(String s) {}",
"", public void m1(String s) {}
" public void m1(int i, int j) {}",
"", public void m1(int i, int j) {}
" public void m2() {}",
"", public void m2() {}
" public void m2(String s) {}",
"", public void m2(String s) {}
" public void m2(int i, int j) {}",
"", public void m2(int i, int j) {}
" public void m3() {}",
"", public void m3() {}
" public void m3(String s) {}",
"", public void m3(String s) {}
" public void m3(int i, int j) {}",
"}") public void m3(int i, int j) {}
}
""")
.addSourceLines( .addSourceLines(
"com/example/B.java", "com/example/B.java",
"package com.example;", """
"", package com.example;
"public class B {",
" public void m1() {}", public class B {
"", public void m1() {}
" public void m1(String s) {}",
"", public void m1(String s) {}
" public void m1(int i, int j) {}",
"", public void m1(int i, int j) {}
" public void m2() {}",
"", public void m2() {}
" public void m2(String s) {}",
"", public void m2(String s) {}
" public void m2(int i, int j) {}",
"", public void m2(int i, int j) {}
" public void m3() {}",
"", public void m3() {}
" public void m3(String s) {}",
"", public void m3(String s) {}
" public void m3(int i, int j) {}",
"}") public void m3(int i, int j) {}
}
""")
.addSourceLines( .addSourceLines(
"com/example/sub/A.java", "com/example/sub/A.java",
"package com.example.sub;", """
"", package com.example.sub;
"public class A {",
" public static void m1() {}", public class A {
"", public static void m1() {}
" public static void m1(String s) {}",
"", public static void m1(String s) {}
" public static void m1(int i, int j) {}",
"", public static void m1(int i, int j) {}
" public static void m2() {}",
"", public static void m2() {}
" public static void m2(String s) {}",
"", public static void m2(String s) {}
" public static void m2(int i, int j) {}",
"", public static void m2(int i, int j) {}
" public static void m3() {}",
"", public static void m3() {}
" public static void m3(String s) {}",
"", public static void m3(String s) {}
" public static void m3(int i, int j) {}",
"}") public static void m3(int i, int j) {}
}
""")
.addSourceLines( .addSourceLines(
"com/example/sub/B.java", "com/example/sub/B.java",
"package com.example.sub;", """
"", package com.example.sub;
"public class B {",
" public static void m1() {}", public class B {
"", public static void m1() {}
" public static void m1(String s) {}",
"", public static void m1(String s) {}
" public static void m1(int i, int j) {}",
"", public static void m1(int i, int j) {}
" public static void m2() {}",
"", public static void m2() {}
" public static void m2(String s) {}",
"", public static void m2(String s) {}
" public static void m2(int i, int j) {}",
"", public static void m2(int i, int j) {}
" public static void m3() {}",
"", public static void m3() {}
" public static void m3(String s) {}",
"", public static void m3(String s) {}
" public static void m3(int i, int j) {}",
"}") public static void m3(int i, int j) {}
}
""")
.addSourceLines( .addSourceLines(
"External.java", "External.java",
"import com.example.A;", """
"import com.example.sub.B;", import com.example.A;
"", import com.example.sub.B;
"public class External {",
" void invocations() {", public class External {
" // BUG: Diagnostic contains:", void invocations() {
" new A().m1();", // BUG: Diagnostic contains:
" new A().m1(\"\");", new A().m1();
" new A().m1(0, 0);", new A().m1("");
" new A().m2();", new A().m1(0, 0);
" // BUG: Diagnostic contains:", new A().m2();
" new A().m2(\"\");", // BUG: Diagnostic contains:
" new A().m2(0, 0);", new A().m2("");
" new A().m3();", new A().m2(0, 0);
" new A().m3(\"\");", new A().m3();
" new A().m3(0, 0);", new A().m3("");
" B.m1();", new A().m3(0, 0);
" B.m1(\"\");", B.m1();
" B.m1(0, 0);", B.m1("");
" B.m2();", B.m1(0, 0);
" B.m2(\"\");", B.m2();
" B.m2(0, 0);", B.m2("");
" B.m3();", B.m2(0, 0);
" B.m3(\"\");", B.m3();
" // BUG: Diagnostic contains:", B.m3("");
" B.m3(0, 0);", // BUG: Diagnostic contains:
" }", B.m3(0, 0);
"}") }
}
""")
.addSourceLines( .addSourceLines(
"ExternalWithDifferentPackages.java", "ExternalWithDifferentPackages.java",
"import com.example.B;", """
"import com.example.sub.A;", import com.example.B;
"", import com.example.sub.A;
"public class ExternalWithDifferentPackages {",
" void invocations() {", public class ExternalWithDifferentPackages {
" A.m1();", void invocations() {
" A.m1(\"\");", A.m1();
" A.m1(0, 0);", A.m1("");
" A.m2();", A.m1(0, 0);
" A.m2(\"\");", A.m2();
" A.m2(0, 0);", A.m2("");
" A.m3();", A.m2(0, 0);
" A.m3(\"\");", A.m3();
" A.m3(0, 0);", A.m3("");
" new B().m1();", A.m3(0, 0);
" new B().m1(\"\");", new B().m1();
" new B().m1(0, 0);", new B().m1("");
" new B().m2();", new B().m1(0, 0);
" new B().m2(\"\");", new B().m2();
" new B().m2(0, 0);", new B().m2("");
" new B().m3();", new B().m2(0, 0);
" new B().m3(\"\");", new B().m3();
" new B().m3(0, 0);", new B().m3("");
" }", new B().m3(0, 0);
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -30,24 +30,26 @@ final class MoreASTHelpersTest {
CompilationTestHelper.newInstance(FindMethodsTestChecker.class, getClass()) CompilationTestHelper.newInstance(FindMethodsTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" // BUG: Diagnostic contains: {foo=1, bar=2, baz=0}", class A {
" void foo() {}", // BUG: Diagnostic contains: {foo=1, bar=2, baz=0}
"", void foo() {}
" // BUG: Diagnostic contains: {foo=1, bar=2, baz=0}",
" void bar() {}", // BUG: Diagnostic contains: {foo=1, bar=2, baz=0}
"", void bar() {}
" // BUG: Diagnostic contains: {foo=1, bar=2, baz=0}",
" void bar(int i) {}", // BUG: Diagnostic contains: {foo=1, bar=2, baz=0}
"", void bar(int i) {}
" static class B {",
" // BUG: Diagnostic contains: {foo=0, bar=1, baz=1}", static class B {
" void bar() {}", // BUG: Diagnostic contains: {foo=0, bar=1, baz=1}
"", void bar() {}
" // BUG: Diagnostic contains: {foo=0, bar=1, baz=1}",
" void baz() {}", // BUG: Diagnostic contains: {foo=0, bar=1, baz=1}
" }", void baz() {}
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -56,24 +58,26 @@ final class MoreASTHelpersTest {
CompilationTestHelper.newInstance(MethodExistsTestChecker.class, getClass()) CompilationTestHelper.newInstance(MethodExistsTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" // BUG: Diagnostic contains: {foo=true, bar=true, baz=false}", class A {
" void foo() {}", // BUG: Diagnostic contains: {foo=true, bar=true, baz=false}
"", void foo() {}
" // BUG: Diagnostic contains: {foo=true, bar=true, baz=false}",
" void bar() {}", // BUG: Diagnostic contains: {foo=true, bar=true, baz=false}
"", void bar() {}
" // BUG: Diagnostic contains: {foo=true, bar=true, baz=false}",
" void bar(int i) {}", // BUG: Diagnostic contains: {foo=true, bar=true, baz=false}
"", void bar(int i) {}
" static class B {",
" // BUG: Diagnostic contains: {foo=false, bar=true, baz=true}", static class B {
" void bar() {}", // BUG: Diagnostic contains: {foo=false, bar=true, baz=true}
"", void bar() {}
" // BUG: Diagnostic contains: {foo=false, bar=true, baz=true}",
" void baz() {}", // BUG: Diagnostic contains: {foo=false, bar=true, baz=true}
" }", void baz() {}
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -82,42 +86,44 @@ final class MoreASTHelpersTest {
CompilationTestHelper.newInstance(FindMethodReturnTestChecker.class, getClass()) CompilationTestHelper.newInstance(FindMethodReturnTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.stream.Stream;", """
"", import java.util.stream.Stream;
"class A {",
" {", class A {
" toString();", {
" }", toString();
"", }
" String topLevelMethod() {",
" // BUG: Diagnostic contains: topLevelMethod", String topLevelMethod() {
" toString();", // BUG: Diagnostic contains: topLevelMethod
" // BUG: Diagnostic contains: topLevelMethod", toString();
" return toString();", // BUG: Diagnostic contains: topLevelMethod
" }", return toString();
"", }
" Stream<String> anotherMethod() {",
" // BUG: Diagnostic contains: anotherMethod", Stream<String> anotherMethod() {
" return Stream.of(1)", // BUG: Diagnostic contains: anotherMethod
" .map(", return Stream.of(1)
" n -> {", .map(
" toString();", n -> {
" return toString();", toString();
" });", return toString();
" }", });
"", }
" void recursiveMethod(Runnable r) {",
" // BUG: Diagnostic contains: recursiveMethod", void recursiveMethod(Runnable r) {
" recursiveMethod(", // BUG: Diagnostic contains: recursiveMethod
" new Runnable() {", recursiveMethod(
" @Override", new Runnable() {
" public void run() {", @Override
" // BUG: Diagnostic contains: run", public void run() {
" toString();", // BUG: Diagnostic contains: run
" }", toString();
" });", }
" }", });
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -126,17 +132,19 @@ final class MoreASTHelpersTest {
CompilationTestHelper.newInstance(AreSameTypeTestChecker.class, getClass()) CompilationTestHelper.newInstance(AreSameTypeTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" void negative1(String a, Integer b) {}", class A {
"", void negative1(String a, Integer b) {}
" void negative2(Integer a, Number b) {}",
"", void negative2(Integer a, Number b) {}
" // BUG: Diagnostic contains:",
" void positive1(String a, String b) {}", // BUG: Diagnostic contains:
"", void positive1(String a, String b) {}
" // BUG: Diagnostic contains:",
" void positive2(Iterable<String> a, Iterable<Integer> b) {}", // BUG: Diagnostic contains:
"}") void positive2(Iterable<String> a, Iterable<Integer> b) {}
}
""")
.doTest(); .doTest();
} }
@@ -145,17 +153,19 @@ final class MoreASTHelpersTest {
CompilationTestHelper.newInstance(IsStringTypedTestChecker.class, getClass()) CompilationTestHelper.newInstance(IsStringTypedTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" int foo = 1;", void m() {
" // BUG: Diagnostic contains:", int foo = 1;
" String s = \"foo\";", // BUG: Diagnostic contains:
"", String s = "foo";
" hashCode();",
" // BUG: Diagnostic contains:", hashCode();
" toString();", // BUG: Diagnostic contains:
" }", toString();
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -27,56 +27,58 @@ final class MoreJUnitMatchersTest {
CompilationTestHelper.newInstance(MethodMatchersTestChecker.class, getClass()) CompilationTestHelper.newInstance(MethodMatchersTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import static org.junit.jupiter.params.provider.Arguments.arguments;", """
"", import static org.junit.jupiter.params.provider.Arguments.arguments;
"import java.util.stream.Stream;",
"import org.junit.jupiter.api.AfterAll;", import java.util.stream.Stream;
"import org.junit.jupiter.api.AfterEach;", import org.junit.jupiter.api.AfterAll;
"import org.junit.jupiter.api.BeforeAll;", import org.junit.jupiter.api.AfterEach;
"import org.junit.jupiter.api.BeforeEach;", import org.junit.jupiter.api.BeforeAll;
"import org.junit.jupiter.api.RepeatedTest;", import org.junit.jupiter.api.BeforeEach;
"import org.junit.jupiter.api.Test;", import org.junit.jupiter.api.RepeatedTest;
"import org.junit.jupiter.params.ParameterizedTest;", import org.junit.jupiter.api.Test;
"import org.junit.jupiter.params.provider.Arguments;", import org.junit.jupiter.params.ParameterizedTest;
"import org.junit.jupiter.params.provider.MethodSource;", import org.junit.jupiter.params.provider.Arguments;
"", import org.junit.jupiter.params.provider.MethodSource;
"class A {",
" @BeforeAll", class A {
" // BUG: Diagnostic contains: SETUP_OR_TEARDOWN_METHOD", @BeforeAll
" public void beforeAll() {}", // BUG: Diagnostic contains: SETUP_OR_TEARDOWN_METHOD
"", public void beforeAll() {}
" @BeforeEach",
" @Test", @BeforeEach
" // BUG: Diagnostic contains: TEST_METHOD, SETUP_OR_TEARDOWN_METHOD", @Test
" protected void beforeEachAndTest() {}", // BUG: Diagnostic contains: TEST_METHOD, SETUP_OR_TEARDOWN_METHOD
"", protected void beforeEachAndTest() {}
" @AfterEach",
" // BUG: Diagnostic contains: SETUP_OR_TEARDOWN_METHOD", @AfterEach
" private void afterEach() {}", // BUG: Diagnostic contains: SETUP_OR_TEARDOWN_METHOD
"", private void afterEach() {}
" @AfterAll",
" // BUG: Diagnostic contains: SETUP_OR_TEARDOWN_METHOD", @AfterAll
" private void afterAll() {}", // BUG: Diagnostic contains: SETUP_OR_TEARDOWN_METHOD
"", private void afterAll() {}
" @Test",
" // BUG: Diagnostic contains: TEST_METHOD", @Test
" void test() {}", // BUG: Diagnostic contains: TEST_METHOD
"", void test() {}
" private static Stream<Arguments> booleanArgs() {",
" return Stream.of(arguments(false), arguments(true));", private static Stream<Arguments> booleanArgs() {
" }", return Stream.of(arguments(false), arguments(true));
"", }
" @ParameterizedTest",
" @MethodSource(\"booleanArgs\")", @ParameterizedTest
" // BUG: Diagnostic contains: TEST_METHOD, HAS_METHOD_SOURCE", @MethodSource("booleanArgs")
" void parameterizedTest(boolean b) {}", // BUG: Diagnostic contains: TEST_METHOD, HAS_METHOD_SOURCE
"", void parameterizedTest(boolean b) {}
" @RepeatedTest(2)",
" // BUG: Diagnostic contains: TEST_METHOD", @RepeatedTest(2)
" private void repeatedTest() {}", // BUG: Diagnostic contains: TEST_METHOD
"", private void repeatedTest() {}
" private void unannotatedMethod() {}",
"}") private void unannotatedMethod() {}
}
""")
.doTest(); .doTest();
} }
@@ -85,32 +87,34 @@ final class MoreJUnitMatchersTest {
CompilationTestHelper.newInstance(MethodSourceFactoryNamesTestChecker.class, getClass()) CompilationTestHelper.newInstance(MethodSourceFactoryNamesTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import org.junit.jupiter.params.provider.MethodSource;", """
"", import org.junit.jupiter.params.provider.MethodSource;
"class A {",
" @MethodSource", class A {
" // BUG: Diagnostic contains: [matchingMethodSource]", @MethodSource
" void matchingMethodSource(boolean b) {}", // BUG: Diagnostic contains: [matchingMethodSource]
"", void matchingMethodSource(boolean b) {}
" @MethodSource(\"myValueFactory\")",
" // BUG: Diagnostic contains: [myValueFactory]", @MethodSource("myValueFactory")
" void singleCustomMethodSource(boolean b) {}", // BUG: Diagnostic contains: [myValueFactory]
"", void singleCustomMethodSource(boolean b) {}
" @MethodSource({",
" \"nullary()\",", @MethodSource({
" \"nullary()\",", "nullary()",
" \"\",", "nullary()",
" \"withStringParam(java.lang.String)\",", "",
" \"paramsUnspecified\"", "withStringParam(java.lang.String)",
" })", "paramsUnspecified"
" // BUG: Diagnostic contains: [nullary, nullary, multipleMethodSources, withStringParam,", })
" // paramsUnspecified]", // BUG: Diagnostic contains: [nullary, nullary, multipleMethodSources, withStringParam,
" void multipleMethodSources(boolean b) {}", // paramsUnspecified]
"", void multipleMethodSources(boolean b) {}
" @MethodSource({\"foo\", \"()\", \"bar\"})",
" // BUG: Diagnostic contains: [foo, , bar]", @MethodSource({"foo", "()", "bar"})
" void methodSourceWithoutName(boolean b) {}", // BUG: Diagnostic contains: [foo, , bar]
"}") void methodSourceWithoutName(boolean b) {}
}
""")
.doTest(); .doTest();
} }
@@ -119,49 +123,51 @@ final class MoreJUnitMatchersTest {
CompilationTestHelper.newInstance(MethodSourceFactoryDescriptorsTestChecker.class, getClass()) CompilationTestHelper.newInstance(MethodSourceFactoryDescriptorsTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import org.junit.jupiter.params.provider.MethodSource;", """
"", import org.junit.jupiter.params.provider.MethodSource;
"class A {",
" @MethodSource", class A {
" // BUG: Diagnostic contains: [matchingMethodSource]", @MethodSource
" void matchingMethodSource(boolean b) {}", // BUG: Diagnostic contains: [matchingMethodSource]
"", void matchingMethodSource(boolean b) {}
" @MethodSource()",
" // BUG: Diagnostic contains: [matchingMethodSourceWithParens]", @MethodSource()
" void matchingMethodSourceWithParens(boolean b) {}", // BUG: Diagnostic contains: [matchingMethodSourceWithParens]
"", void matchingMethodSourceWithParens(boolean b) {}
" @MethodSource(\"\")",
" // BUG: Diagnostic contains: [matchingMethodSourceMadeExplicit]", @MethodSource("")
" void matchingMethodSourceMadeExplicit(boolean b) {}", // BUG: Diagnostic contains: [matchingMethodSourceMadeExplicit]
"", void matchingMethodSourceMadeExplicit(boolean b) {}
" @MethodSource({\"\"})",
" // BUG: Diagnostic contains: [matchingMethodSourceMadeExplicitWithParens]", @MethodSource({""})
" void matchingMethodSourceMadeExplicitWithParens(boolean b) {}", // BUG: Diagnostic contains: [matchingMethodSourceMadeExplicitWithParens]
"", void matchingMethodSourceMadeExplicitWithParens(boolean b) {}
" @MethodSource({})",
" // BUG: Diagnostic contains: []", @MethodSource({})
" void noMethodSources(boolean b) {}", // BUG: Diagnostic contains: []
"", void noMethodSources(boolean b) {}
" @MethodSource(\"myValueFactory\")",
" // BUG: Diagnostic contains: [myValueFactory]", @MethodSource("myValueFactory")
" void singleCustomMethodSource(boolean b) {}", // BUG: Diagnostic contains: [myValueFactory]
"", void singleCustomMethodSource(boolean b) {}
" @MethodSource({\"firstValueFactory\", \"secondValueFactory\"})",
" // BUG: Diagnostic contains: [firstValueFactory, secondValueFactory]", @MethodSource({"firstValueFactory", "secondValueFactory"})
" void twoCustomMethodSources(boolean b) {}", // BUG: Diagnostic contains: [firstValueFactory, secondValueFactory]
"", void twoCustomMethodSources(boolean b) {}
" @MethodSource({\"myValueFactory\", \"\"})",
" // BUG: Diagnostic contains: [myValueFactory, customAndMatchingMethodSources]", @MethodSource({"myValueFactory", ""})
" void customAndMatchingMethodSources(boolean b) {}", // BUG: Diagnostic contains: [myValueFactory, customAndMatchingMethodSources]
"", void customAndMatchingMethodSources(boolean b) {}
" @MethodSource({\"factory\", \"\", \"factory\", \"\"})",
" // BUG: Diagnostic contains: [factory, repeatedMethodSources, factory, repeatedMethodSources]", @MethodSource({"factory", "", "factory", ""})
" void repeatedMethodSources(boolean b) {}", // BUG: Diagnostic contains: [factory, repeatedMethodSources, factory, repeatedMethodSources]
"", void repeatedMethodSources(boolean b) {}
" @MethodSource({\"nullary()\", \"withStringParam(java.lang.String)\"})",
" // BUG: Diagnostic contains: [nullary(), withStringParam(java.lang.String)]", @MethodSource({"nullary()", "withStringParam(java.lang.String)"})
" void methodSourcesWithParameterSpecification(boolean b) {}", // BUG: Diagnostic contains: [nullary(), withStringParam(java.lang.String)]
"}") void methodSourcesWithParameterSpecification(boolean b) {}
}
""")
.doTest(); .doTest();
} }

View File

@@ -26,32 +26,34 @@ final class MoreMatchersTest {
CompilationTestHelper.newInstance(HasMetaAnnotationTestChecker.class, getClass()) CompilationTestHelper.newInstance(HasMetaAnnotationTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import org.junit.jupiter.api.AfterAll;", """
"import org.junit.jupiter.api.RepeatedTest;", import org.junit.jupiter.api.AfterAll;
"import org.junit.jupiter.api.Test;", import org.junit.jupiter.api.RepeatedTest;
"import org.junit.jupiter.api.TestTemplate;", import org.junit.jupiter.api.Test;
"import org.junit.jupiter.params.ParameterizedTest;", import org.junit.jupiter.api.TestTemplate;
"", import org.junit.jupiter.params.ParameterizedTest;
"class A {",
" void negative1() {}", class A {
"", void negative1() {}
" @Test",
" void negative2() {}", @Test
"", void negative2() {}
" @AfterAll",
" void negative3() {}", @AfterAll
"", void negative3() {}
" @TestTemplate",
" void negative4() {}", @TestTemplate
"", void negative4() {}
" // BUG: Diagnostic contains:",
" @ParameterizedTest", // BUG: Diagnostic contains:
" void positive1() {}", @ParameterizedTest
"", void positive1() {}
" // BUG: Diagnostic contains:",
" @RepeatedTest(2)", // BUG: Diagnostic contains:
" void positive2() {}", @RepeatedTest(2)
"}") void positive2() {}
}
""")
.doTest(); .doTest();
} }
@@ -60,33 +62,35 @@ final class MoreMatchersTest {
CompilationTestHelper.newInstance(IsSubTypeOfTestChecker.class, getClass()) CompilationTestHelper.newInstance(IsSubTypeOfTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableList;
"import com.google.common.collect.ImmutableSortedSet;", import com.google.common.collect.ImmutableSet;
"", import com.google.common.collect.ImmutableSortedSet;
"class A {",
" void m() {", class A {
" ImmutableSet.of(\"foo\");", void m() {
" ImmutableSortedSet.of(\"foo\");", ImmutableSet.of("foo");
" ImmutableList.of(\"foo\");", ImmutableSortedSet.of("foo");
" ImmutableList.of(1);", ImmutableList.of("foo");
" ImmutableList.of(1.0);", ImmutableList.of(1);
" ImmutableList.of((Number) 1);", ImmutableList.of(1.0);
"", ImmutableList.of((Number) 1);
" // BUG: Diagnostic contains:",
" ImmutableSet.of(1);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableSet.of(1);
" ImmutableSet.of(1.0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableSet.of(1.0);
" ImmutableSet.of((Number) 1);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableSet.of((Number) 1);
" ImmutableSortedSet.of(1);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableSortedSet.of(1);
" ImmutableSortedSet.of(1.0);", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", ImmutableSortedSet.of(1.0);
" ImmutableSortedSet.of((Number) 1);", // BUG: Diagnostic contains:
" }", ImmutableSortedSet.of((Number) 1);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -96,11 +100,13 @@ final class MoreMatchersTest {
.withClasspath() .withClasspath()
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" System.out.println(toString());", void m() {
" }", System.out.println(toString());
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -33,91 +33,93 @@ final class MoreTypesTest {
CompilationTestHelper.newInstance(SubtypeFlagger.class, getClass()) CompilationTestHelper.newInstance(SubtypeFlagger.class, getClass())
.addSourceLines( .addSourceLines(
"/A.java", "/A.java",
"import java.util.Collection;", """
"import java.util.List;", import java.util.Collection;
"import java.util.Map;", import java.util.List;
"import java.util.Optional;", import java.util.Map;
"import java.util.Set;", import java.util.Optional;
"", import java.util.Set;
"class A<S, T> {",
" void m() {", class A<S, T> {
" Object object = factory();", void m() {
" A a = factory();", Object object = factory();
"", A a = factory();
" // BUG: Diagnostic contains: [Number, ? super Number, Integer, ? super Integer]",
" int integer = factory();", // BUG: Diagnostic contains: [Number, ? super Number, Integer, ? super Integer]
"", int integer = factory();
" // BUG: Diagnostic contains: [String]",
" String string = factory();", // BUG: Diagnostic contains: [String]
"", String string = factory();
" // BUG: Diagnostic contains: [Optional]",
" Optional rawOptional = factory();", // BUG: Diagnostic contains: [Optional]
" // BUG: Diagnostic contains: [Optional, Optional<?>]", Optional rawOptional = factory();
" Optional<S> optionalOfS = factory();", // BUG: Diagnostic contains: [Optional, Optional<?>]
" // BUG: Diagnostic contains: [Optional, Optional<?>]", Optional<S> optionalOfS = factory();
" Optional<T> optionalOfT = factory();", // BUG: Diagnostic contains: [Optional, Optional<?>]
" // BUG: Diagnostic contains: [Optional, Optional<?>, Optional<Number>]", Optional<T> optionalOfT = factory();
" Optional<Number> optionalOfNumber = factory();", // BUG: Diagnostic contains: [Optional, Optional<?>, Optional<Number>]
" // BUG: Diagnostic contains: [Optional, Optional<?>]", Optional<Number> optionalOfNumber = factory();
" Optional<Integer> optionalOfInteger = factory();", // BUG: Diagnostic contains: [Optional, Optional<?>]
"", Optional<Integer> optionalOfInteger = factory();
" // BUG: Diagnostic contains: [Collection]",
" Collection rawCollection = factory();", // BUG: Diagnostic contains: [Collection]
" // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<Number>, Collection<? super", Collection rawCollection = factory();
" // Number>, Collection<? extends Number>, Collection<? super Integer>]", // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<Number>, Collection<? super
" Collection<Number> collectionOfNumber = factory();", // Number>, Collection<? extends Number>, Collection<? super Integer>]
" // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>,", Collection<Number> collectionOfNumber = factory();
" // Collection<Integer>, Collection<? super Integer>, Collection<? extends Integer>]", // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>,
" Collection<Integer> collectionOfInteger = factory();", // Collection<Integer>, Collection<? super Integer>, Collection<? extends Integer>]
" // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>]", Collection<Integer> collectionOfInteger = factory();
" Collection<Short> collectionOfShort = factory();", // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>]
"", Collection<Short> collectionOfShort = factory();
" // BUG: Diagnostic contains: [Collection, List]",
" List rawList = factory();", // BUG: Diagnostic contains: [Collection, List]
" // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<Number>, Collection<? super", List rawList = factory();
" // Number>, Collection<? extends Number>, Collection<? super Integer>, List, List<?>,", // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<Number>, Collection<? super
" // List<Number>, List<? super Number>, List<? extends Number>, List<? super Integer>]", // Number>, Collection<? extends Number>, Collection<? super Integer>, List, List<?>,
" List<Number> listOfNumber = factory();", // List<Number>, List<? super Number>, List<? extends Number>, List<? super Integer>]
" // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>,", List<Number> listOfNumber = factory();
" // Collection<Integer>, Collection<? super Integer>, Collection<? extends Integer>, List,", // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>,
" // List<?>, List<? extends Number>, List<Integer>, List<? super Integer>, List<? extends", // Collection<Integer>, Collection<? super Integer>, Collection<? extends Integer>, List,
" // Integer>]", // List<?>, List<? extends Number>, List<Integer>, List<? super Integer>, List<? extends
" List<Integer> listOfInteger = factory();", // Integer>]
" // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>, List,", List<Integer> listOfInteger = factory();
" // List<?>, List<? extends Number>]", // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>, List,
" List<Short> listOfShort = factory();", // List<?>, List<? extends Number>]
"", List<Short> listOfShort = factory();
" // BUG: Diagnostic contains: [Collection]",
" Set rawSet = factory();", // BUG: Diagnostic contains: [Collection]
" // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<Number>, Collection<? super", Set rawSet = factory();
" // Number>, Collection<? extends Number>, Collection<? super Integer>]", // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<Number>, Collection<? super
" Set<Number> setOfNumber = factory();", // Number>, Collection<? extends Number>, Collection<? super Integer>]
" // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>,", Set<Number> setOfNumber = factory();
" // Collection<Integer>, Collection<? super Integer>, Collection<? extends Integer>]", // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>,
" Set<Integer> setOfInteger = factory();", // Collection<Integer>, Collection<? super Integer>, Collection<? extends Integer>]
" // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>]", Set<Integer> setOfInteger = factory();
" Set<Short> setOfShort = factory();", // BUG: Diagnostic contains: [Collection, Collection<?>, Collection<? extends Number>]
"", Set<Short> setOfShort = factory();
" Map rawMap = factory();",
" Map<Number, Collection<Number>> mapFromNumberToCollectionOfNumber = factory();", Map rawMap = factory();
" Map<Number, Collection<Short>> mapFromNumberToCollectionOfShort = factory();", Map<Number, Collection<Number>> mapFromNumberToCollectionOfNumber = factory();
" Map<Number, Collection<Integer>> mapFromNumberToCollectionOfInteger = factory();", Map<Number, Collection<Short>> mapFromNumberToCollectionOfShort = factory();
" // BUG: Diagnostic contains: [Map<String, ? extends Collection<? super Short>>]", Map<Number, Collection<Integer>> mapFromNumberToCollectionOfInteger = factory();
" Map<String, Collection<Number>> mapFromStringToCollectionOfNumber = factory();", // BUG: Diagnostic contains: [Map<String, ? extends Collection<? super Short>>]
" // BUG: Diagnostic contains: [Map<String, ? extends Collection<? super Short>>]", Map<String, Collection<Number>> mapFromStringToCollectionOfNumber = factory();
" Map<String, Collection<Short>> mapFromStringToCollectionOfShort = factory();", // BUG: Diagnostic contains: [Map<String, ? extends Collection<? super Short>>]
" Map<String, Collection<Integer>> mapFromStringToCollectionOfInteger = factory();", Map<String, Collection<Short>> mapFromStringToCollectionOfShort = factory();
" // BUG: Diagnostic contains: [Map<String, ? extends Collection<? super Short>>]", Map<String, Collection<Integer>> mapFromStringToCollectionOfInteger = factory();
" Map<String, List<Number>> mapFromStringToListOfNumber = factory();", // BUG: Diagnostic contains: [Map<String, ? extends Collection<? super Short>>]
" // BUG: Diagnostic contains: [Map<String, ? extends Collection<? super Short>>]", Map<String, List<Number>> mapFromStringToListOfNumber = factory();
" Map<String, List<Short>> mapFromStringToListOfShort = factory();", // BUG: Diagnostic contains: [Map<String, ? extends Collection<? super Short>>]
" Map<String, List<Integer>> mapFromStringToListOfInteger = factory();", Map<String, List<Short>> mapFromStringToListOfShort = factory();
" }", Map<String, List<Integer>> mapFromStringToListOfInteger = factory();
"", }
" private <T> T factory() {",
" return null;", private <T> T factory() {
" }", return null;
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -72,22 +72,24 @@ final class SourceCodeTest {
CompilationTestHelper.newInstance(TextBlockFlagger.class, getClass()) CompilationTestHelper.newInstance(TextBlockFlagger.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" String negative1() {", class A {
" return toString();", String negative1() {
" }", return toString();
"", }
" String negative2() {",
" return \"foo\";", String negative2() {
" }", return "foo";
"", }
" String positive1() {",
" // BUG: Diagnostic contains:", String positive1() {
" return \"\"\"", // BUG: Diagnostic contains:
" foo", return ""\"
" \"\"\";", foo
" }", ""\";
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -97,22 +99,26 @@ final class SourceCodeTest {
ToStringConstantExpressionTestChecker.class, getClass()) ToStringConstantExpressionTestChecker.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"class A {", """
" String m() {", class A {
" char a = 'c';", String m() {
" char b = '\\'';", char a = 'c';
" return \"foo\\\"bar\\'baz\\bqux\";", char b = '\\'';
" }", return "foo\\"bar\\'baz\\bqux";
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"class A {", """
" String m() {", class A {
" char a = 'c' /* 'c' */; /* \"a\" */", String m() {
" char b = '\\'' /* '\\'' */; /* \"b\" */", char a = 'c' /* 'c' */; /* "a" */
" return \"foo\\\"bar\\'baz\\bqux\" /* \"foo\\\"bar'baz\\bqux\" */;", char b = '\\'' /* '\\'' */; /* "b" */
" }", return "foo\\"bar\\'baz\\bqux" /* "foo\\"bar'baz\\bqux" */;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -120,73 +126,84 @@ final class SourceCodeTest {
void deleteWithTrailingWhitespaceAnnotations() { void deleteWithTrailingWhitespaceAnnotations() {
BugCheckerRefactoringTestHelper.newInstance( BugCheckerRefactoringTestHelper.newInstance(
DeleteWithTrailingWhitespaceTestChecker.class, getClass()) DeleteWithTrailingWhitespaceTestChecker.class, getClass())
.addInputLines("AnnotationToBeDeleted.java", "@interface AnnotationToBeDeleted {}") .addInputLines(
"AnnotationToBeDeleted.java",
"""
@interface AnnotationToBeDeleted {}
""")
.expectUnchanged() .expectUnchanged()
.addInputLines( .addInputLines(
"AnotherAnnotationToBeDeleted.java", "@interface AnotherAnnotationToBeDeleted {}") "AnotherAnnotationToBeDeleted.java",
"""
@interface AnotherAnnotationToBeDeleted {}
""")
.expectUnchanged() .expectUnchanged()
.addInputLines( .addInputLines(
"AnnotationDeletions.java", "AnnotationDeletions.java",
"interface AnnotationDeletions {", """
" class SoleAnnotation {", interface AnnotationDeletions {
" @AnnotationToBeDeleted", class SoleAnnotation {
" void m() {}", @AnnotationToBeDeleted
" }", void m() {}
"", }
" class FirstAnnotation {",
" @AnnotationToBeDeleted", class FirstAnnotation {
" @Deprecated", @AnnotationToBeDeleted
" void m() {}", @Deprecated
" }", void m() {}
"", }
" class MiddleAnnotation {",
" @Deprecated", class MiddleAnnotation {
" @AnnotationToBeDeleted", @Deprecated
" @SuppressWarnings(\"foo\")", @AnnotationToBeDeleted
" void m() {}", @SuppressWarnings("foo")
" }", void m() {}
"", }
" class LastAnnotation {",
" @Deprecated", class LastAnnotation {
" @AnnotationToBeDeleted", @Deprecated
" void m() {}", @AnnotationToBeDeleted
" }", void m() {}
"", }
" class MultipleAnnotations {",
" @AnnotationToBeDeleted", class MultipleAnnotations {
" @AnotherAnnotationToBeDeleted", @AnnotationToBeDeleted
" @Deprecated", @AnotherAnnotationToBeDeleted
" void m() {}", @Deprecated
" }", void m() {}
"}") }
}
""")
.addOutputLines( .addOutputLines(
"AnnotationDeletions.java", "AnnotationDeletions.java",
"interface AnnotationDeletions {", """
" class SoleAnnotation {", interface AnnotationDeletions {
" void m() {}", class SoleAnnotation {
" }", void m() {}
"", }
" class FirstAnnotation {",
" @Deprecated", class FirstAnnotation {
" void m() {}", @Deprecated
" }", void m() {}
"", }
" class MiddleAnnotation {",
" @Deprecated", class MiddleAnnotation {
" @SuppressWarnings(\"foo\")", @Deprecated
" void m() {}", @SuppressWarnings("foo")
" }", void m() {}
"", }
" class LastAnnotation {",
" @Deprecated", class LastAnnotation {
" void m() {}", @Deprecated
" }", void m() {}
"", }
" class MultipleAnnotations {",
" @Deprecated", class MultipleAnnotations {
" void m() {}", @Deprecated
" }", void m() {}
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -196,66 +213,70 @@ final class SourceCodeTest {
DeleteWithTrailingWhitespaceTestChecker.class, getClass()) DeleteWithTrailingWhitespaceTestChecker.class, getClass())
.addInputLines( .addInputLines(
"MethodDeletions.java", "MethodDeletions.java",
"interface MethodDeletions {", """
" class SoleMethod {", interface MethodDeletions {
" void methodToBeDeleted() {}", class SoleMethod {
" }", void methodToBeDeleted() {}
"", }
" class FirstMethod {",
" void methodToBeDeleted() {}", class FirstMethod {
"", void methodToBeDeleted() {}
" void finalMethod() {}",
" }", void finalMethod() {}
"", }
" class MiddleMethod {",
" void initialMethod() {}", class MiddleMethod {
"", void initialMethod() {}
" void methodToBeDeleted() {}",
"", void methodToBeDeleted() {}
" void finalMethod() {}",
" }", void finalMethod() {}
"", }
" class LastMethod {",
" void initialMethod() {}", class LastMethod {
"", void initialMethod() {}
" void methodToBeDeleted() {}",
" }", void methodToBeDeleted() {}
"", }
" class MultipleMethods {",
" void method1ToBeDeleted() {}", class MultipleMethods {
"", void method1ToBeDeleted() {}
" void method2ToBeDeleted() {}",
"", void method2ToBeDeleted() {}
" void middleMethod() {}",
"", void middleMethod() {}
" void method3ToBeDeleted() {}",
"", void method3ToBeDeleted() {}
" void method4ToBeDeleted() {}",
" }", void method4ToBeDeleted() {}
"}") }
}
""")
.addOutputLines( .addOutputLines(
"MethodDeletions.java", "MethodDeletions.java",
"interface MethodDeletions {", """
" class SoleMethod {}", interface MethodDeletions {
"", class SoleMethod {}
" class FirstMethod {",
" void finalMethod() {}", class FirstMethod {
" }", void finalMethod() {}
"", }
" class MiddleMethod {",
" void initialMethod() {}", class MiddleMethod {
"", void initialMethod() {}
" void finalMethod() {}",
" }", void finalMethod() {}
"", }
" class LastMethod {",
" void initialMethod() {}", class LastMethod {
" }", void initialMethod() {}
"", }
" class MultipleMethods {",
" void middleMethod() {}", class MultipleMethods {
" }", void middleMethod() {}
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -264,30 +285,34 @@ final class SourceCodeTest {
BugCheckerRefactoringTestHelper.newInstance(UnwrapMethodInvocationTestChecker.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(UnwrapMethodInvocationTestChecker.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"", import com.google.common.collect.ImmutableList;
"class A {",
" Object[] m() {", class A {
" return new Object[][] {", Object[] m() {
" {ImmutableList.of()},", return new Object[][] {
" {ImmutableList.of(1)},", {ImmutableList.of()},
" {com.google.common.collect.ImmutableList.of(1, 2)},", {ImmutableList.of(1)},
" {", {com.google.common.collect.ImmutableList.of(1, 2)},
" 0, /*a*/", {
" ImmutableList /*b*/./*c*/ <Integer> /*d*/of /*e*/(/*f*/ 1 /*g*/, /*h*/ 2 /*i*/) /*j*/", 0, /*a*/
" }", ImmutableList /*b*/./*c*/ <Integer> /*d*/of /*e*/(/*f*/ 1 /*g*/, /*h*/ 2 /*i*/) /*j*/
" };", }
" }", };
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"", import com.google.common.collect.ImmutableList;
"class A {",
" Object[] m() {", class A {
" return new Object[][] {{}, {1}, {1, 2}, {0, /*a*/ /*f*/ 1 /*g*/, /*h*/ 2 /*i*/ /*j*/}};", Object[] m() {
" }", return new Object[][] {{}, {1}, {1, 2}, {0, /*a*/ /*f*/ 1 /*g*/, /*h*/ 2 /*i*/ /*j*/}};
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -297,30 +322,34 @@ final class SourceCodeTest {
UnwrapMethodInvocationDroppingWhitespaceAndCommentsTestChecker.class, getClass()) UnwrapMethodInvocationDroppingWhitespaceAndCommentsTestChecker.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"", import com.google.common.collect.ImmutableList;
"class A {",
" Object[] m() {", class A {
" return new Object[][] {", Object[] m() {
" {ImmutableList.of()},", return new Object[][] {
" {ImmutableList.of(1)},", {ImmutableList.of()},
" {com.google.common.collect.ImmutableList.of(1, 2)},", {ImmutableList.of(1)},
" {", {com.google.common.collect.ImmutableList.of(1, 2)},
" 0, /*a*/", {
" ImmutableList /*b*/./*c*/ <Integer> /*d*/of /*e*/(/*f*/ 1 /*g*/, /*h*/ 2 /*i*/) /*j*/", 0, /*a*/
" }", ImmutableList /*b*/./*c*/ <Integer> /*d*/of /*e*/(/*f*/ 1 /*g*/, /*h*/ 2 /*i*/) /*j*/
" };", }
" }", };
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"", import com.google.common.collect.ImmutableList;
"class A {",
" Object[] m() {", class A {
" return new Object[][] {{}, {1}, {1, 2}, {0, /*a*/ 1, 2 /*j*/}};", Object[] m() {
" }", return new Object[][] {{}, {1}, {1, 2}, {0, /*a*/ 1, 2 /*j*/}};
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }

View File

@@ -24,8 +24,10 @@ final class ThirdPartyLibraryTest {
CompilationTestHelper.newInstance(IsIntroductionAllowedTestChecker.class, getClass()) CompilationTestHelper.newInstance(IsIntroductionAllowedTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"// BUG: Diagnostic contains: ASSERTJ: true, GUAVA: true, REACTOR: true", """
"class A {}") // BUG: Diagnostic contains: ASSERTJ: true, GUAVA: true, REACTOR: true
class A {}
""")
.doTest(); .doTest();
} }
@@ -34,18 +36,20 @@ final class ThirdPartyLibraryTest {
CompilationTestHelper.newInstance(IsIntroductionAllowedTestChecker.class, getClass()) CompilationTestHelper.newInstance(IsIntroductionAllowedTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"import org.assertj.core.api.Assertions;", import com.google.common.collect.ImmutableList;
"import reactor.core.publisher.Flux;", import org.assertj.core.api.Assertions;
"", import reactor.core.publisher.Flux;
"// BUG: Diagnostic contains: ASSERTJ: true, GUAVA: true, REACTOR: true",
"class A {", // BUG: Diagnostic contains: ASSERTJ: true, GUAVA: true, REACTOR: true
" void m(Class<?> clazz) {", class A {
" m(Assertions.class);", void m(Class<?> clazz) {
" m(ImmutableList.class);", m(Assertions.class);
" m(Flux.class);", m(ImmutableList.class);
" }", m(Flux.class);
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -55,8 +59,10 @@ final class ThirdPartyLibraryTest {
.withClasspath(ImmutableList.class, Flux.class) .withClasspath(ImmutableList.class, Flux.class)
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"// BUG: Diagnostic contains: ASSERTJ: false, GUAVA: true, REACTOR: true", """
"class A {}") // BUG: Diagnostic contains: ASSERTJ: false, GUAVA: true, REACTOR: true
class A {}
""")
.doTest(); .doTest();
} }
@@ -66,9 +72,11 @@ final class ThirdPartyLibraryTest {
.withClasspath() .withClasspath()
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"// BUG: Diagnostic contains: ASSERTJ: false, GUAVA: false, REACTOR:", """
"// false", // BUG: Diagnostic contains: ASSERTJ: false, GUAVA: false, REACTOR:
"class A {}") // false
class A {}
""")
.doTest(); .doTest();
} }
@@ -92,9 +100,11 @@ final class ThirdPartyLibraryTest {
CompilationTestHelper.newInstance(CanIntroduceUsageTestChecker.class, getClass()) CompilationTestHelper.newInstance(CanIntroduceUsageTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"// BUG: Diagnostic contains: GUAVA_PUBLIC: true, GUAVA_PRIVATE: false, ERROR_PRONE_PUBLIC_NESTED:", """
"// true", // BUG: Diagnostic contains: GUAVA_PUBLIC: true, GUAVA_PRIVATE: false, ERROR_PRONE_PUBLIC_NESTED:
"class A {}") // true
class A {}
""")
.doTest(); .doTest();
} }

View File

@@ -52,18 +52,20 @@ final class RefasterTest {
.expectErrorMessage("StringOfSizeThreeRule", DIAGNOSTIC_STRING_OF_SIZE_THREE.asPredicate()) .expectErrorMessage("StringOfSizeThreeRule", DIAGNOSTIC_STRING_OF_SIZE_THREE.asPredicate())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" // BUG: Diagnostic matches: StringOfSizeZeroRule", void m() {
" boolean b1 = \"foo\".toCharArray().length == 0;", // BUG: Diagnostic matches: StringOfSizeZeroRule
" // BUG: Diagnostic matches: StringOfSizeOneRule", boolean b1 = "foo".toCharArray().length == 0;
" boolean b2 = \"bar\".toCharArray().length == 1;", // BUG: Diagnostic matches: StringOfSizeOneRule
" // BUG: Diagnostic matches: StringOfSizeTwoRule", boolean b2 = "bar".toCharArray().length == 1;
" boolean b3 = \"baz\".toCharArray().length == 2;", // BUG: Diagnostic matches: StringOfSizeTwoRule
" // BUG: Diagnostic matches: StringOfSizeThreeRule", boolean b3 = "baz".toCharArray().length == 2;
" boolean b4 = \"qux\".toCharArray().length == 3;", // BUG: Diagnostic matches: StringOfSizeThreeRule
" }", boolean b4 = "qux".toCharArray().length == 3;
"}") }
}
""")
.doTest(); .doTest();
} }
@@ -154,16 +156,18 @@ final class RefasterTest {
.setArgs(arguments) .setArgs(arguments)
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" boolean[] bs = {", void m() {
" \"foo\".toCharArray().length == 0,", boolean[] bs = {
" \"bar\".toCharArray().length == 1,", "foo".toCharArray().length == 0,
" \"baz\".toCharArray().length == 2,", "bar".toCharArray().length == 1,
" \"qux\".toCharArray().length == 3", "baz".toCharArray().length == 2,
" };", "qux".toCharArray().length == 3
" }", };
"}"); }
}
""");
if (expectedSeverities.isEmpty()) { if (expectedSeverities.isEmpty()) {
compilationTestHelper.doTest(); compilationTestHelper.doTest();
@@ -206,24 +210,28 @@ final class RefasterTest {
BugCheckerRefactoringTestHelper.newInstance(Refaster.class, getClass()) BugCheckerRefactoringTestHelper.newInstance(Refaster.class, getClass())
.addInputLines( .addInputLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" boolean b1 = \"foo\".toCharArray().length == 0;", void m() {
" boolean b2 = \"bar\".toCharArray().length == 1;", boolean b1 = "foo".toCharArray().length == 0;
" boolean b3 = \"baz\".toCharArray().length == 2;", boolean b2 = "bar".toCharArray().length == 1;
" boolean b4 = \"qux\".toCharArray().length == 3;", boolean b3 = "baz".toCharArray().length == 2;
" }", boolean b4 = "qux".toCharArray().length == 3;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" boolean b1 = \"foo\".isEmpty();", void m() {
" boolean b2 = \"bar\".length() == 1;", boolean b1 = "foo".isEmpty();
" boolean b3 = \"baz\".length() == 2;", boolean b2 = "bar".length() == 1;
" boolean b4 = \"qux\".length() == 3;", boolean b3 = "baz".length() == 2;
" }", boolean b4 = "qux".length() == 3;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
@@ -234,24 +242,28 @@ final class RefasterTest {
"-XepOpt:Refaster:NamePattern=.*\\$(StringOfSizeZeroVerboseRule|StringOfSizeTwoRule)$") "-XepOpt:Refaster:NamePattern=.*\\$(StringOfSizeZeroVerboseRule|StringOfSizeTwoRule)$")
.addInputLines( .addInputLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" boolean b1 = \"foo\".toCharArray().length == 0;", void m() {
" boolean b2 = \"bar\".toCharArray().length == 1;", boolean b1 = "foo".toCharArray().length == 0;
" boolean b3 = \"baz\".toCharArray().length == 2;", boolean b2 = "bar".toCharArray().length == 1;
" boolean b4 = \"qux\".toCharArray().length == 3;", boolean b3 = "baz".toCharArray().length == 2;
" }", boolean b4 = "qux".toCharArray().length == 3;
"}") }
}
""")
.addOutputLines( .addOutputLines(
"A.java", "A.java",
"class A {", """
" void m() {", class A {
" boolean b1 = \"foo\".length() + 1 == 1;", void m() {
" boolean b2 = \"bar\".toCharArray().length == 1;", boolean b1 = "foo".length() + 1 == 1;
" boolean b3 = \"baz\".length() == 2;", boolean b2 = "bar".toCharArray().length == 1;
" boolean b4 = \"qux\".toCharArray().length == 3;", boolean b3 = "baz".length() == 2;
" }", boolean b4 = "qux".toCharArray().length == 3;
"}") }
}
""")
.doTest(TestMode.TEXT_MATCH); .doTest(TestMode.TEXT_MATCH);
} }
} }

View File

@@ -13,38 +13,40 @@ final class IsArrayTest {
CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass()) CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" Object negative1() {", class A {
" return alwaysNull();", Object negative1() {
" }", return alwaysNull();
"", }
" String negative2() {",
" return alwaysNull();", String negative2() {
" }", return alwaysNull();
"", }
" int negative3() {",
" return alwaysNull();", int negative3() {
" }", return alwaysNull();
"", }
" Object[] positive1() {",
" // BUG: Diagnostic contains:", Object[] positive1() {
" return alwaysNull();", // BUG: Diagnostic contains:
" }", return alwaysNull();
"", }
" String[] positive2() {",
" // BUG: Diagnostic contains:", String[] positive2() {
" return alwaysNull();", // BUG: Diagnostic contains:
" }", return alwaysNull();
"", }
" int[] positive3() {",
" // BUG: Diagnostic contains:", int[] positive3() {
" return alwaysNull();", // BUG: Diagnostic contains:
" }", return alwaysNull();
"", }
" private static <T> T alwaysNull() {",
" return null;", private static <T> T alwaysNull() {
" }", return null;
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -13,38 +13,40 @@ final class IsCharacterTest {
CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass()) CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"class A {", """
" String negative1() {", class A {
" return \"a\";", String negative1() {
" }", return "a";
"", }
" char[] negative2() {",
" return \"a\".toCharArray();", char[] negative2() {
" }", return "a".toCharArray();
"", }
" byte negative3() {",
" return (byte) 0;", byte negative3() {
" }", return (byte) 0;
"", }
" int negative4() {",
" return 0;", int negative4() {
" }", return 0;
"", }
" char positive1() {",
" // BUG: Diagnostic contains:", char positive1() {
" return 'a';", // BUG: Diagnostic contains:
" }", return 'a';
"", }
" Character positive2() {",
" // BUG: Diagnostic contains:", Character positive2() {
" return (Character) null;", // BUG: Diagnostic contains:
" }", return (Character) null;
"", }
" char positive3() {",
" // BUG: Diagnostic contains:", char positive3() {
" return (char) 1;", // BUG: Diagnostic contains:
" }", return (char) 1;
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -13,423 +13,425 @@ final class IsEmptyTest {
CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass()) CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.collect.ImmutableList;", """
"import com.google.common.collect.ImmutableMap;", import com.google.common.collect.ImmutableList;
"import com.google.common.collect.ImmutableSet;", import com.google.common.collect.ImmutableMap;
"import com.google.common.collect.ImmutableSetMultimap;", import com.google.common.collect.ImmutableSet;
"import java.util.ArrayList;", import com.google.common.collect.ImmutableSetMultimap;
"import java.util.Collections;", import java.util.ArrayList;
"import java.util.Comparator;", import java.util.Collections;
"import java.util.HashMap;", import java.util.Comparator;
"import java.util.HashSet;", import java.util.HashMap;
"import java.util.LinkedHashMap;", import java.util.HashSet;
"import java.util.LinkedHashSet;", import java.util.LinkedHashMap;
"import java.util.LinkedList;", import java.util.LinkedHashSet;
"import java.util.List;", import java.util.LinkedList;
"import java.util.Map;", import java.util.List;
"import java.util.Random;", import java.util.Map;
"import java.util.Set;", import java.util.Random;
"import java.util.Stack;", import java.util.Set;
"import java.util.TreeMap;", import java.util.Stack;
"import java.util.TreeSet;", import java.util.TreeMap;
"import java.util.Vector;", import java.util.TreeSet;
"import java.util.stream.Stream;", import java.util.Vector;
"import reactor.core.publisher.Flux;", import java.util.stream.Stream;
"import reactor.core.publisher.Mono;", import reactor.core.publisher.Flux;
"import reactor.util.context.Context;", import reactor.core.publisher.Mono;
"", import reactor.util.context.Context;
"class A {",
" int[] negative1() {", class A {
" return new int[1];", int[] negative1() {
" }", return new int[1];
"", }
" int[][] negative2() {",
" return new int[1][0];", int[][] negative2() {
" }", return new int[1][0];
"", }
" int[] negative3() {",
" return new int[] {0};", int[] negative3() {
" }", return new int[] {0};
"", }
" int[][] negative4() {",
" return new int[][] {{0}};", int[][] negative4() {
" }", return new int[][] {{0}};
"", }
" int[] negative5() {",
" int i = hashCode();", int[] negative5() {
" return new int[i];", int i = hashCode();
" }", return new int[i];
"", }
" Random negative6() {",
" return new Random();", Random negative6() {
" }", return new Random();
"", }
" List<Integer> negative7() {",
" return new ArrayList<>(ImmutableList.of(1));", List<Integer> negative7() {
" }", return new ArrayList<>(ImmutableList.of(1));
"", }
" Map<Integer, Integer> negative8() {",
" return new HashMap<>(ImmutableMap.of(1, 2));", Map<Integer, Integer> negative8() {
" }", return new HashMap<>(ImmutableMap.of(1, 2));
"", }
" Set<Integer> negative9() {",
" return new HashSet<>(ImmutableList.of(1));", Set<Integer> negative9() {
" }", return new HashSet<>(ImmutableList.of(1));
"", }
" Map<Integer, Integer> negative10() {",
" return new LinkedHashMap<>(ImmutableMap.of(1, 2));", Map<Integer, Integer> negative10() {
" }", return new LinkedHashMap<>(ImmutableMap.of(1, 2));
"", }
" Set<Integer> negative11() {",
" return new LinkedHashSet<>(ImmutableList.of(1));", Set<Integer> negative11() {
" }", return new LinkedHashSet<>(ImmutableList.of(1));
"", }
" List<Integer> negative12() {",
" return new LinkedList<>(ImmutableList.of(1));", List<Integer> negative12() {
" }", return new LinkedList<>(ImmutableList.of(1));
"", }
" Map<Integer, Integer> negative13() {",
" return new HashMap<>(ImmutableMap.of(1, 2));", Map<Integer, Integer> negative13() {
" }", return new HashMap<>(ImmutableMap.of(1, 2));
"", }
" Set<Integer> negative14() {",
" return new HashSet<>(ImmutableList.of(1));", Set<Integer> negative14() {
" }", return new HashSet<>(ImmutableList.of(1));
"", }
" List<Integer> negative15() {",
" return new Vector<>(ImmutableList.of(1));", List<Integer> negative15() {
" }", return new Vector<>(ImmutableList.of(1));
"", }
" ImmutableList<Integer> negative16() {",
" return ImmutableList.of(1);", ImmutableList<Integer> negative16() {
" }", return ImmutableList.of(1);
"", }
" ImmutableSet<Integer> negative17() {",
" return ImmutableSet.of(1);", ImmutableSet<Integer> negative17() {
" }", return ImmutableSet.of(1);
"", }
" ImmutableMap<Integer, Integer> negative18() {",
" return ImmutableMap.of(1, 2);", ImmutableMap<Integer, Integer> negative18() {
" }", return ImmutableMap.of(1, 2);
"", }
" ImmutableSetMultimap<Integer, Integer> negative19() {",
" return ImmutableSetMultimap.of(1, 2);", ImmutableSetMultimap<Integer, Integer> negative19() {
" }", return ImmutableSetMultimap.of(1, 2);
"", }
" List<Integer> negative20() {",
" return List.of(1);", List<Integer> negative20() {
" }", return List.of(1);
"", }
" Map<Integer, Integer> negative21() {",
" return Map.of(1, 2);", Map<Integer, Integer> negative21() {
" }", return Map.of(1, 2);
"", }
" Set<Integer> negative22() {",
" return Set.of(1);", Set<Integer> negative22() {
" }", return Set.of(1);
"", }
" Stream<Integer> negative23() {",
" return Stream.of(1);", Stream<Integer> negative23() {
" }", return Stream.of(1);
"", }
" int[] positive1() {",
" // BUG: Diagnostic contains:", int[] positive1() {
" return new int[0];", // BUG: Diagnostic contains:
" }", return new int[0];
"", }
" int[][] positive2() {",
" // BUG: Diagnostic contains:", int[][] positive2() {
" return new int[0][1];", // BUG: Diagnostic contains:
" }", return new int[0][1];
"", }
" int[] positive3() {",
" // BUG: Diagnostic contains:", int[] positive3() {
" return new int[] {};", // BUG: Diagnostic contains:
" }", return new int[] {};
"", }
" int[][] positive4() {",
" // BUG: Diagnostic contains:", int[][] positive4() {
" return new int[][] {};", // BUG: Diagnostic contains:
" }", return new int[][] {};
"", }
" List<Integer> positive5() {",
" // BUG: Diagnostic contains:", List<Integer> positive5() {
" return new ArrayList<>();", // BUG: Diagnostic contains:
" }", return new ArrayList<>();
"", }
" List<String> positive6() {",
" // BUG: Diagnostic contains:", List<String> positive6() {
" return new ArrayList<>(1);", // BUG: Diagnostic contains:
" }", return new ArrayList<>(1);
"", }
" List<String> positive7() {",
" // BUG: Diagnostic contains:", List<String> positive7() {
" return new ArrayList<>(", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", return new ArrayList<>(
" ImmutableList.of());", // BUG: Diagnostic contains:
" }", ImmutableList.of());
"", }
" Map<String, String> positive8() {",
" // BUG: Diagnostic contains:", Map<String, String> positive8() {
" return new HashMap<>();", // BUG: Diagnostic contains:
" }", return new HashMap<>();
"", }
" Map<String, String> positive9() {",
" // BUG: Diagnostic contains:", Map<String, String> positive9() {
" return new HashMap<>(1);", // BUG: Diagnostic contains:
" }", return new HashMap<>(1);
"", }
" Map<String, String> positive10() {",
" // BUG: Diagnostic contains:", Map<String, String> positive10() {
" return new HashMap<>(1, 1.0F);", // BUG: Diagnostic contains:
" }", return new HashMap<>(1, 1.0F);
"", }
" Map<String, String> positive11() {",
" // BUG: Diagnostic contains:", Map<String, String> positive11() {
" return new HashMap<>(", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", return new HashMap<>(
" ImmutableMap.of());", // BUG: Diagnostic contains:
" }", ImmutableMap.of());
"", }
" Set<Integer> positive12() {",
" // BUG: Diagnostic contains:", Set<Integer> positive12() {
" return new HashSet<>();", // BUG: Diagnostic contains:
" }", return new HashSet<>();
"", }
" Set<Integer> positive13() {",
" // BUG: Diagnostic contains:", Set<Integer> positive13() {
" return new HashSet<>(1);", // BUG: Diagnostic contains:
" }", return new HashSet<>(1);
"", }
" Set<Integer> positive14() {",
" // BUG: Diagnostic contains:", Set<Integer> positive14() {
" return new HashSet<>(1, 1.0F);", // BUG: Diagnostic contains:
" }", return new HashSet<>(1, 1.0F);
"", }
" Set<Integer> positive15() {",
" // BUG: Diagnostic contains:", Set<Integer> positive15() {
" return new HashSet<>(", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", return new HashSet<>(
" ImmutableList.of());", // BUG: Diagnostic contains:
" }", ImmutableList.of());
"", }
" Map<String, String> positive16() {",
" // BUG: Diagnostic contains:", Map<String, String> positive16() {
" return new LinkedHashMap<>();", // BUG: Diagnostic contains:
" }", return new LinkedHashMap<>();
"", }
" Map<String, String> positive17() {",
" // BUG: Diagnostic contains:", Map<String, String> positive17() {
" return new LinkedHashMap<>(1);", // BUG: Diagnostic contains:
" }", return new LinkedHashMap<>(1);
"", }
" Map<String, String> positive18() {",
" // BUG: Diagnostic contains:", Map<String, String> positive18() {
" return new LinkedHashMap<>(1, 1.0F);", // BUG: Diagnostic contains:
" }", return new LinkedHashMap<>(1, 1.0F);
"", }
" Map<String, String> positive19() {",
" // BUG: Diagnostic contains:", Map<String, String> positive19() {
" return new LinkedHashMap<>(1, 1.0F, false);", // BUG: Diagnostic contains:
" }", return new LinkedHashMap<>(1, 1.0F, false);
"", }
" Map<String, String> positive20() {",
" // BUG: Diagnostic contains:", Map<String, String> positive20() {
" return new LinkedHashMap<>(", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", return new LinkedHashMap<>(
" ImmutableMap.of());", // BUG: Diagnostic contains:
" }", ImmutableMap.of());
"", }
" Set<Integer> positive21() {",
" // BUG: Diagnostic contains:", Set<Integer> positive21() {
" return new LinkedHashSet<>();", // BUG: Diagnostic contains:
" }", return new LinkedHashSet<>();
"", }
" Set<Integer> positive22() {",
" // BUG: Diagnostic contains:", Set<Integer> positive22() {
" return new LinkedHashSet<>(1);", // BUG: Diagnostic contains:
" }", return new LinkedHashSet<>(1);
"", }
" Set<Integer> positive23() {",
" // BUG: Diagnostic contains:", Set<Integer> positive23() {
" return new LinkedHashSet<>(1, 1.0F);", // BUG: Diagnostic contains:
" }", return new LinkedHashSet<>(1, 1.0F);
"", }
" Set<Integer> positive24() {",
" // BUG: Diagnostic contains:", Set<Integer> positive24() {
" return new LinkedHashSet<>(", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", return new LinkedHashSet<>(
" ImmutableList.of());", // BUG: Diagnostic contains:
" }", ImmutableList.of());
"", }
" List<Integer> positive25() {",
" // BUG: Diagnostic contains:", List<Integer> positive25() {
" return new LinkedList<>();", // BUG: Diagnostic contains:
" }", return new LinkedList<>();
"", }
" List<String> positive26() {",
" // BUG: Diagnostic contains:", List<String> positive26() {
" return new LinkedList<>(", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", return new LinkedList<>(
" ImmutableList.of());", // BUG: Diagnostic contains:
" }", ImmutableList.of());
"", }
" List<Integer> positive27() {",
" // BUG: Diagnostic contains:", List<Integer> positive27() {
" return new Stack<>();", // BUG: Diagnostic contains:
" }", return new Stack<>();
"", }
" Map<String, String> positive28() {",
" // BUG: Diagnostic contains:", Map<String, String> positive28() {
" return new TreeMap<>();", // BUG: Diagnostic contains:
" }", return new TreeMap<>();
"", }
" Map<String, String> positive29() {",
" // BUG: Diagnostic contains:", Map<String, String> positive29() {
" return new TreeMap<>(Comparator.naturalOrder());", // BUG: Diagnostic contains:
" }", return new TreeMap<>(Comparator.naturalOrder());
"", }
" Map<String, String> positive30() {",
" // BUG: Diagnostic contains:", Map<String, String> positive30() {
" return new TreeMap<>(", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", return new TreeMap<>(
" ImmutableMap.of());", // BUG: Diagnostic contains:
" }", ImmutableMap.of());
"", }
" Set<Integer> positive31() {",
" // BUG: Diagnostic contains:", Set<Integer> positive31() {
" return new TreeSet<>();", // BUG: Diagnostic contains:
" }", return new TreeSet<>();
"", }
" Set<Integer> positive32() {",
" // BUG: Diagnostic contains:", Set<Integer> positive32() {
" return new TreeSet<>(Comparator.naturalOrder());", // BUG: Diagnostic contains:
" }", return new TreeSet<>(Comparator.naturalOrder());
"", }
" Set<Integer> positive33() {",
" // BUG: Diagnostic contains:", Set<Integer> positive33() {
" return new TreeSet<>(", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", return new TreeSet<>(
" ImmutableList.of());", // BUG: Diagnostic contains:
" }", ImmutableList.of());
"", }
" List<Integer> positive34() {",
" // BUG: Diagnostic contains:", List<Integer> positive34() {
" return new Vector<>();", // BUG: Diagnostic contains:
" }", return new Vector<>();
"", }
" List<Integer> positive35() {",
" // BUG: Diagnostic contains:", List<Integer> positive35() {
" return new Vector<>(1);", // BUG: Diagnostic contains:
" }", return new Vector<>(1);
"", }
" List<Integer> positive36() {",
" // BUG: Diagnostic contains:", List<Integer> positive36() {
" return new Vector<>(1, 2);", // BUG: Diagnostic contains:
" }", return new Vector<>(1, 2);
"", }
" List<Integer> positive37() {",
" // BUG: Diagnostic contains:", List<Integer> positive37() {
" return new Vector<>(", // BUG: Diagnostic contains:
" // BUG: Diagnostic contains:", return new Vector<>(
" ImmutableList.of());", // BUG: Diagnostic contains:
" }", ImmutableList.of());
"", }
" List<Integer> positive38() {",
" // BUG: Diagnostic contains:", List<Integer> positive38() {
" return Collections.EMPTY_LIST;", // BUG: Diagnostic contains:
" }", return Collections.EMPTY_LIST;
"", }
" Map<String, String> positive39() {",
" // BUG: Diagnostic contains:", Map<String, String> positive39() {
" return Collections.EMPTY_MAP;", // BUG: Diagnostic contains:
" }", return Collections.EMPTY_MAP;
"", }
" Set<Integer> positive40() {",
" // BUG: Diagnostic contains:", Set<Integer> positive40() {
" return Collections.EMPTY_SET;", // BUG: Diagnostic contains:
" }", return Collections.EMPTY_SET;
"", }
" List<Integer> positive41() {",
" // BUG: Diagnostic contains:", List<Integer> positive41() {
" return Collections.emptyList();", // BUG: Diagnostic contains:
" }", return Collections.emptyList();
"", }
" Map<String, String> positive42() {",
" // BUG: Diagnostic contains:", Map<String, String> positive42() {
" return Collections.emptyMap();", // BUG: Diagnostic contains:
" }", return Collections.emptyMap();
"", }
" Set<Integer> positive43() {",
" // BUG: Diagnostic contains:", Set<Integer> positive43() {
" return Collections.emptySet();", // BUG: Diagnostic contains:
" }", return Collections.emptySet();
"", }
" ImmutableList<Integer> positive44() {",
" // BUG: Diagnostic contains:", ImmutableList<Integer> positive44() {
" return ImmutableList.of();", // BUG: Diagnostic contains:
" }", return ImmutableList.of();
"", }
" ImmutableSet<Integer> positive45() {",
" // BUG: Diagnostic contains:", ImmutableSet<Integer> positive45() {
" return ImmutableSet.of();", // BUG: Diagnostic contains:
" }", return ImmutableSet.of();
"", }
" ImmutableMap<String, Integer> positive46() {",
" // BUG: Diagnostic contains:", ImmutableMap<String, Integer> positive46() {
" return ImmutableMap.of();", // BUG: Diagnostic contains:
" }", return ImmutableMap.of();
"", }
" ImmutableSetMultimap<String, Integer> positive47() {",
" // BUG: Diagnostic contains:", ImmutableSetMultimap<String, Integer> positive47() {
" return ImmutableSetMultimap.of();", // BUG: Diagnostic contains:
" }", return ImmutableSetMultimap.of();
"", }
" List<Integer> positive48() {",
" // BUG: Diagnostic contains:", List<Integer> positive48() {
" return List.of();", // BUG: Diagnostic contains:
" }", return List.of();
"", }
" Map<String, String> positive49() {",
" // BUG: Diagnostic contains:", Map<String, String> positive49() {
" return Map.of();", // BUG: Diagnostic contains:
" }", return Map.of();
"", }
" Set<Integer> positive50() {",
" // BUG: Diagnostic contains:", Set<Integer> positive50() {
" return Set.of();", // BUG: Diagnostic contains:
" }", return Set.of();
"", }
" Stream<Integer> positive51() {",
" // BUG: Diagnostic contains:", Stream<Integer> positive51() {
" return Stream.of();", // BUG: Diagnostic contains:
" }", return Stream.of();
"", }
" Stream<Integer> positive52() {",
" // BUG: Diagnostic contains:", Stream<Integer> positive52() {
" return Stream.empty();", // BUG: Diagnostic contains:
" }", return Stream.empty();
"", }
" Flux<Integer> positive53() {",
" // BUG: Diagnostic contains:", Flux<Integer> positive53() {
" return Flux.empty();", // BUG: Diagnostic contains:
" }", return Flux.empty();
"", }
" Mono<Integer> positive54() {",
" // BUG: Diagnostic contains:", Mono<Integer> positive54() {
" return Mono.empty();", // BUG: Diagnostic contains:
" }", return Mono.empty();
"", }
" Context positive55() {",
" // BUG: Diagnostic contains:", Context positive55() {
" return Context.empty();", // BUG: Diagnostic contains:
" }", return Context.empty();
"", }
" Flux<Integer> positive56() {",
" // BUG: Diagnostic contains:", Flux<Integer> positive56() {
" return Flux.just();", // BUG: Diagnostic contains:
" }", return Flux.just();
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -13,52 +13,54 @@ final class IsIdentityOperationTest {
CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass()) CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.function.BinaryOperator;", """
"import java.util.function.DoubleUnaryOperator;", import java.util.function.BinaryOperator;
"import java.util.function.Function;", import java.util.function.DoubleUnaryOperator;
"import java.util.function.IntUnaryOperator;", import java.util.function.Function;
"import java.util.function.LongUnaryOperator;", import java.util.function.IntUnaryOperator;
"import java.util.function.UnaryOperator;", import java.util.function.LongUnaryOperator;
"", import java.util.function.UnaryOperator;
"class A {",
" BinaryOperator<String> negative1() {", class A {
" return (a, b) -> a;", BinaryOperator<String> negative1() {
" }", return (a, b) -> a;
"", }
" UnaryOperator<String> negative2() {",
" return a -> a + a;", UnaryOperator<String> negative2() {
" }", return a -> a + a;
"", }
" DoubleUnaryOperator positive1() {",
" // BUG: Diagnostic contains:", DoubleUnaryOperator positive1() {
" return DoubleUnaryOperator.identity();", // BUG: Diagnostic contains:
" }", return DoubleUnaryOperator.identity();
"", }
" Function<Integer, Integer> positive2() {",
" // BUG: Diagnostic contains:", Function<Integer, Integer> positive2() {
" return Function.identity();", // BUG: Diagnostic contains:
" }", return Function.identity();
"", }
" UnaryOperator<String> positive3() {",
" // BUG: Diagnostic contains:", UnaryOperator<String> positive3() {
" return UnaryOperator.identity();", // BUG: Diagnostic contains:
" }", return UnaryOperator.identity();
"", }
" IntUnaryOperator positive4() {",
" // BUG: Diagnostic contains:", IntUnaryOperator positive4() {
" return IntUnaryOperator.identity();", // BUG: Diagnostic contains:
" }", return IntUnaryOperator.identity();
"", }
" LongUnaryOperator positive5() {",
" // BUG: Diagnostic contains:", LongUnaryOperator positive5() {
" return LongUnaryOperator.identity();", // BUG: Diagnostic contains:
" }", return LongUnaryOperator.identity();
"", }
" UnaryOperator positive6() {",
" // BUG: Diagnostic contains:", UnaryOperator positive6() {
" return a -> a;", // BUG: Diagnostic contains:
" }", return a -> a;
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -13,45 +13,47 @@ final class IsLambdaExpressionOrMethodReferenceTest {
CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass()) CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.common.base.Predicates;", """
"import java.util.function.Function;", import com.google.common.base.Predicates;
"import java.util.function.Predicate;", import java.util.function.Function;
"", import java.util.function.Predicate;
"class A {",
" boolean negative1() {", class A {
" return true;", boolean negative1() {
" }", return true;
"", }
" String negative2() {",
" return new String(new byte[0]);", String negative2() {
" }", return new String(new byte[0]);
"", }
" Predicate<String> negative3() {",
" return Predicates.alwaysTrue();", Predicate<String> negative3() {
" }", return Predicates.alwaysTrue();
"", }
" Predicate<String> positive1() {",
" // BUG: Diagnostic contains:", Predicate<String> positive1() {
" return str -> true;", // BUG: Diagnostic contains:
" }", return str -> true;
"", }
" Predicate<String> positive2() {",
" // BUG: Diagnostic contains:", Predicate<String> positive2() {
" return str -> {", // BUG: Diagnostic contains:
" return true;", return str -> {
" };", return true;
" }", };
"", }
" Predicate<String> positive3() {",
" // BUG: Diagnostic contains:", Predicate<String> positive3() {
" return String::isEmpty;", // BUG: Diagnostic contains:
" }", return String::isEmpty;
"", }
" Function<byte[], String> positive4() {",
" // BUG: Diagnostic contains:", Function<byte[], String> positive4() {
" return String::new;", // BUG: Diagnostic contains:
" }", return String::new;
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -13,30 +13,32 @@ final class IsRefasterAsVarargsTest {
CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass()) CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import com.google.errorprone.refaster.Refaster;", """
"", import com.google.errorprone.refaster.Refaster;
"class A {",
" int[] negative1() {", class A {
" return new int[4];", int[] negative1() {
" }", return new int[4];
"", }
" String[] negative2() {",
" return \"foo\".split(\"o\");", String[] negative2() {
" }", return "foo".split("o");
"", }
" String[] negative3() {",
" return asVarArgs(\"bar\");", String[] negative3() {
" }", return asVarArgs("bar");
"", }
" String[] positive1() {",
" // BUG: Diagnostic contains:", String[] positive1() {
" return Refaster.asVarargs(\"o\");", // BUG: Diagnostic contains:
" }", return Refaster.asVarargs("o");
"", }
" private static String[] asVarArgs(String s) {",
" return s.split(\"a\");", private static String[] asVarArgs(String s) {
" }", return s.split("a");
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -14,126 +14,128 @@ final class RequiresComputationTest {
CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass()) CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.io.OutputStream;", """
"import java.util.Comparator;", import java.io.OutputStream;
"import java.util.function.Predicate;", import java.util.Comparator;
"", import java.util.function.Predicate;
"class A {",
" int negative1() {", class A {
" int[] arr = new int[0];", int negative1() {
" return arr[0];", int[] arr = new int[0];
" }", return arr[0];
"", }
" String negative2() {",
" return null;", String negative2() {
" }", return null;
"", }
" boolean negative3() {",
" return false;", boolean negative3() {
" }", return false;
"", }
" int negative4() {",
" return 0;", int negative4() {
" }", return 0;
"", }
" String negative5() {",
" return \"foo\" + \"bar\";", String negative5() {
" }", return "foo" + "bar";
"", }
" Predicate<String> negative6() {",
" return v -> \"foo\".equals(v);", Predicate<String> negative6() {
" }", return v -> "foo".equals(v);
"", }
" A negative7() {",
" return this;", A negative7() {
" }", return this;
"", }
" Predicate<String> negative8() {",
" return \"foo\"::equals;", Predicate<String> negative8() {
" }", return "foo"::equals;
"", }
" OutputStream negative9() {",
" return System.out;", OutputStream negative9() {
" }", return System.out;
"", }
" A negative10() {",
" return (this);", A negative10() {
" }", return (this);
"", }
" Object negative11() {",
" return (Object) this;", Object negative11() {
" }", return (Object) this;
"", }
" boolean negative12() {",
" boolean[] arr = new boolean[0];", boolean negative12() {
" return !arr[0];", boolean[] arr = new boolean[0];
" }", return !arr[0];
"", }
" String negative13() {",
" return \"foo\" + 0;", String negative13() {
" }", return "foo" + 0;
"", }
" String positive1() {",
" // BUG: Diagnostic contains:", String positive1() {
" return toString();", // BUG: Diagnostic contains:
" }", return toString();
"", }
" String positive2() {",
" // BUG: Diagnostic contains:", String positive2() {
" return this.toString();", // BUG: Diagnostic contains:
" }", return this.toString();
"", }
" String positive3() {",
" // BUG: Diagnostic contains:", String positive3() {
" return String.valueOf(1);", // BUG: Diagnostic contains:
" }", return String.valueOf(1);
"", }
" String positive4() {",
" // BUG: Diagnostic contains:", String positive4() {
" return toString().toString();", // BUG: Diagnostic contains:
" }", return toString().toString();
"", }
" String positive5() {",
" // BUG: Diagnostic contains:", String positive5() {
" return \"foo\" + toString();", // BUG: Diagnostic contains:
" }", return "foo" + toString();
"", }
" byte positive6() {",
" // BUG: Diagnostic contains:", byte positive6() {
" return \"foo\".getBytes()[0];", // BUG: Diagnostic contains:
" }", return "foo".getBytes()[0];
"", }
" int positive7() {",
" int[] arr = new int[0];", int positive7() {
" // BUG: Diagnostic contains:", int[] arr = new int[0];
" return arr[hashCode()];", // BUG: Diagnostic contains:
" }", return arr[hashCode()];
"", }
" Predicate<String> positive8() {",
" // BUG: Diagnostic contains:", Predicate<String> positive8() {
" return toString()::equals;", // BUG: Diagnostic contains:
" }", return toString()::equals;
"", }
" Comparator<String> positive9() {",
" // BUG: Diagnostic contains:", Comparator<String> positive9() {
" return toString().CASE_INSENSITIVE_ORDER;", // BUG: Diagnostic contains:
" }", return toString().CASE_INSENSITIVE_ORDER;
"", }
" String positive10() {",
" // BUG: Diagnostic contains:", String positive10() {
" return (toString());", // BUG: Diagnostic contains:
" }", return (toString());
"", }
" Object positive11() {",
" // BUG: Diagnostic contains:", Object positive11() {
" return (Object) toString();", // BUG: Diagnostic contains:
" }", return (Object) toString();
"", }
" int positive12() {",
" // BUG: Diagnostic contains:", int positive12() {
" return -hashCode();", // BUG: Diagnostic contains:
" }", return -hashCode();
"}") }
}
""")
.doTest(); .doTest();
} }

View File

@@ -13,107 +13,109 @@ final class ThrowsCheckedExceptionTest {
CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass()) CompilationTestHelper.newInstance(MatcherTestChecker.class, getClass())
.addSourceLines( .addSourceLines(
"A.java", "A.java",
"import java.util.concurrent.Callable;", """
"import java.util.function.Supplier;", import java.util.concurrent.Callable;
"", import java.util.function.Supplier;
"class A {",
" void negative1() {", class A {
" callableSink(null);", void negative1() {
" }", callableSink(null);
"", }
" void negative2() {",
" supplierSink(null);", void negative2() {
" }", supplierSink(null);
"", }
" void negative3() {",
" supplierSink((Supplier<?> & Iterable<?>) null);", void negative3() {
" }", supplierSink((Supplier<?> & Iterable<?>) null);
"", }
" void negative4() {",
" callableSink(() -> toString());", void negative4() {
" }", callableSink(() -> toString());
"", }
" void negative5() {",
" supplierSink(() -> toString());", void negative5() {
" }", supplierSink(() -> toString());
"", }
" void negative6() {",
" callableSink(this::toString);", void negative6() {
" }", callableSink(this::toString);
"", }
" void negative7() {",
" supplierSink(this::toString);", void negative7() {
" }", supplierSink(this::toString);
"", }
" void negative8() {",
" callableSink(A::throwsRuntimeException);", void negative8() {
" }", callableSink(A::throwsRuntimeException);
"", }
" void negative9() {",
" supplierSink(A::throwsRuntimeException);", void negative9() {
" }", supplierSink(A::throwsRuntimeException);
"", }
" void negative10() {",
" callableSink(A::throwsError);", void negative10() {
" }", callableSink(A::throwsError);
"", }
" void negative11() {",
" supplierSink(A::throwsError);", void negative11() {
" }", supplierSink(A::throwsError);
"", }
" void negative12() {",
" supplierSink(", void negative12() {
" new Supplier<>() {", supplierSink(
" @Override", new Supplier<>() {
" public Object get() {", @Override
" return getClass();", public Object get() {
" }", return getClass();
" });", }
" }", });
"", }
" void positive1() {",
" // BUG: Diagnostic contains:", void positive1() {
" callableSink((Callable<?>) null);", // BUG: Diagnostic contains:
" }", callableSink((Callable<?>) null);
"", }
" void positive2() {",
" // BUG: Diagnostic contains:", void positive2() {
" callableSink((Callable<?> & Iterable<?>) null);", // BUG: Diagnostic contains:
" }", callableSink((Callable<?> & Iterable<?>) null);
"", }
" void positive3() {",
" // BUG: Diagnostic contains:", void positive3() {
" callableSink(() -> getClass().getDeclaredConstructor());", // BUG: Diagnostic contains:
" }", callableSink(() -> getClass().getDeclaredConstructor());
"", }
" void positive4() {",
" // BUG: Diagnostic contains:", void positive4() {
" callableSink(getClass()::getDeclaredConstructor);", // BUG: Diagnostic contains:
" }", callableSink(getClass()::getDeclaredConstructor);
"", }
" void positive5() {",
" callableSink(", void positive5() {
" // BUG: Diagnostic contains:", callableSink(
" new Callable<>() {", // BUG: Diagnostic contains:
" @Override", new Callable<>() {
" public Object call() throws NoSuchMethodException {", @Override
" return getClass().getDeclaredConstructor();", public Object call() throws NoSuchMethodException {
" }", return getClass().getDeclaredConstructor();
" });", }
" }", });
"", }
" private static Object throwsRuntimeException() throws IllegalStateException {",
" return null;", private static Object throwsRuntimeException() throws IllegalStateException {
" }", return null;
"", }
" private static Object throwsError() throws AssertionError {",
" return null;", private static Object throwsError() throws AssertionError {
" }", return null;
"", }
" private static void callableSink(Callable<?> callable) {}",
"", private static void callableSink(Callable<?> callable) {}
" private static void supplierSink(Supplier<?> supplier) {}",
"}") private static void supplierSink(Supplier<?> supplier) {}
}
""")
.doTest(); .doTest();
} }