repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MisusedDayOfYearTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link MisusedDayOfYear}. */
@RunWith(JUnit4.class)
public final class MisusedDayOfYearTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(MisusedDayOfYear.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(MisusedDayOfYear.class, getClass());
@Test
public void positive() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.time.format.DateTimeFormatter;",
"class Test {",
" static {",
" DateTimeFormatter.ofPattern(\"yy-MM-DD\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.time.format.DateTimeFormatter;",
"class Test {",
" static {",
" DateTimeFormatter.ofPattern(\"yy-MM-dd\");",
" }",
"}")
.doTest();
}
@Test
public void noDayOfYear_noFinding() {
helper
.addSourceLines(
"Test.java",
"import java.time.format.DateTimeFormatter;",
"class Test {",
" static {",
" DateTimeFormatter.ofPattern(\"yy-MM-dd\");",
" }",
"}")
.doTest();
}
@Test
public void noMonthOfYear_noFinding() {
helper
.addSourceLines(
"Test.java",
"import java.time.format.DateTimeFormatter;",
"class Test {",
" static {",
" DateTimeFormatter.ofPattern(\"yy-DD\");",
" }",
"}")
.doTest();
}
@Test
public void escapedInQuotes() {
helper
.addSourceLines(
"Test.java",
"import java.time.format.DateTimeFormatter;",
"class Test {",
" static {",
" DateTimeFormatter.ofPattern(\"'D'yy-MM-dd\");",
" DateTimeFormatter.ofPattern(\"'D'''yy-MM-dd\");",
" DateTimeFormatter.ofPattern(\"'''D'yy-MM-dd\");",
" DateTimeFormatter.ofPattern(\"'D''D'yy-MM-dd\");",
" }",
"}")
.doTest();
}
@Test
public void escapedInQuotes_butAlsoAsSpecialChar() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.time.format.DateTimeFormatter;",
"class Test {",
" static {",
" DateTimeFormatter.ofPattern(\"'D'yy-MM-DD\");",
" DateTimeFormatter.ofPattern(\"'D'''yy-MM-DD\");",
" DateTimeFormatter.ofPattern(\"'''D'yy-MM-DD\");",
" DateTimeFormatter.ofPattern(\"'D''D'yy-MM-DD\");",
" DateTimeFormatter.ofPattern(\"'M'yy-DD\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.time.format.DateTimeFormatter;",
"class Test {",
" static {",
" DateTimeFormatter.ofPattern(\"'D'yy-MM-dd\");",
" DateTimeFormatter.ofPattern(\"'D'''yy-MM-dd\");",
" DateTimeFormatter.ofPattern(\"'''D'yy-MM-dd\");",
" DateTimeFormatter.ofPattern(\"'D''D'yy-MM-dd\");",
" DateTimeFormatter.ofPattern(\"'M'yy-DD\");",
" }",
"}")
.doTest();
}
}
| 4,236
| 31.343511
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IndexOfCharTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link IndexOfChar}Test */
@RunWith(JUnit4.class)
public class IndexOfCharTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(IndexOfChar.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {{",
" // BUG: Diagnostic contains: \"\".indexOf('$', 0);",
" \"\".indexOf(0, '$');",
" // BUG: Diagnostic contains: \"\".lastIndexOf('$', 0);",
" \"\".lastIndexOf(0, '$');",
"}}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {{",
" \"\".indexOf('$', 0);",
"}}")
.doTest();
}
}
| 1,636
| 28.232143
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OverrideThrowableToStringTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author mariasam@google.com (Maria Sam)
*/
@RunWith(JUnit4.class)
public class OverrideThrowableToStringTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(OverrideThrowableToString.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("OverrideThrowableToStringPositiveCases.java").doTest();
}
@Test
public void negativeCases() {
compilationHelper.addSourceFile("OverrideThrowableToStringNegativeCases.java").doTest();
}
@Test
public void fixes() {
BugCheckerRefactoringTestHelper.newInstance(OverrideThrowableToString.class, getClass())
.addInput("OverrideThrowableToStringPositiveCases.java")
.addOutput("OverrideThrowableToStringPositiveCases_expected.java")
.doTest(TestMode.AST_MATCH);
}
}
| 1,775
| 33.823529
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DifferentNameButSameTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link DifferentNameButSame}. */
@RunWith(JUnit4.class)
public final class DifferentNameButSameTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(DifferentNameButSame.class, getClass())
.addInputLines(
"TypeUseAnnotation.java",
"package pkg;",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Target;",
"@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})",
"@interface TypeUseAnnotation {}")
.expectUnchanged()
.addInputLines(
"A.java",
"package pkg;",
"public class A {",
" public static class B {",
" public static class C {",
" public static void foo() {}",
" }",
" }",
"}")
.expectUnchanged()
.addInputLines(
"ClassAnnotation.java",
"package pkg;",
"public @interface ClassAnnotation {",
" Class<?> value();",
"}")
.expectUnchanged();
@Test
public void classReferredToInTwoWays_usesShorterName() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"interface Test {",
" A.B test();",
" B test2();",
"}")
.addOutputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"interface Test {",
" B test();",
" B test2();",
"}")
.doTest();
}
@Test
public void fullyQualifiedType_notMentioned() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"interface Test {",
" A.B test();",
" pkg.A.B test2();",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void positive2() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"class Test {",
" B test() {",
" return new A.B();",
" }",
"}")
.addOutputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"class Test {",
" B test() {",
" return new B();",
" }",
"}")
.doTest();
}
@Test
public void classReferredToInMultipleWaysWithinMemberSelect() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"class Test {",
" B.C test() {",
" A.B.C.foo();",
" return null;",
" }",
"}")
.addOutputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"class Test {",
" B.C test() {",
" B.C.foo();",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void typeUseAnnotations_correctlyRefactored() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"interface Test {",
" A.@TypeUseAnnotation B test();",
" B test2();",
"}")
.addOutputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"interface Test {",
" @TypeUseAnnotation B test();",
" B test2();",
"}")
.doTest();
}
@Test
public void typeUseAnnotation_leftInCorrectPosition() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"interface Test {",
" @TypeUseAnnotation B test();",
" A.B test2();",
"}")
.addOutputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"interface Test {",
" @TypeUseAnnotation B test();",
" B test2();",
"}")
.doTest();
}
@Test
public void nameShadowed_noChange() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"interface Test {",
" interface B {",
" B get();",
" }",
" Test.B get();",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void doesNotRefactorOutsideOuterClass() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"@ClassAnnotation(A.B.C.class)",
"class D extends A.B {",
" private C c;",
" private C c2;",
"}")
.addOutputLines(
"Test.java",
"package pkg;",
"@ClassAnnotation(A.B.C.class)",
"class D extends A.B {",
" private A.B.C c;",
" private A.B.C c2;",
"}")
.doTest();
}
@Test
public void genericsNotRefactored() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"interface Test {",
" interface A<T> {",
" interface D {}",
" }",
" class B implements A<Long> {}",
" class C implements A<String> {}",
" B.D b();",
" C.D c();",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void typesDefinedWithinSameFileIgnored() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"interface Test {",
" interface Foo {",
" Foo foo();",
" }",
" Test.Foo foo();",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void typesWhichMakePoorImports_disfavoured() {
helper
.addInputLines("Foo.java", "package pkg;", "interface Foo {", " interface Builder {}", "}")
.expectUnchanged()
.addInputLines(
"Test.java",
"package pkg;",
"import pkg.Foo.Builder;",
"interface Test {",
" Foo.Builder a();",
" Builder b();",
"}")
.addOutputLines(
"Test.java",
"package pkg;",
"import pkg.Foo.Builder;",
"interface Test {",
" Foo.Builder a();",
" Foo.Builder b();",
"}")
.doTest();
}
@Test
public void classClashesWithVariableName() {
helper
.addInputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"class Test {",
" A.B test(Object B) {",
" return new A.B();",
" }",
" B test2() {",
" return null;",
" }",
"}")
.addOutputLines(
"Test.java",
"package pkg;",
"import pkg.A.B;",
"class Test {",
" A.B test(Object B) {",
" return new A.B();",
" }",
" A.B test2() {",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void innerClassConstructor() {
BugCheckerRefactoringTestHelper.newInstance(DifferentNameButSame.class, getClass())
.addInputLines(
"A.java", //
"package pkg;",
"class A {",
" class B {}",
"}")
.expectUnchanged()
.addInputLines(
"Test.java",
"package pkg;",
"class Test {",
" static void f(A a) {",
" A.B b = a.new B();",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| 8,934
| 25.671642
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ErroneousBitwiseExpressionTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link ErroneousBitwiseExpression}. */
@RunWith(JUnit4.class)
public final class ErroneousBitwiseExpressionTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(ErroneousBitwiseExpression.class, getClass());
@Test
public void bitwiseAnd() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" // BUG: Diagnostic contains: 1 | 2",
" double flags = 1 & 2;",
"}")
.doTest();
}
@Test
public void bitwiseAnd_noFinding() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" double flags = 2 & 10;",
"}")
.doTest();
}
}
| 1,539
| 28.615385
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/PackageInfoTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link PackageInfo}Test */
@RunWith(JUnit4.class)
public class PackageInfoTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(PackageInfo.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"test/package-info.java", //
"package test;",
"// BUG: Diagnostic contains:",
"class Test {}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"test/package-info.java", //
"package test;")
.doTest();
}
}
| 1,416
| 27.34
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ComparableTypeTest.java
|
/* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ComparableType}Test */
@RunWith(JUnit4.class)
public class ComparableTypeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ComparableType.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("ComparableTypePositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("ComparableTypeNegativeCases.java").doTest();
}
}
| 1,270
| 31.589744
| 81
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BigDecimalLiteralDoubleTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link BigDecimalLiteralDouble}.
*
* @author endobson@google.com (Eric Dobson)
*/
@RunWith(JUnit4.class)
public class BigDecimalLiteralDoubleTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(BigDecimalLiteralDouble.class, getClass());
@Test
public void exactlyRepresentable() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.math.BigDecimal;",
"class Test {",
" void test() {",
" new BigDecimal(\"99\");",
" new BigDecimal(\"99.0\");",
" new BigDecimal(123_459);",
" new BigDecimal(123_456L);",
" BigDecimal.valueOf(123);",
" BigDecimal.valueOf(123L);",
" }",
"}")
.doTest();
}
@Test
public void losesPrecision() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.math.BigDecimal;",
"class Test {",
" void test() {",
" // BUG: Diagnostic matches: A",
" new BigDecimal(-0.012);",
" // BUG: Diagnostic matches: B",
" new BigDecimal(0.1f);",
" // BUG: Diagnostic matches: C",
" new BigDecimal(0.99);",
" }",
"}")
.expectErrorMessage(
"A",
message ->
message.contains("-0.0120000000000000002498001805406602215953171253204345703125")
&& message.contains("new BigDecimal(\"-0.012\")"))
.expectErrorMessage(
"B",
message ->
message.contains("0.100000001490116119384765625")
&& message.contains("new BigDecimal(\"0.1\")"))
.expectErrorMessage(
"C",
message ->
message.contains("0.9899999999999999911182158029987476766109466552734375")
&& message.contains("new BigDecimal(\"0.99\")"))
.doTest();
}
}
| 2,874
| 31.670455
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryAssignmentTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link UnnecessaryAssignment}. */
@RunWith(JUnit4.class)
public final class UnnecessaryAssignmentTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(UnnecessaryAssignment.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryAssignment.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java", //
"import org.mockito.Mock;",
"class Test {",
" // BUG: Diagnostic contains:",
" @Mock Object mockObject = new Object();",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java", //
"import org.mockito.Mock;",
"class Test {",
" @Mock Object mockObject;",
"}")
.doTest();
}
@Test
public void doubleAnnotation() {
testHelper
.addSourceLines(
"Test.java", //
"import com.google.inject.Inject;",
"import org.mockito.Mock;",
"class Test {",
" // BUG: Diagnostic contains: both",
" @Mock @Inject Object mockObject;",
"}")
.doTest();
}
@Test
public void refactoring() {
refactoringHelper
.addInputLines(
"Test.java", //
"import org.mockito.Mock;",
"class Test {",
" @Mock Object mockObject = new Object();",
"}")
.addOutputLines(
"Test.java", //
"import org.mockito.Mock;",
"class Test {",
" @Mock Object mockObject;",
"}")
.doTest();
}
@Test
public void initializedViaInitMocks() {
refactoringHelper
.addInputLines(
"Test.java",
"import org.mockito.Mock;",
"import org.mockito.Mockito;",
"import org.mockito.MockitoAnnotations;",
"class Test {",
" @Mock Object mockObject = Mockito.mock(Object.class);",
" void before() {",
" MockitoAnnotations.initMocks(this);",
" }",
"}")
.addOutputLines(
"Test.java",
"import org.mockito.Mock;",
"import org.mockito.Mockito;",
"import org.mockito.MockitoAnnotations;",
"class Test {",
" @Mock Object mockObject;",
" void before() {",
" MockitoAnnotations.initMocks(this);",
" }",
"}")
.doTest();
}
@Test
public void noInitializerPresent_retainManualInitialization() {
refactoringHelper
.addInputLines(
"Test.java", //
"import org.mockito.Mock;",
"import org.mockito.Mockito;",
"class Test {",
" @Mock Object mockObject = Mockito.mock(Object.class);",
"}")
.addOutputLines(
"Test.java", //
"import org.mockito.Mock;",
"import org.mockito.Mockito;",
"class Test {",
" Object mockObject = Mockito.mock(Object.class);",
"}")
.doTest();
}
@Test
public void initializedViaRunner() {
refactoringHelper
.addInputLines(
"Test.java", //
"import org.junit.runner.RunWith;",
"import org.mockito.Mock;",
"import org.mockito.Mockito;",
"import org.mockito.junit.MockitoJUnitRunner;",
"@RunWith(MockitoJUnitRunner.class)",
"public class Test {",
" @Mock Object mockObject = Mockito.mock(Object.class);",
"}")
.addOutputLines(
"Test.java", //
"import org.junit.runner.RunWith;",
"import org.mockito.Mock;",
"import org.mockito.Mockito;",
"import org.mockito.junit.MockitoJUnitRunner;",
"@RunWith(MockitoJUnitRunner.class)",
"public class Test {",
" @Mock Object mockObject;",
"}")
.doTest();
}
@Test
public void positiveOnTestParameter() {
testHelper
.addSourceLines(
"Test.java", //
"import com.google.testing.junit.testparameterinjector.TestParameter;",
"class Test {",
" // BUG: Diagnostic contains: @TestParameter",
" @TestParameter boolean myFoo = false;",
"}")
.doTest();
}
@Test
public void optionalInject_notFlagged() {
testHelper
.addSourceLines(
"Test.java", //
"import com.google.inject.Inject;",
"class Test {",
" @Inject(optional = true) boolean myFoo = false;",
"}")
.doTest();
}
@Test
public void fixForTestParameter_deletesAssignment() {
refactoringHelper
.addInputLines(
"Test.java", //
"import com.google.testing.junit.testparameterinjector.TestParameter;",
"class Test {",
" @TestParameter boolean myFoo = false;",
"}")
.addOutputLines(
"Test.java", //
"import com.google.testing.junit.testparameterinjector.TestParameter;",
"class Test {",
" @TestParameter boolean myFoo;",
"}")
.doTest();
}
@Test
public void fixForTestParameter_ifFinal_deletesAnnotation() {
refactoringHelper
.addInputLines(
"Test.java", //
"import com.google.testing.junit.testparameterinjector.TestParameter;",
"class Test {",
" @TestParameter final boolean myFoo = false;",
"}")
.addOutputLines(
"Test.java", //
"import com.google.testing.junit.testparameterinjector.TestParameter;",
"class Test {",
" final boolean myFoo = false;",
"}")
.doTest();
}
}
| 6,924
| 29.641593
| 91
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/PackageLocationTest.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link PackageLocation}Test */
@RunWith(JUnit4.class)
public class PackageLocationTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(PackageLocation.class, getClass());
@Test
public void positiveCustomRoot() {
compilationHelper
.addSourceLines(
"src/main/java/a/b/A.java",
"// BUG: Diagnostic contains: Expected package a to be declared in a directory "
+ "ending with a, instead found b",
"package a;",
"class A {}")
.doTest();
}
@Test
public void positiveTooLong() {
compilationHelper
.addSourceLines(
"src/main/java/A.java",
"// BUG: Diagnostic contains: Expected package a.b.c to be declared in a directory "
+ "ending with a/b/c, instead found src/main/java",
"package a.b.c;",
"class A {}")
.doTest();
}
@Test
public void positiveTooShort() {
compilationHelper
.addSourceLines(
"java/b/c/d/A.java",
"// BUG: Diagnostic contains: Expected package a.b.c.d to be declared in a directory "
+ "ending with a/b/c/d, instead found java/b/c/d",
"package a.b.c.d;",
"class A {}")
.doTest();
}
@Test
public void positiveTooShortSuffix() {
compilationHelper
.addSourceLines(
"panda/b/c/d/A.java",
"// BUG: Diagnostic contains: Expected package a.b.c.d to be declared in a directory "
+ "ending with a/b/c/d, instead found panda/b/c/d",
"package a.b.c.d;",
"class A {}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"a/A.java", //
"package a;",
"class A {}")
.doTest();
}
@Test
public void negative2() {
compilationHelper
.addSourceLines(
"a/b/c/A.java", //
"package a.b.c;",
"class A {}")
.doTest();
}
@Test
public void negativeSuffix() {
compilationHelper
.addSourceLines(
"src/main/java/a/b/A.java", //
"package a.b;",
"class A {}")
.doTest();
}
@Test
public void suppression() {
compilationHelper
.addSourceLines(
"java/com/google/foo/package-info.java",
"@com.google.errorprone.annotations.SuppressPackageLocation",
"package xyz.abc.foo;")
.addSourceLines(
"java/com/google/foo/A.java", //
"package xyz.abc.foo;",
"class A {}")
.doTest();
}
}
| 3,490
| 27.382114
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ThrowIfUncheckedKnownCheckedTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
@RunWith(JUnit4.class)
public class ThrowIfUncheckedKnownCheckedTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ThrowIfUncheckedKnownChecked.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("ThrowIfUncheckedKnownCheckedTestPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("ThrowIfUncheckedKnownCheckedTestNegativeCases.java").doTest();
}
}
| 1,350
| 32.775
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OptionalEqualityTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cushon@google.com (Liam Miller-Cushon)
*/
@RunWith(JUnit4.class)
public class OptionalEqualityTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(OptionalEquality.class, getClass());
@Test
public void positiveCase_equal() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Optional<Integer> a, Optional<Integer> b) {",
" // BUG: Diagnostic contains: a.equals(b)",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void positiveCase_notEqual() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Optional<Integer> a, Optional<Integer> b) {",
" // BUG: Diagnostic contains: !a.equals(b)",
" return a != b;",
" }",
"}")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Optional<Integer> b) {",
" return b == null;",
" }",
"}")
.doTest();
}
@Test
public void maybeNull() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Optional<Integer> a) {",
" Optional<Integer> b = Optional.of(42);",
" // BUG: Diagnostic contains: Did you mean 'return Objects.equals(a, b);' or"
+ " 'return a.equals(b);'?",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void maybeNull_prefersAlreadyImportedHelper() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Objects;",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Optional<Integer> a) {",
" Optional<Integer> b = Optional.of(42);",
" // BUG: Diagnostic contains: Did you mean 'return Objects.equal(a, b);' or 'return"
+ " a.equals(b);'?",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void definitelyNull() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f() {",
" Optional<Integer> a = null;",
" Optional<Integer> b = Optional.of(42);",
" // BUG: Diagnostic contains: Did you mean 'return Objects.equals(a, b);'?",
" return a == b;",
" }",
"}")
.doTest();
}
}
| 3,910
| 29.317829
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ThreadLocalUsageTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ThreadLocalUsage}Test */
@RunWith(JUnit4.class)
public class ThreadLocalUsageTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(ThreadLocalUsage.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"ThreadLocalUsage.java", //
"class ThreadLocalUsage {",
" // BUG: Diagnostic contains:",
" ThreadLocal<Object> local = new ThreadLocal<>();",
" {",
" new ThreadLocal<>();",
" new ThreadLocal<Object>() {};",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" static final ThreadLocal<Object> local = new ThreadLocal<>();",
"}")
.doTest();
}
@Test
public void negativeWellKnownTypes() {
testHelper
.addSourceLines(
"Test.java", //
"import java.text.DateFormat;",
"import java.text.SimpleDateFormat;",
"class Test {",
" final ThreadLocal<Boolean> a = new ThreadLocal<>();",
" final ThreadLocal<Long> b = new ThreadLocal<>();",
" final ThreadLocal<DateFormat> c = new ThreadLocal<>();",
" final ThreadLocal<SimpleDateFormat> d = new ThreadLocal<>();",
"}")
.doTest();
}
@Test
public void negativeSingleton() {
testHelper
.addSourceLines(
"Singleton.java", //
"@interface Singleton {}")
.addSourceLines(
"Test.java", //
"@Singleton",
"class Test {",
" final ThreadLocal<Object> a = new ThreadLocal<>();",
"}")
.doTest();
}
}
| 2,644
| 28.719101
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LongLiteralLowerCaseSuffixTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Test cases for {@link LongLiteralLowerCaseSuffix}.
*
* @author Simon Nickerson (sjnickerson@google.com)
*/
@RunWith(JUnit4.class)
public class LongLiteralLowerCaseSuffixTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(LongLiteralLowerCaseSuffix.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("LongLiteralLowerCaseSuffixPositiveCase1.java").doTest();
}
/** Test for Java 7 integer literals that include underscores. */
@Test
public void java7PositiveCase() {
compilationHelper.addSourceFile("LongLiteralLowerCaseSuffixPositiveCase2.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("LongLiteralLowerCaseSuffixNegativeCases.java").doTest();
}
@Test
public void disableable() {
compilationHelper
.setArgs(ImmutableList.of("-Xep:LongLiteralLowerCaseSuffix:OFF"))
.expectNoDiagnostics()
.addSourceFile("LongLiteralLowerCaseSuffixPositiveCase1.java")
.doTest();
}
}
| 1,924
| 30.557377
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CatchingUncheckedTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link CatchingUnchecked}. */
@RunWith(JUnit4.class)
public final class CatchingUncheckedTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(CatchingUnchecked.class, getClass());
@Test
public void positive() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" this.hashCode();",
" // BUG: Diagnostic contains:",
" } catch (Exception e) {}",
" }",
"}")
.doTest();
}
@Test
public void positiveMultiCatch() {
helper
.addSourceLines(
"Test.java",
"import java.io.IOException;",
"class Test {",
" void test() {",
" try {",
" throw new IOException();",
" } catch (IOException e) {",
" // BUG: Diagnostic contains:",
" } catch (Exception e) {}",
" }",
"}")
.doTest();
}
@Test
public void negative() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" throw new Exception();",
" } catch (Exception e) {",
" }",
" }",
"}")
.doTest();
}
}
| 2,226
| 26.8375
| 77
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InvalidZoneIdTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@RunWith(JUnit4.class)
public class InvalidZoneIdTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(InvalidZoneId.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"import java.time.ZoneId;",
"class A {",
" private static final String TIMEZONE_ID = \"unknown\";",
" public static void test() {",
" // BUG: Diagnostic contains:",
" ZoneId.of(\"\");",
" // BUG: Diagnostic contains:",
" ZoneId.of(\"unknown\");",
" // BUG: Diagnostic contains:",
" ZoneId.of(TIMEZONE_ID);",
" // BUG: Diagnostic contains:",
" ZoneId.of(\"America/Los_Angele\");",
" // BUG: Diagnostic contains:",
" ZoneId.of(\"America/Los Angeles\");",
" // BUG: Diagnostic contains:",
" ZoneId.of(\"KST\");",
" }",
" public static void invalidCustomIDs() {",
" // BUG: Diagnostic contains:",
" ZoneId.of(\"GMT+24\");",
" // BUG: Diagnostic contains:",
" ZoneId.of(\"GMT1\");",
" // BUG: Diagnostic contains:",
" ZoneId.of(\"GMT/0\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"import java.time.ZoneId;",
"class A {",
" private static final String TIMEZONE_ID = \"America/New_York\";",
" public static void ianaIDs() {",
" ZoneId.of(\"America/Los_Angeles\");",
" ZoneId.of(TIMEZONE_ID);",
" ZoneId.of(\"Europe/London\");",
" }",
" public static void customIDs() {",
" // Custom IDs",
" ZoneId.of(\"GMT+0\");",
" ZoneId.of(\"GMT+00\");",
" ZoneId.of(\"GMT+00:00\");",
" ZoneId.of(\"GMT+00:00:00\");",
" }",
" public static void twoLetterIDs() {",
" ZoneId.of(\"UT\");",
" }",
" public static void threeLetterIDs() {",
" ZoneId.of(\"GMT\");",
" ZoneId.of(\"UTC\");",
" }",
"}")
.doTest();
}
}
| 3,398
| 32.99
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TypeParameterShadowingTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link TypeParameterShadowing} */
@RunWith(JUnit4.class)
public class TypeParameterShadowingTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(TypeParameterShadowing.class, getClass());
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(TypeParameterShadowing.class, getClass());
@Test
public void singleLevel() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test<T> {",
" // BUG: Diagnostic contains: T declared in Test",
" <T> void something() {}",
"}")
.doTest();
}
@Test
public void staticNotFlagged() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test<T> {",
" static <T> void something() {}",
"}")
.doTest();
}
@Test
public void staticMethodInnerDoesntConflictWithOuter() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test<D> {",
" static <T> void something() {",
" class MethodInner<D> {}", // Doesn't clash with Test<D>
" class MethodInner2 {",
" // BUG: Diagnostic contains: T declared in something",
" <T> void clashingMethod() {}",
" <D> void nonClashingMethod() {}", // <D> not in scope
" }",
" }",
"}")
.doTest();
}
@Test
public void nestedClassDeclarations() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test<D> {",
" // BUG: Diagnostic contains: D declared in Test",
" class Test2<D> {}",
"}")
.doTest();
}
@Test
public void twoLevels() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test<T> {",
" class MyTest<J> {",
" // BUG: Diagnostic matches: combo",
" public <T,J> void something() {}",
" }",
"}")
.expectErrorMessage(
"combo", s -> s.contains("J declared in MyTest") && s.contains("T declared in Test"))
.doTest();
}
@Test
public void renameTypeVar() {
refactoring
.addInputLines(
"in/Test.java",
"package foo.bar;",
"class Test<T> {",
" /** @param <T> foo */",
" <T> void something(T t) { T other = t;}",
"}")
.addOutputLines(
"out/Test.java",
"package foo.bar;",
"class Test<T> {",
" /** @param <T2> foo */",
" <T2> void something(T2 t) { T2 other = t;}",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void renameRecursiveBound() {
refactoring
.addInputLines(
"in/Test.java",
"package foo.bar;",
"class Test<T> {",
" <T extends Comparable<T>> void something(T t) { T other = t;}",
"}")
.addOutputLines(
"out/Test.java",
"package foo.bar;",
"class Test<T> {",
" <T2 extends Comparable<T2>> void something(T2 t) { T2 other = t;}",
"}")
.doTest();
}
@Test
public void refactorUnderneathStuff() {
refactoring
.addInputLines(
"in/Test.java",
"package foo.bar;",
"class Test<T> {",
" <T> void something(T t) { T other = t;}",
" <T> T identity(T t) { return t; }",
"}")
.addOutputLines(
"out/Test.java",
"package foo.bar;",
"class Test<T> {",
" <T2> void something(T2 t) { T2 other = t;}",
" <T2> T2 identity(T2 t) { return t; }",
"}")
.doTest();
}
@Test
public void refactorMultipleVars() {
refactoring
.addInputLines(
"in/Test.java",
"package foo.bar;",
"class Test<T,D> {",
" <T,D> void something(T t) { ",
" T other = t;",
" java.util.List<T> ts = new java.util.ArrayList<T>();",
" D d = null; ",
" }",
"}")
.addOutputLines(
"out/Test.java",
"package foo.bar;",
"class Test<T,D> {",
" <T2,D2> void something(T2 t) { ",
" T2 other = t;",
" java.util.List<T2> ts = new java.util.ArrayList<T2>();",
" D2 d = null; ",
" }",
"}")
.doTest();
}
@Test
public void refactorWithNestedTypeParameterDeclaration() {
// The nested @SuppressWarnings are because there will be multiple findings
// (T is shadowed multiple times). We're trying to test all of the fixes suggested by the
// finding generated from the outermost instance method, namely that it doesn't attempt to
// rewrite symbols T that don't match the T we're rewriting.
refactoring
.addInputLines(
"in/Test.java",
"package foo.bar;",
"class Test<T> {",
" <T,T2> void something(T t) { ",
" T var = t;",
" @SuppressWarnings(\"TypeParameterShadowing\")",
" class MethodInnerWithGeneric<T> {}",
" MethodInnerWithGeneric<T> innerVar = null;",
" class MethodInner {",
" @SuppressWarnings(\"TypeParameterShadowing\")",
" <T> void doSomething() {}",
" void doSomethingElse(T t) { this.<T>doSomething(); }",
" }",
" MethodInner myInner = null;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"package foo.bar;",
"class Test<T> {",
" <T3,T2> void something(T3 t) { ",
" T3 var = t;",
" @SuppressWarnings(\"TypeParameterShadowing\")",
" class MethodInnerWithGeneric<T> {}",
" MethodInnerWithGeneric<T3> innerVar = null;",
" class MethodInner {",
" @SuppressWarnings(\"TypeParameterShadowing\")",
" <T> void doSomething() {}",
" void doSomethingElse(T3 t) { this.<T3>doSomething(); }",
" }",
" MethodInner myInner = null;",
" }",
"}")
.doTest();
}
@Test
public void refactorCheckForExisting() {
refactoring
.addInputLines(
"in/Test.java",
"package foo.bar;",
"class Test<T> {",
" class A<T2,T3,T4> {",
" <T> void something(T t) { ",
" T var = t;",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"package foo.bar;",
"class Test<T> {",
" class A<T2,T3,T4> {",
" <T5> void something(T5 t) { ",
" T5 var = t;",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactorMethodInnerInner() {
refactoring
.addInputLines(
"in/Test.java",
"package foo.bar;",
"class Test<T> {",
" static <D> void something(D t) {",
" class B {",
" class C<T,D> {}",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"package foo.bar;",
"class Test<T> {",
" static <D> void something(D t) {",
" class B {",
// T isn't accessible to the inner since the method is static
" class C<T,D2> {}",
" }",
" }",
"}")
.doTest();
}
// don't try to read type parameters off the enclosing local variable declaration
@Test
public void symbolWithoutTypeParameters() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"import java.util.Map;",
"import java.util.Comparator;",
"class Test {",
" static Comparator<Map.Entry<Integer, String>> ENTRY_COMPARATOR =",
" new Comparator<Map.Entry<Integer, String>>() {",
" public int compare(",
" Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {",
" return 0;",
" }",
" private <T extends Comparable> int c(T o1, T o2) {",
" return 0;",
" }",
" };",
"}")
.doTest();
}
@Test
public void lambdaParameterDesugaring() {
refactoring
.addInputLines(
"in/A.java",
"import java.util.function.Consumer;",
"class A<T> {",
" abstract class B<T> {",
" void f() {",
" g(t -> {});",
" }",
" abstract void g(Consumer<T> c);",
" }",
"}")
.addOutputLines(
"out/A.java",
"import java.util.function.Consumer;",
"class A<T> {",
" abstract class B<T2> {",
" void f() {",
" g(t -> {});",
" }",
" abstract void g(Consumer<T2> c);",
" }",
"}")
.doTest();
}
@Test
public void typesWithBounds() {
refactoring
.addInputLines(
"in/Test.java",
"import java.util.function.Predicate;",
"class Test<T> {",
" <B extends Object & Comparable> void something(B b) {",
" class Foo<B extends Object & Comparable> implements Predicate<B> {",
" public boolean test(B b) { return false; }",
" }",
" new Foo<>();",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.function.Predicate;",
"class Test<T> {",
" <B extends Object & Comparable> void something(B b) {",
" class Foo<B2 extends Object & Comparable> implements Predicate<B2> {",
" public boolean test(B2 b) { return false; }",
" }",
" new Foo<>();",
" }",
"}")
.doTest();
}
}
| 11,717
| 30.67027
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EqualsNullTest.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link EqualsNull} check. */
@RunWith(JUnit4.class)
public class EqualsNullTest {
private static final String EXPECTED_BUG_COMMENT =
"// BUG: Diagnostic contains: x.equals(null) should return false";
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(EqualsNull.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(EqualsNull.class, getClass());
@Test
public void negativeSimpleCase() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean m(Object x, Object y) {",
" return x.equals(y);",
" }",
"}")
.doTest();
}
@Test
public void negativeJUnit4TestClass() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(JUnit4.class)",
"class Test {",
" boolean m(Object x) {",
" return x.equals(null);",
" }",
"}")
.doTest();
}
@Test
public void negativeTestNgTestClass() {
compilationTestHelper
.addSourceLines(
"org/testng/annotations/Test.java",
"package org.testng.annotations;",
"public @interface Test {",
"}")
.addSourceLines(
"MyTest.java",
"import org.testng.annotations.Test;",
"@Test",
"class MyTest {",
" boolean m(Object x) {",
" return x.equals(null);",
" }",
"}")
.doTest();
}
@Test
public void negativeAssertClass() {
compilationTestHelper
.addSourceLines(
"AssertHelper.java",
"import org.junit.Assert;",
"class AssertHelper extends Assert {",
" public static void myAssert(Object x) {",
" x.equals(null);",
" }",
"}")
.doTest();
}
@Test
public void negativeEnclosedByJUnitAssert() {
compilationTestHelper
.addSourceLines(
"TestHelper.java",
"import static org.junit.Assert.assertFalse;",
"class TestHelper {",
" public static void myAssert(Object x) {",
" assertFalse(x.equals(null));",
" }",
"}")
.doTest();
}
@Test
public void negativeEnclosedByTruthAssert() {
compilationTestHelper
.addSourceLines(
"TestHelper.java",
"import static com.google.common.truth.Truth.assertThat;",
"class TestHelper {",
" public static void myAssert(Object x) {",
" assertThat(x.equals(null)).isFalse();",
" }",
"}")
.doTest();
}
@Test
public void positiveSimpleCase() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean m(Object x) {",
EXPECTED_BUG_COMMENT,
" return x.equals(null);",
" }",
"}")
.doTest();
}
@Test
public void positiveReturnObjectEqualsNullFix() {
refactoringTestHelper
.addInputLines(
"in/Test.java",
"class Test {",
" boolean m(Object x) {",
" return x.equals(null);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" boolean m(Object x) {",
" return x == null;",
" }",
"}")
.doTest();
}
@Test
public void positiveReturnObjectNotEqualsNullFix() {
refactoringTestHelper
.addInputLines(
"in/Test.java",
"class Test {",
" boolean m(Object x) {",
" return !x.equals(null);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" boolean m(Object x) {",
" return x != null;",
" }",
"}")
.doTest();
}
@Test
public void positiveIfObjectEqualsNullFix() {
refactoringTestHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void m(Object x) {",
" if (x.equals(null)) {",
" return;",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void m(Object x) {",
" if (x == null) {",
" return;",
" }",
" }",
"}")
.doTest();
}
@Test
public void positiveMethodReturnValueNotEqualsNullFix() {
refactoringTestHelper
.addInputLines(
"in/Test.java",
"class Test {",
" boolean m(Object x) {",
" return !x.toString().equals(null);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" boolean m(Object x) {",
" return x.toString() != null;",
" }",
"}")
.doTest();
}
}
| 6,287
| 26.823009
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IntLongMathTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link IntLongMath}Test. */
@RunWith(JUnit4.class)
public final class IntLongMathTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(IntLongMath.class, getClass());
@Test
public void ignoreNonWideningAssignments() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" int f(int x) {",
" return x + 3;",
" }",
" long g(long x) {",
" return x + 3;",
" }",
" int h(long x) {",
" return (int) (x + 3);",
" }",
" long i(int x) {",
" // BUG: Diagnostic contains: x + 3L",
" return x + 3;",
" }",
"}")
.doTest();
}
@Test
public void lambda() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" interface F {",
" long f(int i);",
" }",
" F f = i -> {",
" // BUG: Diagnostic contains: return i + 3L",
" return i + 3;",
" };",
"}")
.doTest();
}
@Test
public void refactoring() {
BugCheckerRefactoringTestHelper.newInstance(IntLongMath.class, getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" static final int MILLION = 1_000_000;",
" long f(int x) {",
" long r = (x + 3) * MILLION / 3;",
" r = (x / 3) * MILLION / 3;",
" r = x / 3;",
" r = x + 3;",
" return r;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" static final int MILLION = 1_000_000;",
" long f(int x) {",
" long r = (x + 3L) * MILLION / 3;",
" r = (long) (x / 3) * MILLION / 3;",
" r = x / 3;",
" r = x + 3L;",
" return r;",
" }",
"}")
.doTest();
}
}
| 3,062
| 29.029412
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NegativeCharLiteralTest.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link NegativeCharLiteral}Test */
@RunWith(JUnit4.class)
public class NegativeCharLiteralTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NegativeCharLiteral.class, getClass());
@Test
public void positive_literalNegativeOne() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" // BUG: Diagnostic contains: 'char x = Character.MAX_VALUE;'",
" char x = (char) -1;",
"}")
.doTest();
}
@Test
public void positive_literalNegativeTwo() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" // BUG: Diagnostic contains: 'char x = Character.MAX_VALUE - 1;'",
" char x = (char) -2;",
"}")
.doTest();
}
@Test
public void positive_literalOneLessThanMultipleOf65536() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" // BUG: Diagnostic contains: 'char x = Character.MAX_VALUE;'",
" char x = (char) -65537;",
"}")
.doTest();
}
@Test
public void positive_longLiteral() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" // BUG: Diagnostic contains: 'char x = Character.MAX_VALUE;'",
" char x = (char) -1L;",
"}")
.doTest();
}
@Test
public void positive_multipleOverflow() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" // BUG: Diagnostic contains: 'char x = Character.MAX_VALUE - 38527;'",
" char x = (char) -10000000;",
"}")
.doTest();
}
@Test
public void negative_zeroLiteral() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" char x = (char) 0;",
"}")
.doTest();
}
@Test
public void negative_positiveLiteral() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" char x = (char) 1;",
"}")
.doTest();
}
@Test
public void negative_castToTypeNotChar() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" int x = (int) -1;",
"}")
.doTest();
}
}
| 3,322
| 25.798387
| 85
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditionsTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author mariasam@google.com (Maria Sam)
* @author sulku@google.com (Marsela Sulku)
*/
@RunWith(JUnit4.class)
public class NestedInstanceOfConditionsTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NestedInstanceOfConditions.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("NestedInstanceOfConditionsPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("NestedInstanceOfConditionsNegativeCases.java").doTest();
}
}
| 1,383
| 30.454545
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StringBuilderInitWithCharTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author lowasser@google.com (Louis Wasserman)
*/
@RunWith(JUnit4.class)
public class StringBuilderInitWithCharTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(StringBuilderInitWithChar.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("StringBuilderInitWithCharPositiveCases.java").doTest();
}
@Test
public void negativeCases() {
compilationHelper.addSourceFile("StringBuilderInitWithCharNegativeCases.java").doTest();
}
}
| 1,343
| 30.255814
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ImmutableMemberCollectionTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ImmutableMemberCollection}. */
@RunWith(JUnit4.class)
public final class ImmutableMemberCollectionTest {
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(ImmutableMemberCollection.class, getClass());
@Test
public void listInitInline_notMutated_replacesTypeWithImmutableList() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.List;",
"class Test {",
" private final List<String> myList = ImmutableList.of(\"a\");",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.List;",
"class Test {",
" private final ImmutableList<String> myList = ImmutableList.of(\"a\");",
"}")
.doTest();
}
@Test
public void setInitConstructor_notMutatedButSuppressed_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.List;",
"class Test {",
" @SuppressWarnings(\"ImmutableMemberCollection\")",
" private final List<String> myList;",
" Test(List<String> myList) {",
" this.myList = myList;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void listInitConstructor_notMutated_replacesTypeWithImmutableList() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.List;",
"class Test {",
" private final List<String> myList;",
" private List<String> doNotTouchThisList;",
" Test() {",
" myList = ImmutableList.of(\"a\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.List;",
"class Test {",
" private final ImmutableList<String> myList;",
" private List<String> doNotTouchThisList;",
" Test() {",
" myList = ImmutableList.of(\"a\");",
" }",
"}")
.doTest();
}
@Test
public void listInitInline_bindAnnotation_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.inject.testing.fieldbinder.Bind;",
"import java.util.List;",
"class Test {",
" @Bind private final List<String> myList = ImmutableList.of(\"a\");",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void setInit_mutableTypeInConstructor_mutated_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Set;",
"import java.util.HashSet;",
"class Test {",
" private final Set<String> mySet;",
" Test() {",
" mySet = new HashSet<>();",
" }",
" private void myFunc() {",
" mySet.add(\"myString\");",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void setInit_mutableTypeInConstructor_returnedAsIs_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Set;",
"import java.util.HashSet;",
"class Test {",
" private final Set<String> mySet = new HashSet<String>();",
" private Set<String> myFunc() {",
" return mySet;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void setInit_mutableTypeInConstructor_returnedInConditional_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Set;",
"import java.util.HashSet;",
"class Test {",
" private final Set<String> mySet = new HashSet<String>();",
" private Set<String> myFunc() {",
" return 1 > 2 ? new HashSet<String>() : mySet;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void setInit_mutableTypeInStaticBlock_mutated_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Set;",
"import java.util.HashSet;",
"class Test {",
" private static final Set<String> mySet;",
" static {",
" mySet = new HashSet<>();",
" }",
" private static void myFunc() {",
" mySet.add(\"myString\");",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void setInit_mutableTypeInStaticBlock_passedToAnotherFunction_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Set;",
"import java.util.HashSet;",
"class Test {",
" private static final Set<String> mySet;",
" static {",
" mySet = new HashSet<>();",
" }",
" private static void myFunc() {",
" System.out.println(mySet);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void listInitWithMutableType_notMutated_replacesTypeAndMakesDefensiveCopy() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.List;",
"import java.util.ArrayList;",
"class Test {",
" private final List<String> myList1 = new ArrayList<>();",
" private final List<String> myList2;",
" Test() {",
" myList2 = new ArrayList<>();",
" }",
" Test(String x) {",
" myList2 = ImmutableList.of(x);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.List;",
"import java.util.ArrayList;",
"class Test {",
" private final ImmutableList<String> myList1 = ",
" ImmutableList.copyOf(new ArrayList<>());",
" private final ImmutableList<String> myList2;",
" Test() {",
" myList2 = ImmutableList.copyOf(new ArrayList<>());",
" }",
" Test(String x) {",
" myList2 = ImmutableList.of(x);",
" }",
"}")
.doTest();
}
@Test
public void listInitWithMutableType_invokesReadOnlyMethods_replacesTypeAndMakesDefensiveCopy() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" private final List<String> myList = new ArrayList<>();",
" private String myFunc() {",
" return myList.get(0);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" private final ImmutableList<String> myList = ",
" ImmutableList.copyOf(new ArrayList<>());",
" private String myFunc() {",
" return myList.get(0);",
" }",
"}")
.doTest();
}
@Test
public void setMutation_thisReference_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import java.util.Set;",
"import java.util.HashSet;",
"class Test {",
" private final ImmutableSet<String> mySet;",
" Test() {",
" mySet = ImmutableSet.of();",
" }",
" private static final class Builder {",
" private final Set<String> mySet = new HashSet<>();",
" public void addString(String x) {",
" this.mySet.add(x);",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void setInNestedClassMutationInParent_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import java.util.Set;",
"import java.util.HashSet;",
"class Test {",
" public void addString(String x) {",
" NestedTest nested = new NestedTest();",
" nested.mySet.add(x);",
" }",
" private static final class NestedTest {",
" private final Set<String> mySet = new HashSet<>();",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| 10,309
| 31.834395
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TheoryButNoTheoriesTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link TheoryButNoTheories}. */
@RunWith(JUnit4.class)
public final class TheoryButNoTheoriesTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(TheoryButNoTheories.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(TheoryButNoTheories.class, getClass());
@Test
public void positive() {
refactoringHelper
.addInputLines(
"Test.java",
"import org.junit.experimental.theories.Theory;",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(JUnit4.class)",
"public class Test {",
" @Theory public void test() {}",
"}")
.addOutputLines(
"Test.java",
"import org.junit.experimental.theories.Theories;",
"import org.junit.experimental.theories.Theory;",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(Theories.class)",
"public class Test {",
" @Theory public void test() {}",
"}")
.doTest();
}
@Test
public void alreadyParameterized_noFinding() {
helper
.addSourceLines(
"Test.java",
"import org.junit.experimental.theories.Theories;",
"import org.junit.experimental.theories.Theory;",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(Theories.class)",
"public class Test {",
" @Theory public void test() {}",
"}")
.doTest();
}
@Test
public void noParameters_noFinding() {
helper
.addSourceLines(
"Test.java",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(JUnit4.class)",
"public class Test {",
"}")
.doTest();
}
}
| 2,917
| 32.54023
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LogicalAssignmentTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link LogicalAssignment}Test */
@RunWith(JUnit4.class)
public class LogicalAssignmentTest {
@Test
public void positive() {
BugCheckerRefactoringTestHelper.newInstance(LogicalAssignment.class, getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" void f(boolean x){",
" if (x = true) {}",
" while (x = true) {}",
" for (; x = true; ) {}",
" do {} while (x = true);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f(boolean x){",
" if ((x = true)) {}",
" while ((x = true)) {}",
" for (; (x = true); ) {}",
" do {} while ((x = true));",
" }",
"}")
.doTest();
}
@Test
public void negative() {
CompilationTestHelper.newInstance(LogicalAssignment.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" void f(boolean x){",
" if ((x = true)) {}",
" while ((x = true)) {}",
" for (; (x = true); ) {}",
" do {} while (x == true);",
" if (x == true) {}",
" while (x == true) {}",
" for (; x == true; ) {}",
" do {} while (x == true);",
" }",
"}")
.doTest();
}
@Test
public void positive_equalityFix() {
BugCheckerRefactoringTestHelper.newInstance(LogicalAssignment.class, getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" void f(boolean x){",
" if (x = true) {}",
" if ((x = true)) {}",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f(boolean x){",
" if (x == true) {}",
" if ((x = true)) {}",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
}
| 3,073
| 30.050505
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TruthAssertExpectedTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link TruthAssertExpected} bug pattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class TruthAssertExpectedTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(TruthAssertExpected.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("TruthAssertExpectedPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("TruthAssertExpectedNegativeCases.java").doTest();
}
}
| 1,377
| 30.318182
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ConstantPatternCompileTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link ConstantPatternCompile} bug pattern.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@RunWith(JUnit4.class)
public class ConstantPatternCompileTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ConstantPatternCompile.class, getClass());
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(ConstantPatternCompile.class, getClass());
@Test
public void inlineExpressions() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" boolean isCar(String input) {",
" return Pattern.compile(\"car\").matcher(input).matches();",
" }",
"}")
.addOutputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" boolean isCar(String input) {",
" return INPUT_PATTERN.matcher(input).matches();",
" }",
" private static final Pattern INPUT_PATTERN = Pattern.compile(\"car\");",
"}")
.doTest();
}
@Test
public void variableNameFromField() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" private static final String INPUT = null;",
" boolean isCar() {",
" return Pattern.compile(\"car\").matcher(INPUT).matches();",
" }",
"}")
.addOutputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" private static final String INPUT = null;",
" boolean isCar() {",
" return INPUT_PATTERN.matcher(INPUT).matches();",
" }",
" private static final Pattern INPUT_PATTERN = Pattern.compile(\"car\");",
"}")
.doTest();
}
@Test
public void inlineExpression_argumentIsMethodCall() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" String getText() {return null;}",
" boolean isCar() {",
" return Pattern.compile(\"car\").matcher(getText()).matches();",
" }",
"}")
.addOutputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" String getText() {return null;}",
" boolean isCar() {",
" return GET_TEXT_PATTERN.matcher(getText()).matches();",
" }",
" private static final Pattern GET_TEXT_PATTERN = Pattern.compile(\"car\");",
"}")
.doTest();
}
@Test
public void inlineExpression_nameDefaultsToPattern() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" boolean isCar() {",
" return Pattern.compile(\"car\").matcher(\"\").matches();",
" }",
"}")
.addOutputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" boolean isCar() {",
" return PATTERN.matcher(\"\").matches();",
" }",
" private static final Pattern PATTERN = Pattern.compile(\"car\");",
"}")
.doTest();
}
@Test
public void multipleInlineExpressions() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" boolean isBlueCar(String input) {",
" return Pattern.compile(\"car\").matcher(input).matches()",
" && Pattern.compile(\"blue\").matcher(input).matches();",
" }",
"}")
.addOutputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" boolean isBlueCar(String input) {",
" return INPUT_PATTERN.matcher(input).matches()",
" && INPUT_PATTERN2.matcher(input).matches();",
" }",
" private static final Pattern INPUT_PATTERN = Pattern.compile(\"car\");",
" private static final Pattern INPUT_PATTERN2 = Pattern.compile(\"blue\");",
"}")
.doTest();
}
@Test
public void sameNameInDifferentMethods() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" boolean isCar(String input) {",
" return Pattern.compile(\"car\").matcher(input).matches();",
" }",
" boolean isDog(String input) {",
" return Pattern.compile(\"dog\").matcher(input).matches();",
" }",
"}")
.addOutputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" boolean isCar(String input) {",
" return INPUT_PATTERN.matcher(input).matches();",
" }",
" boolean isDog(String input) {",
" return INPUT_PATTERN2.matcher(input).matches();",
" }",
" private static final Pattern INPUT_PATTERN = Pattern.compile(\"car\");",
" private static final Pattern INPUT_PATTERN2 = Pattern.compile(\"dog\");",
"}")
.doTest();
}
@Test
public void fixGenerationStatic() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" static final String MY_COOL_PATTERN = \"a+\";",
" public static void myPopularStaticMethod() {",
" Pattern somePattern = Pattern.compile(MY_COOL_PATTERN);",
" Matcher m = somePattern.matcher(\"aaaaab\");",
" }",
"}")
.addOutputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" static final String MY_COOL_PATTERN = \"a+\";",
" public static void myPopularStaticMethod() {",
" Matcher m = SOME_PATTERN.matcher(\"aaaaab\");",
" }",
" private static final Pattern SOME_PATTERN = Pattern.compile(MY_COOL_PATTERN);",
"}")
.doTest();
}
@Test
public void fixGeneration_multiplePatterns() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Pattern;",
"class Test {",
" public static boolean match() {",
" String line = \"abcd\";",
" Pattern p1 = Pattern.compile(\"a+\");",
" Pattern p2 = Pattern.compile(\"b+\");",
" if (p1.matcher(line).matches() && p2.matcher(line).matches()) {",
" return true;",
" }",
" Pattern p3 = Pattern.compile(\"c+\");",
" Pattern p4 = Pattern.compile(\"d+\");",
" return p3.matcher(line).matches() && p4.matcher(line).matches();",
" }",
"}")
.addOutputLines(
"in/Test.java",
"import java.util.regex.Pattern;",
"class Test {",
" public static boolean match() {",
" String line = \"abcd\";",
" if (P1.matcher(line).matches() && P2.matcher(line).matches()) {",
" return true;",
" }",
" return P3.matcher(line).matches() && P4.matcher(line).matches();",
" }",
" private static final Pattern P1 = Pattern.compile(\"a+\");",
" private static final Pattern P2 = Pattern.compile(\"b+\");",
" private static final Pattern P3 = Pattern.compile(\"c+\");",
" private static final Pattern P4 = Pattern.compile(\"d+\");",
"}")
.doTest();
}
@Test
public void fixGenerationWithJavadoc() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" /** This is a javadoc. **/ ",
" public static void myPopularStaticMethod() {",
" Pattern myPattern = Pattern.compile(\"a+\");",
" Matcher m = myPattern.matcher(\"aaaaab\");",
" }",
"}")
.addOutputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" /** This is a javadoc. **/ ",
" public static void myPopularStaticMethod() {",
" Matcher m = MY_PATTERN.matcher(\"aaaaab\");",
" }",
" private static final Pattern MY_PATTERN = Pattern.compile(\"a+\");",
"}")
.doTest();
}
@Test
public void fixGeneration_nonStaticInnerClass() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" static final String MY_COOL_PATTERN = \"a+\";",
" class Inner {",
" public void myPopularStaticMethod() {",
" Pattern myPattern = Pattern.compile(MY_COOL_PATTERN);",
" Matcher m = myPattern.matcher(\"aaaaab\");",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" static final String MY_COOL_PATTERN = \"a+\";",
" class Inner {",
" public void myPopularStaticMethod() {",
" Matcher m = MY_PATTERN.matcher(\"aaaaab\");",
" }",
" private final Pattern MY_PATTERN = Pattern.compile(MY_COOL_PATTERN);",
" }",
"}")
.doTest();
}
@Test
public void negativeCases() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.regex.Pattern;",
"class Test {",
" private static String pattern;",
" private static final Pattern MY_COOL_PATTERN = Pattern.compile(pattern);",
" private static final Pattern LOWER_CASE_ONLY = ",
" Pattern.compile(\"^([a-z]+)$\", Pattern.CASE_INSENSITIVE);",
" ",
" private void myPopularNonStaticMethod(String arg) {",
" Pattern pattern = Pattern.compile(arg + \"+\");",
" }",
" private void myPopularMethod(@CompileTimeConstant String arg) {",
" Pattern pattern = Pattern.compile(arg);",
" }",
" private final String patString = \"a+\";",
" private void patternCompileOnNonStaticArg() {",
" Pattern pattern = Pattern.compile(patString);",
" }",
"}")
.doTest();
}
@Test
public void negativeCases_multiArg() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" public static int getMatchCount(CharSequence content, String regex) {",
" int count = 0;",
" Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);",
" Matcher matcher = pattern.matcher(content);",
" while (matcher.find()) {",
" count++;",
" }",
" return count;",
" }",
"}")
.doTest();
}
@Test
public void negativeCase_staticBlock() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.regex.Pattern;",
"class Test {",
" private static final String pattern = \"a+\";",
" static {",
" Pattern MY_COOL_PATTERN = Pattern.compile(pattern);",
" }",
"}")
.doTest();
}
// Don't convert String constants to patterns if they're used anywhere other than a single
// Pattern.compile call.
@Test
public void onlyCode_noFinding() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import java.util.regex.Pattern;",
"class Test {",
" public static void test() {",
" Pattern pattern = Pattern.compile(\".*\");",
" }",
"}")
.setArgs("-XepCompilingTestOnlyCode")
.doTest();
}
@Test
public void withinList_noFinding() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.regex.Pattern;",
"class Test {",
" private static final ImmutableList<Pattern> patterns =",
" ImmutableList.of(Pattern.compile(\".*\"));",
"}")
.doTest();
}
@Test
public void suppressible() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.regex.Matcher;",
"import java.util.regex.Pattern;",
"class Test {",
" @SuppressWarnings(\"ConstantPatternCompile\")",
" boolean isCar(String input) {",
" return Pattern.compile(\"car\").matcher(input).matches();",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| 15,759
| 34.736961
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InterfaceWithOnlyStaticsTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link InterfaceWithOnlyStatics} bug pattern. */
@RunWith(JUnit4.class)
public class InterfaceWithOnlyStaticsTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(InterfaceWithOnlyStatics.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(InterfaceWithOnlyStatics.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"// BUG: Diagnostic contains: InterfaceWithOnlyStatics",
"interface Test {",
" public static final int foo = 42;",
"}")
.doTest();
}
@Test
public void negative_hasNonStaticMethod() {
testHelper
.addSourceLines(
"Test.java",
"interface Test {",
" public static final int foo = 42;",
" int bar();",
"}")
.doTest();
}
@Test
public void negative_notInterface() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" public static final int foo = 42;",
"}")
.doTest();
}
@Test
public void negative_annotation() {
testHelper
.addSourceLines(
"Test.java", //
"@interface Test {",
" public static final int foo = 42;",
"}")
.doTest();
}
@Test
public void negative_extends() {
testHelper
.addSourceLines(
"A.java", //
"interface A {}")
.addSourceLines(
"Test.java", //
"interface Test extends A {",
" int foo = 42;",
" static int bar() { return 1; }",
"}")
.doTest();
}
@Test
public void negative_daggerModules() {
testHelper
.addSourceLines(
"Module.java", //
"package dagger;",
"public @interface Module {}")
.addSourceLines(
"Test.java", //
"import dagger.Module;",
"@Module",
"interface Test {",
" public static final int foo = 42;",
"}")
.doTest();
}
@Test
public void negative_daggerModules_producerModule() {
testHelper
.addSourceLines(
"ProducerModule.java", //
"package dagger.producers;",
"public @interface ProducerModule {}")
.addSourceLines(
"Test.java", //
"import dagger.producers.ProducerModule;",
"@ProducerModule",
"interface Test {",
" public static final int foo = 42;",
"}")
.doTest();
}
@Test
public void refactoring() {
refactoringHelper
.addInputLines(
"Test.java", //
"interface Test {",
" int foo = 42;",
" static int bar() { return 1; }",
"}")
.addOutputLines(
"Test.java",
"final class Test {",
" public static final int foo = 42;",
" public static int bar() { return 1; }",
" private Test() {}",
"}")
.doTest();
}
@Test
public void refactoring_innerClass() {
refactoringHelper
.addInputLines(
"Foo.java", //
"class Foo {",
" interface Test {",
" int foo = 42;",
" }",
"}")
.addOutputLines(
"Foo.java",
"class Foo {",
" static final class Test {",
" public static final int foo = 42;",
" private Test() {}",
" }",
"}")
.doTest();
}
}
| 4,639
| 26.619048
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ArrayEqualsTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit4.class)
public class ArrayEqualsTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ArrayEquals.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("ArrayEqualsPositiveCases.java").doTest();
}
@Test
public void java7PositiveCase() {
compilationHelper.addSourceFile("ArrayEqualsPositiveCases2.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("ArrayEqualsNegativeCases.java").doTest();
}
@Test
public void java7NegativeCase() {
compilationHelper.addSourceFile("ArrayEqualsNegativeCases2.java").doTest();
}
}
| 1,543
| 28.132075
| 79
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NewFileSystemTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static org.junit.Assume.assumeFalse;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.util.RuntimeVersion;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class NewFileSystemTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(NewFileSystem.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(NewFileSystem.class, getClass());
@Test
public void refactoring() {
assumeFalse(RuntimeVersion.isAtLeast13());
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.nio.file.FileSystems;",
"import java.nio.file.Paths;",
"import java.io.IOException;",
"class Test {",
" void f() throws IOException {",
" FileSystems.newFileSystem(Paths.get(\".\"), null);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.nio.file.FileSystems;",
"import java.nio.file.Paths;",
"import java.io.IOException;",
"class Test {",
" void f() throws IOException {",
" FileSystems.newFileSystem(Paths.get(\".\"), (ClassLoader) null);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java",
"import java.nio.file.FileSystems;",
"import java.nio.file.Paths;",
"import java.io.IOException;",
"class Test {",
" void f() throws IOException {",
" FileSystems.newFileSystem(Paths.get(\".\"), (ClassLoader) null);",
" }",
"}")
.doTest();
}
}
| 2,627
| 31.85
| 83
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DoNotMockAutoValueTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link DoNotMockAutoValue}. */
@RunWith(JUnit4.class)
public final class DoNotMockAutoValueTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(DoNotMockAutoValue.class, getClass());
@Test
public void positive() {
helper
.addSourceLines(
"AV.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"public abstract class AV {}")
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"class Test {",
" // BUG: Diagnostic contains:",
" private final AV av = mock(AV.class);",
"}")
.doTest();
}
}
| 1,533
| 30.958333
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IgnoredPureGetterTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link IgnoredPureGetter}. */
@RunWith(JUnit4.class)
public final class IgnoredPureGetterTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(IgnoredPureGetter.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(IgnoredPureGetter.class, getClass());
@Test
public void autoValue() {
helper
.addSourceLines(
"A.java", //
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"abstract class A {",
" abstract int foo();",
"}")
.addSourceLines(
"B.java", //
"class B {",
" void test(A a) {",
" // BUG: Diagnostic contains:",
" a.foo();",
" }",
"}")
.doTest();
}
@Test
public void autoValueBuilder() {
helper
.addSourceLines(
"Animal.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"abstract class Animal {",
" abstract String name();",
" @AutoValue.Builder",
" abstract static class Builder {",
" abstract Builder setName(String name);",
" abstract Animal build();",
" }",
"}")
.addSourceLines(
"B.java",
"class B {",
" void test(Animal.Builder builder) {",
// The setters are OK
" builder.setName(\"dog\");",
" // BUG: Diagnostic contains:",
" builder.build();",
" }",
"}")
.doTest();
}
@Test
public void autoValueStepBuilder() {
helper
.addSourceLines(
"Animal.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"public abstract class Animal {",
" public abstract String name();",
" public abstract int legs();",
" public interface NameStep { LegStep setName(String name); }",
" public interface LegStep { Build setLegs(int legs); }",
" public interface Build { Animal build(); }",
" @AutoValue.Builder",
" abstract static class Builder implements NameStep, LegStep, Build {}",
"}")
.addSourceLines(
"B.java",
"class B {",
" void test(Animal.Builder builder) {",
// The setters are OK
" builder.setName(\"dog\");",
" builder.setLegs(4);",
// We don't currently catch this, but maybe we should?
" builder.build();",
" }",
"}")
.doTest();
}
@Test
public void autoValue_secondFix() {
refactoringHelper
.addInputLines(
"A.java", //
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"abstract class A {",
" abstract int foo();",
" static A of(int foo) {",
" return null;",
" }",
"}")
.expectUnchanged()
.addInputLines(
"B.java", //
"class B {",
" void test() {",
" A.of(1).foo();",
" }",
"}")
.addOutputLines(
"B.java", //
"class B {",
" void test() {",
" A.of(1);",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void autoBuilder_getters() {
helper
.addSourceLines(
"Named.java",
"import com.google.auto.value.AutoBuilder;",
"import java.util.Optional;",
"public class Named {",
" Named(String name, String nickname) {}",
" @AutoBuilder",
" public abstract static class Builder {",
" public abstract Builder setName(String x);",
" public abstract Builder setNickname(String x);",
" abstract String getName();",
" abstract Optional<String> getNickname();",
" abstract Named autoBuild();",
" public Named build() {",
" if (!getNickname().isPresent()) {",
" setNickname(getName());",
" }",
" return autoBuild();",
" }",
" }",
"}")
.addSourceLines(
"B.java",
"class B {",
" void test(Named.Builder builder) {",
// The setters are OK
" builder.setName(\"Stumpy\");",
" builder.setNickname(\"Stumps\");",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" builder.getName();",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" builder.getNickname();",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" builder.autoBuild();",
// build() isn't covered since it's non-abstract
" builder.build();",
" }",
"}")
.doTest();
}
@Test
public void autoBuilder_buildIsntCrv() {
helper
.addSourceLines(
"Named.java",
"import com.google.auto.value.AutoBuilder;",
"import java.time.LocalTime;",
"@AutoBuilder(callMethod = \"of\", ofClass = LocalTime.class)",
"interface LocalTimeBuilder {",
" LocalTimeBuilder setHour(int hour);",
" LocalTimeBuilder setMinute(int minute);",
" LocalTimeBuilder setSecond(int second);",
" LocalTimeBuilder setNanoOfSecond(int nanoOfSecond);",
" int getHour();",
" int getMinute();",
" int getSecond();",
" int getNanoOfSecond();",
" LocalTime build();", // calls: LocalTime.of(...)
"}")
.addSourceLines(
"B.java",
"class B {",
" void test(LocalTimeBuilder builder) {",
// the setters are treated as CIRV:
" builder.setHour(12);",
" builder.setMinute(12);",
" builder.setSecond(12);",
// the getters are treated as CRV:
" // BUG: Diagnostic contains: IgnoredPureGetter",
" builder.getHour();",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" builder.getMinute();",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" builder.getSecond();",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" builder.getNanoOfSecond();",
// TODO(b/229107551): this shouldn't be treated as CRV
" // BUG: Diagnostic contains: IgnoredPureGetter",
" builder.build();",
" }",
"}")
.doTest();
}
@Test
public void refactoringHelper() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void test(TestProtoMessage message) {",
" message.getMessage();",
" message.hasMessage();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void test(TestProtoMessage message) {",
" }",
"}")
.doTest();
}
@Test
public void protoInstanceMethodsFlagged() {
helper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void test(TestProtoMessage message) {",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" message.getMultiField(1);",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" message.getWeightMap();",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" message.getWeightOrDefault(1, 42);",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" message.getWeightOrThrow(1);",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" message.containsWeight(1);",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" message.getWeightCount();",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" message.getMessage();",
" // BUG: Diagnostic contains: IgnoredPureGetter",
" message.hasMessage();",
" }",
"}")
.doTest();
}
@Test
public void protoReturnValueIgnored_noFinding() {
helper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void test(TestProtoMessage message) {",
" Object o = message.getMessage();",
" boolean b = message.hasMessage();",
" }",
"}")
.doTest();
}
}
| 10,416
| 33.839465
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IncompatibleModifiersCheckerTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link IncompatibleModifiersChecker}.
*
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@RunWith(JUnit4.class)
public class IncompatibleModifiersCheckerTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(IncompatibleModifiersChecker.class, getClass())
.addSourceLines(
"test/NotPrivateOrFinal.java",
"package test;",
"import static javax.lang.model.element.Modifier.FINAL;",
"import static javax.lang.model.element.Modifier.PRIVATE;",
"import com.google.errorprone.annotations.IncompatibleModifiers;",
"@IncompatibleModifiers({PRIVATE, FINAL})",
"public @interface NotPrivateOrFinal {",
"}")
.addSourceLines(
"test/NotPublicOrFinal.java",
"package test;",
"import static javax.lang.model.element.Modifier.FINAL;",
"import static javax.lang.model.element.Modifier.PUBLIC;",
"import com.google.errorprone.annotations.IncompatibleModifiers;",
"@IncompatibleModifiers({PUBLIC, FINAL})",
"public @interface NotPublicOrFinal {",
"}")
.addSourceLines(
"test/NotAbstract.java",
"package test;",
"import static javax.lang.model.element.Modifier.ABSTRACT;",
"import com.google.errorprone.annotations.IncompatibleModifiers;",
"@IncompatibleModifiers(ABSTRACT)",
"public @interface NotAbstract {",
"}");
@Test
public void annotationWithIncompatibleModifierOnClassFails() {
compilationHelper
.addSourceLines(
"test/IncompatibleModifiersTestCase.java",
"package test;",
"import test.NotAbstract;",
"// BUG: Diagnostic contains: The annotation '@NotAbstract' has specified that it"
+ " should not be used together with the following modifiers: [abstract]",
"@NotAbstract abstract class IncompatibleModifiersTestCase {",
"}")
.doTest();
}
@Test
public void annotationWithIncompatibleModifierOnFieldFails() {
compilationHelper
.addSourceLines(
"test/IncompatibleModifiersTestCase.java",
"package test;",
"import test.NotPrivateOrFinal;",
"public class IncompatibleModifiersTestCase {",
" // BUG: Diagnostic contains: The annotation '@NotPrivateOrFinal' has specified that"
+ " it should not be used together with the following modifiers: [final]",
" @NotPrivateOrFinal public final int n = 0;",
"}")
.doTest();
}
@Test
public void annotationWithIncompatibleModifierOnMethodFails() {
compilationHelper
.addSourceLines(
"test/IncompatibleModifiersTestCase.java",
"package test;",
"import test.NotPrivateOrFinal;",
"public class IncompatibleModifiersTestCase {",
" // BUG: Diagnostic contains: The annotation '@NotPrivateOrFinal' has specified that"
+ " it should not be used together with the following modifiers: [private]",
" @NotPrivateOrFinal private void foo(){}",
"}")
.doTest();
}
@Test
public void annotationWithTwoIncompatibleModifiersFails() {
compilationHelper
.addSourceLines(
"test/IncompatibleModifiersTestCase.java",
"package test;",
"import test.NotPublicOrFinal;",
"public class IncompatibleModifiersTestCase {",
" // BUG: Diagnostic contains: The annotation '@NotPublicOrFinal' has specified that"
+ " it should not be used together with the following modifiers: [public, final]",
" @NotPublicOrFinal public static final int FOO = 0;",
"}")
.doTest();
}
@Test
public void annotationWithCompatibleModifiersSucceeds() {
compilationHelper
.addSourceLines(
"test/IncompatibleModifiersTestCase.java",
"package test;",
"import test.NotAbstract;",
"public class IncompatibleModifiersTestCase {}")
.doTest();
}
// Regression test for #313
@Test
public void negativeNestedAnnotations() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"@interface Foos {",
" Foo[] value();",
"}",
"@interface Foo {",
"}",
"@Foos({@Foo, @Foo}) public class Test {",
"}")
.doTest();
}
// Regression test for #313
@Test
public void negativePackageAnnotation() {
compilationHelper
.addSourceLines(
"testdata/Anno.java",
"package testdata;",
"import java.lang.annotation.Target;",
"import java.lang.annotation.ElementType;",
"@Target(ElementType.PACKAGE)",
"public @interface Anno {",
"}")
.addSourceLines("testdata/package-info.java", "@Anno", "package testdata;")
.doTest();
}
@Test
public void refactoring() {
BugCheckerRefactoringTestHelper.newInstance(IncompatibleModifiersChecker.class, getClass())
.addInputLines(
"test/NotAbstract.java",
"package test;",
"import static javax.lang.model.element.Modifier.ABSTRACT;",
"import com.google.errorprone.annotations.IncompatibleModifiers;",
"@IncompatibleModifiers(ABSTRACT)",
"public @interface NotAbstract {",
"}")
.expectUnchanged()
.addInputLines(
"test/IncompatibleModifiersTestCase.java",
"package test;",
"import test.NotAbstract;",
"@NotAbstract abstract class IncompatibleModifiersTestCase {",
"}")
.addOutputLines(
"test/IncompatibleModifiersTestCase.java",
"package test;",
"import test.NotAbstract;",
"@NotAbstract class IncompatibleModifiersTestCase {",
"}")
.doTest();
}
}
| 7,113
| 36.052083
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryParenthesesTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static org.junit.Assume.assumeTrue;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.util.RuntimeVersion;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link UnnecessaryParentheses}Test */
@RunWith(JUnit4.class)
public class UnnecessaryParenthesesTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryParentheses.class, getClass());
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(UnnecessaryParentheses.class, getClass());
@Test
public void test() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f(int x) {",
" if (true) System.err.println((x));",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f(int x) {",
" if (true) System.err.println(x);",
" }",
"}")
.doTest();
}
@Test
public void anonymousClass() {
testHelper
.addInputLines(
"in/Test.java",
"import com.google.common.base.Function;",
"import com.google.common.collect.Iterables;",
"import java.util.List;",
"class Test {",
" Iterable<Integer> f(List<Integer> l) {",
" return Iterables.transform(",
" l,",
" (new Function<Integer, Integer>() {",
" public Integer apply(Integer a) {",
" return a * 2;",
" }",
" }));",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.base.Function;",
"import com.google.common.collect.Iterables;",
"import java.util.List;",
"class Test {",
" Iterable<Integer> f(List<Integer> l) {",
" return Iterables.transform(",
" l,",
" new Function<Integer, Integer>() {",
" public Integer apply(Integer a) {",
" return a * 2;",
" }",
" });",
" }",
"}")
.doTest();
}
@Test
public void binaryTrees() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" int e() {",
" // BUG: Diagnostic contains:",
" return (\"b\").hashCode();",
" }",
" int f() {",
" return (\"a\" + \"b\").hashCode();",
" }",
" int g() {",
" return (1 + 2) & 3;",
" }",
"}")
.doTest();
}
@Test
public void methodReference() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Predicate;",
"class Test {",
" Predicate<Test> foo(Predicate<Test> a) {",
" // BUG: Diagnostic contains:",
" return foo((this::equals));",
" }",
"}")
.doTest();
}
@Test
public void lambdaLambda() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" Function<Void, Function<Void, Void>> r = x -> (y -> y);",
"}")
.doTest();
}
@Test
public void lambda() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" Function<Void, Void> f() {",
" // BUG: Diagnostic contains:",
" Function<Void, Void> r = (y -> y);",
" // BUG: Diagnostic contains:",
" return (y -> y);",
" }",
"}")
.doTest();
}
@Test
public void unaryPostFixParenthesesNotNeeded() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void print(Integer i) {",
" int j = (i++) + 2;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" void print(Integer i) {",
" int j = i++ + 2;",
" }",
"}")
.doTest();
}
@Test
public void unaryPostFixParenthesesNeeded() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void print(Integer i) {",
" (i++).toString();",
" }",
"}")
.doTest();
}
@Test
public void unaryPreFixParenthesesNeeded() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void print(Integer i) {",
" (++i).toString();",
" }",
"}")
.doTest();
}
@Test
public void negativeStatements() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void print(boolean b, int i) {",
" if (b) {}",
" while (b) {}",
" do {} while (b);",
" switch (i) {}",
" synchronized (this) {}",
" }",
"}")
.doTest();
}
@Test
public void positiveStatements() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" int f(boolean b, Integer x) {",
" assert(b);",
" return(x);",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int f(boolean b, Integer x) {",
" assert b;",
" return x;",
" }",
"}")
.doTest();
}
@Test
public void switchExpression() {
assumeTrue(RuntimeVersion.isAtLeast12());
helper
.addSourceLines(
"Test.java",
"class Test {",
" public boolean match(String value) {",
" return switch (value) {",
" case \"true\" -> true;",
" case \"false\" -> false;",
" default -> throw new RuntimeException(\"Unable to match\");",
" };",
" }",
"}")
.expectNoDiagnostics()
.doTest();
}
}
| 7,305
| 26.885496
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MutablePublicArrayTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link MutablePublicArray}. */
@RunWith(JUnit4.class)
public class MutablePublicArrayTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(MutablePublicArray.class, getClass());
@Test
public void publicStaticFinalPrimitive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: MutablePublicArray",
" public static final int[] array = new int[10];",
"}")
.doTest();
}
@Test
public void publicStaticFinalInlineInitializer() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: MutablePublicArray",
" public static final String[] array = {\"foo\", \"bar\"};",
"}")
.doTest();
}
@Test
public void publicStaticFinalObject() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: MutablePublicArray",
" public static final Test[] array = new Test[10];",
"}")
.doTest();
}
@Test
public void publicStaticFinalObjectMultiDimension() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: MutablePublicArray",
" public static final Test[][] array = new Test[10][10];",
"}")
.doTest();
}
@Test
public void privateStaticFinal_negative() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" private static final int[] array = new int[10];",
"}")
.doTest();
}
@Test
public void privateStaticFinalEmptyInlineInitializer_negative() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" public static final String[] array = {};",
"}")
.doTest();
}
@Test
public void privateFinal_negative() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" private final int[] array = new int[10];",
"}")
.doTest();
}
@Test
public void staticFinal_negative() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" static final int[] array = new int[10];",
"}")
.doTest();
}
@Test
public void zeroSizeOneDimensionArray_negative() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" public static final int[] array = new int[0];",
"}")
.doTest();
}
@Test
public void zeroSizeMultiDimensionArray_negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public static final int[][] array = new int[0][0];",
"}")
.doTest();
}
@Test
public void negative_datapoints() {
compilationHelper
.addSourceLines(
"Test.java",
"import org.junit.experimental.theories.DataPoints;",
"class Test {",
" @DataPoints",
" public static final int[] array = new int[10];",
"}")
.doTest();
}
@Test
public void publicStaticFinalStaticInitializeBlock() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public static final long[] l;",
" static {",
" l = new long[1];",
" }",
"}")
.doTest();
}
@Test
public void notAnArray() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: MutablePublicArray",
" public static final long[] y = {0};",
" public static final long[] l = y;",
"}")
.doTest();
}
@Test
public void i1645() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public static final int zero = 0;",
" public static final int one = 1;",
" public static final long[] z1 = new long[zero];",
" public static final long[][] z2 = new long[zero][zero];",
" // BUG: Diagnostic contains: MutablePublicArray",
" public static final long[] o1 = new long[one];",
" // BUG: Diagnostic contains: MutablePublicArray",
" public static final long[][] o2 = new long[one][zero];",
"}")
.doTest();
}
}
| 5,653
| 26.852217
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IncrementInForLoopAndHeaderTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author mariasam@google.com (Maria Sam)
*/
@RunWith(JUnit4.class)
public class IncrementInForLoopAndHeaderTest {
private static CompilationTestHelper compilationTestHelper;
@Before
public void setup() {
compilationTestHelper =
CompilationTestHelper.newInstance(IncrementInForLoopAndHeader.class, getClass());
}
@Test
public void positiveCases() {
compilationTestHelper.addSourceFile("IncrementInForLoopAndHeaderPositiveCases.java").doTest();
}
@Test
public void negativeCases() {
compilationTestHelper.addSourceFile("IncrementInForLoopAndHeaderNegativeCases.java").doTest();
}
}
| 1,449
| 29.851064
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FinalizeTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class FinalizeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(Finalize.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: Do not override finalize",
" protected void finalize() {}",
" interface A {",
" // BUG: Diagnostic contains: Do not override finalize",
" void finalize();",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public void finalize(int x) {}",
" interface B {",
" public int finalize();",
" }",
"}")
.doTest();
}
}
| 1,744
| 28.083333
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnusedExceptionTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link UnusedException} bug pattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class UnusedExceptionTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(UnusedException.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(UnusedException.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" // BUG: Diagnostic contains: ",
" } catch (Exception e) {",
" throw new RuntimeException(\"foo\");",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactoring() {
refactoringHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
" if (equals(this)) {",
" throw new RuntimeException(toString());",
" } else {",
" throw new RuntimeException();",
" }",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
" if (equals(this)) {",
" throw new RuntimeException(toString(), e);",
" } else {",
" throw new RuntimeException(e);",
" }",
" }",
" }",
"}")
.doTest();
}
@Test
public void correctlyWrapped() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
" throw new RuntimeException(e);",
" }",
" }",
"}")
.doTest();
}
@Test
public void rethrown() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
" throw e;",
" }",
" }",
"}")
.doTest();
}
@Test
public void usedSomehow() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
" System.err.println(e.toString());",
" throw new RuntimeException();",
" }",
" }",
"}")
.doTest();
}
@Test
public void usedNested() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
" try {",
" // BUG: Diagnostic contains: ",
" } catch (Exception e2) {",
" System.err.println(e.toString());",
" throw new RuntimeException();",
" }",
" throw new RuntimeException();",
" }",
" }",
"}")
.doTest();
}
@Test
public void swallowedButDoesntThrow() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
" String ohNo = null;",
" }",
" }",
"}")
.doTest();
}
@Test
public void suppressible() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"UnusedException\")",
" void test() {",
" try {",
" } catch (Exception e) {",
" throw new RuntimeException(\"foo\");",
" }",
" }",
"}")
.doTest();
}
@Test
public void suppressibleViaCatchBlock() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (@SuppressWarnings(\"UnusedException\") Exception e) {",
" throw new RuntimeException(\"foo\");",
" }",
" }",
"}")
.doTest();
}
@Test
public void suppressibleByCallingExceptionUnused() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception unusedException) {",
" throw new RuntimeException(\"foo\");",
" }",
" }",
"}")
.doTest();
}
@Test
public void anonymousClass() {
refactoringHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
" throw new RuntimeException() {};",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
" throw new RuntimeException(e) {};",
" }",
" }",
"}")
.doTest();
}
@Test
public void replacementNotVisible() {
refactoringHelper
.addInputLines(
"in/MyException.java",
"class MyException extends RuntimeException {",
" public MyException(int a) {}",
" protected MyException(int a, Throwable th) {}",
"}")
.expectUnchanged()
.addInputLines(
"in/Test.java",
"class Test {",
" void test() {",
" try {",
" } catch (Exception e) {",
// Not refactored as MyException(int, Throwable) isn't visible.
" throw new MyException(1);",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void interruptedException_noFinding() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" try {",
" throw new InterruptedException();",
" } catch (InterruptedException e) {",
" throw new IllegalStateException(\"foo\");",
" }",
" }",
"}")
.doTest();
}
@Test
public void interruptedIOException_noFinding() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.io.InterruptedIOException;",
"abstract class Test {",
" abstract void foo() throws InterruptedIOException;",
" void test() throws InterruptedIOException {",
" try {",
" foo();",
" } catch (InterruptedIOException e) {",
" throw new InterruptedIOException();",
" }",
" }",
"}")
.doTest();
}
}
| 8,633
| 26.673077
| 85
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ChainingConstructorIgnoresParameterTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
@RunWith(JUnit4.class)
public class ChainingConstructorIgnoresParameterTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ChainingConstructorIgnoresParameter.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceFile("ChainingConstructorIgnoresParameterPositiveCases.java")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceFile("ChainingConstructorIgnoresParameterNegativeCases.java")
.doTest();
}
}
| 1,412
| 29.717391
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RedundantThrowsTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link RedundantThrows}Test */
@RunWith(JUnit4.class)
public final class RedundantThrowsTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(RedundantThrows.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"import java.io.IOException;",
"import java.io.FileNotFoundException;",
"import java.nio.file.AccessDeniedException;",
"interface Test {",
" // BUG: Diagnostic contains: FileNotFoundException is a subtype of IOException",
" void f() throws FileNotFoundException, IOException;",
" // BUG: Diagnostic contains: FileNotFoundException is a subtype of IOException",
" void g() throws IOException, FileNotFoundException;",
"}")
.doTest();
}
@Test
public void positiveTwoSubtypes() {
testHelper
.addSourceLines(
"Test.java",
"interface Test {",
" // BUG: Diagnostic contains:"
+ " IllegalAccessException and NoSuchFieldException are subtypes of"
+ " ReflectiveOperationException",
" void f() throws IllegalAccessException, NoSuchFieldException,"
+ " ReflectiveOperationException;",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java",
"import java.io.*;",
"interface Test {",
" void f() throws NullPointerException, FileNotFoundException;",
"}")
.doTest();
}
@Test
public void transitiveSuper() {
BugCheckerRefactoringTestHelper.newInstance(RedundantThrows.class, getClass())
.addInputLines(
"in/Test.java",
"import java.io.IOException;",
"import java.io.FileNotFoundException;",
"import java.nio.file.AccessDeniedException;",
"interface Test {",
" void f() throws FileNotFoundException, IOException, AccessDeniedException;",
"}")
.addOutputLines(
"out/Test.java",
"import java.io.IOException;",
"import java.io.FileNotFoundException;",
"import java.nio.file.AccessDeniedException;",
"interface Test {",
" void f() throws IOException;",
"}")
.doTest();
}
}
| 3,324
| 32.928571
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IncorrectMainMethodTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link IncorrectMainMethod}Test */
@RunWith(JUnit4.class)
public class IncorrectMainMethodTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(IncorrectMainMethod.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(IncorrectMainMethod.class, getClass());
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java",
"class Test {", //
" public static void main(String[] args) {}",
"}")
.doTest();
}
@Test
public void negativeName() {
testHelper
.addSourceLines(
"Test.java",
"class Test {", //
" public static void spain(String[] args) {}",
"}")
.doTest();
}
// clever but not wrong
@Test
public void negativeImplicitPublic() {
testHelper
.addSourceLines(
"Test.java",
"interface Test {", //
" static void main(String[] args) {}",
"}")
.doTest();
}
// clever but not wrong
@Test
public void negativeVarargs() {
testHelper
.addSourceLines(
"Test.java",
"class Test {", //
" public static void main(String... args) {}",
"}")
.doTest();
}
@Test
public void positiveNonPublic() {
testHelper
.addSourceLines(
"Test.java",
"class Test {", //
" // BUG: Diagnostic contains:",
" static void main(String[] args) {}",
"}")
.doTest();
}
@Test
public void positiveNonStatic() {
testHelper
.addSourceLines(
"Test.java",
"class Test {", //
" // BUG: Diagnostic contains:",
" public void main(String[] args) {}",
"}")
.doTest();
}
@Test
public void positiveNonVoid() {
testHelper
.addSourceLines(
"Test.java",
"class Test {", //
" // BUG: Diagnostic contains:",
" public static int main(String[] args) {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void negativeArity() {
testHelper
.addSourceLines(
"Test.java",
"class Test {", //
" static void main(String[] args, String arg) {}",
"}")
.doTest();
}
@Test
public void negativeNotArray() {
testHelper
.addSourceLines(
"Test.java",
"class Test {", //
" static void main(String args) {}",
"}")
.doTest();
}
@Test
public void negativeNotStringArray() {
testHelper
.addSourceLines(
"Test.java",
"class Test {", //
" static void main(Object[] args) {}",
"}")
.doTest();
}
@Test
public void removePrivate() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {", //
" private static void main(String[] args) {}",
"}")
.addOutputLines(
"Test.java",
"class Test {", //
" public static void main(String[] args) {}",
"}")
.doTest();
}
@Test
public void removeProtected() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {", //
" protected static void main(String[] args) {}",
"}")
.addOutputLines(
"Test.java",
"class Test {", //
" public static void main(String[] args) {}",
"}")
.doTest();
}
}
| 4,651
| 24.420765
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MemoizeConstantVisitorStateLookupsTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link com.google.errorprone.bugpatterns.MemoizeConstantVisitorStateLookups}. */
@RunWith(JUnit4.class)
public class MemoizeConstantVisitorStateLookupsTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(MemoizeConstantVisitorStateLookups.class, getClass())
.addModules(
"jdk.compiler/com.sun.tools.javac.util", "jdk.compiler/com.sun.tools.javac.code");
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(
MemoizeConstantVisitorStateLookups.class, getClass())
.addModules(
"jdk.compiler/com.sun.tools.javac.util", "jdk.compiler/com.sun.tools.javac.code");
@Test
public void replaceSingleUsage() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.VisitorState;",
"import com.sun.tools.javac.util.Name;",
"class Test {",
" public Test(VisitorState state) {",
" Name me = state.getName(\"Test\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.VisitorState;",
"import com.google.errorprone.suppliers.Supplier;",
"import com.sun.tools.javac.util.Name;",
"class Test {",
" public Test(VisitorState state) {",
" Name me = TEST.get(state);",
" }",
" private static final Supplier<Name> TEST = ",
" VisitorState.memoize(state -> state.getName(\"Test\"));",
"}")
.doTest();
}
@Test
public void prefersExistingStringConstant() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.VisitorState;",
"import com.sun.tools.javac.code.Type;",
"class Test {",
" private static final String MAP = \"java.util.Map\";",
" public Test(VisitorState state) {",
" Type map = state.getTypeFromString(MAP);",
" Type map2 = state.getTypeFromString(\"java.util.Map\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.VisitorState;",
"import com.google.errorprone.suppliers.Supplier;",
"import com.sun.tools.javac.code.Type;",
"class Test {",
" private static final String MAP = \"java.util.Map\";",
" public Test(VisitorState state) {",
" Type map = JAVA_UTIL_MAP.get(state);",
" Type map2 = JAVA_UTIL_MAP.get(state);",
" }",
" private static final Supplier<Type> JAVA_UTIL_MAP = ",
" VisitorState.memoize(state -> state.getTypeFromString(MAP));",
"}")
.doTest();
}
@Test
public void replaceConflictingValues() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.VisitorState;",
"import com.sun.tools.javac.code.Type;",
"import com.sun.tools.javac.util.Name;",
"class Test {",
" public Test(VisitorState state) {",
" Name className = state.getName(\"java.lang.Class\");",
" Type classType = state.getTypeFromString(\"java.lang.Class\");",
" Name lookupAgain = state.getName(\"java.lang.Class\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.VisitorState;",
"import com.google.errorprone.suppliers.Supplier;",
"import com.sun.tools.javac.code.Type;",
"import com.sun.tools.javac.util.Name;",
"class Test {",
" public Test(VisitorState state) {",
" Name className = JAVA_LANG_CLASS_NAME.get(state);",
" Type classType = JAVA_LANG_CLASS_TYPE.get(state);",
" Name lookupAgain = JAVA_LANG_CLASS_NAME.get(state);",
" }",
" private static final Supplier<Name> JAVA_LANG_CLASS_NAME = ",
" VisitorState.memoize(state -> state.getName(\"java.lang.Class\"));",
" private static final Supplier<Type> JAVA_LANG_CLASS_TYPE = ",
" VisitorState.memoize(state -> state.getTypeFromString(\"java.lang.Class\"));",
"}")
.doTest();
}
@Test
public void findingOnLookup() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.VisitorState;",
"import com.sun.tools.javac.code.Type;",
"import com.sun.tools.javac.util.Name;",
"class Test {",
" public Test(VisitorState state) {",
" // BUG: Diagnostic contains:",
" Name className = state.getName(\"java.lang.Class\");",
" }",
"}")
.doTest();
}
@Test
public void negative_doesntMemoizeTwice() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;\n",
"import com.google.errorprone.VisitorState;",
"import com.google.errorprone.suppliers.Supplier;",
"import com.sun.tools.javac.util.Name;",
"class Test {",
" private static final Supplier<ImmutableSet<Name>> ALLOWED_NAMES ",
" = VisitorState.memoize(state -> ",
" ImmutableSet.of(state.getName(\"foo\"), state.getName(\"bar\")));",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void testSuppressWarnings() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.VisitorState;",
"import com.sun.tools.javac.code.Type;",
"import com.sun.tools.javac.util.Name;",
"class Test {",
" @SuppressWarnings(\"MemoizeConstantVisitorStateLookups\")",
" public Test(VisitorState state) {",
" Name className = state.getName(\"java.lang.Class\");",
" }",
" @SuppressWarnings(\"MemoizeConstantVisitorStateLookups\")",
" public void testMethod(VisitorState state) {",
" Name className = state.getName(\"java.lang.Class\");",
" }",
" @SuppressWarnings(\"MemoizeConstantVisitorStateLookups\")",
" class InnerClass {",
" void innerMethod(VisitorState state) {",
" Name className = state.getName(\"java.lang.Class\");",
" }",
" }",
"}")
.doTest();
}
}
| 7,730
| 39.056995
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessarilyVisibleTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link UnnecessarilyVisible}. */
@RunWith(JUnit4.class)
public final class UnnecessarilyVisibleTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessarilyVisible.class, getClass());
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(UnnecessarilyVisible.class, getClass());
@Test
public void publicConstructor() {
helper
.addInputLines(
"Test.java",
"import javax.inject.Inject;",
"class Test {",
" @Inject",
" public Test() {}",
"}")
.addOutputLines(
"Test.java",
"import javax.inject.Inject;",
"class Test {",
" @Inject",
" Test() {}",
"}")
.doTest();
}
@Test
public void caveatOnInject() {
compilationHelper
.addSourceLines(
"Test.java",
"import javax.inject.Inject;",
"class Test {",
" @Inject",
" // BUG: Diagnostic contains: VisibleForTesting",
" public Test() {}",
"}")
.doTest();
}
@Test
public void caveatNotOnProvides() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.inject.Provides;",
"class Test {",
" @Provides",
" // BUG: Diagnostic matches: X",
" public int foo() {",
" return 1;",
" }",
"}")
.expectErrorMessage("X", msg -> !msg.contains("VisibleForTesting"))
.doTest();
}
@Test
public void protectedConstructor() {
helper
.addInputLines(
"Test.java",
"import javax.inject.Inject;",
"class Test {",
" @Inject",
" protected Test() {}",
"}")
.addOutputLines(
"Test.java",
"import javax.inject.Inject;",
"class Test {",
" @Inject",
" Test() {}",
"}")
.doTest();
}
@Test
public void providesMethod() {
helper
.addInputLines(
"Test.java",
"import com.google.inject.Provides;",
"class Test {",
" @Provides",
" public int foo() {",
" return 1;",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.inject.Provides;",
"class Test {",
" @Provides",
" int foo() {",
" return 1;",
" }",
"}")
.doTest();
}
@Test
public void unannotated_noFinding() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" public int foo() {",
" return 1;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void visibleForTesting_noFinding() {
helper
.addInputLines(
"Test.java", //
"import com.google.common.annotations.VisibleForTesting;",
"import javax.inject.Inject;",
"class Test {",
" @Inject",
" @VisibleForTesting",
" public Test() {}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void overridesPublicMethod_noFinding() {
helper
.addInputLines(
"A.java", //
"class A {",
" public void foo() {}",
"}")
.expectUnchanged()
.addInputLines(
"Test.java", //
"import com.google.inject.Provides;",
"class Test extends A {",
" @Provides",
" public void foo() {}",
"}")
.expectUnchanged()
.doTest();
}
}
| 4,809
| 25.871508
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IdentityHashMapBoxingTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link IdentityHashMapBoxing} bug pattern. */
@RunWith(JUnit4.class)
public class IdentityHashMapBoxingTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(IdentityHashMapBoxing.class, getClass());
@Test
public void constructorPositiveCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.IdentityHashMap;",
"import java.util.Map;",
"class Test {",
" void test() {",
" // BUG: Diagnostic contains: IdentityHashMapBoxing",
" Map<Integer, String> map1 = new IdentityHashMap<>();",
" // BUG: Diagnostic contains: IdentityHashMapBoxing",
" Map<Float, String> map2 = new IdentityHashMap<>();",
" // BUG: Diagnostic contains: IdentityHashMapBoxing",
" Map<Double, String> map3 = new IdentityHashMap<>();",
" // BUG: Diagnostic contains: IdentityHashMapBoxing",
" Map<Long, String> map4 = new IdentityHashMap<>();",
" }",
"}")
.doTest();
}
@Test
public void constructorNegativeCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.IdentityHashMap;",
"import java.util.Map;",
"class Test {",
" void test() {",
" Map<String, Integer> map1 = new IdentityHashMap<>();",
" Map<String, Float> map2 = new IdentityHashMap<>();",
" Map<String, Double> map3 = new IdentityHashMap<>();",
" Map<String, Long> map4 = new IdentityHashMap<>();",
" Map<String, Object> map5 = new IdentityHashMap<>();",
" Map<Object, String> map6 = new IdentityHashMap<>();",
" }",
"}")
.doTest();
}
@Test
public void mapsPositiveCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Maps;",
"import java.util.IdentityHashMap;",
"import java.util.Map;",
"class Test {",
" void test() {",
" // BUG: Diagnostic contains: IdentityHashMapBoxing",
" Map<Integer, String> map1 = Maps.newIdentityHashMap();",
" // BUG: Diagnostic contains: IdentityHashMapBoxing",
" Map<Float, String> map2 = Maps.newIdentityHashMap();",
" // BUG: Diagnostic contains: IdentityHashMapBoxing",
" Map<Double, String> map3 = Maps.newIdentityHashMap();",
" // BUG: Diagnostic contains: IdentityHashMapBoxing",
" Map<Long, String> map4 = Maps.newIdentityHashMap();",
" }",
"}")
.doTest();
}
@Test
public void mapsNegativeCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Maps;",
"import java.util.IdentityHashMap;",
"import java.util.Map;",
"class Test {",
" void test() {",
" Map<String, Integer> map1 = Maps.newIdentityHashMap();",
" Map<String, Float> map2 = Maps.newIdentityHashMap();",
" Map<String, Double> map3 = Maps.newIdentityHashMap();",
" Map<String, Long> map4 = Maps.newIdentityHashMap();",
" Map<String, Object> map5 = Maps.newIdentityHashMap();",
" Map<Object, String> map6 = Maps.newIdentityHashMap();",
" }",
"}")
.doTest();
}
}
| 4,464
| 37.491379
| 81
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryMethodReferenceTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit test for {@link UnnecessaryMethodReference}. */
@RunWith(JUnit4.class)
public final class UnnecessaryMethodReferenceTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(UnnecessaryMethodReference.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryMethodReference.class, getClass());
@Test
public void positiveCase() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"import java.util.stream.Stream;",
"class Test {",
" Stream<String> map(Stream<Integer> xs, Function<Integer, String> fn) {",
" // BUG: Diagnostic contains: (fn)",
" return xs.map(fn::apply);",
" }",
"}")
.doTest();
}
@Test
public void positiveCase_refactoring() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.function.Function;",
"import java.util.stream.Stream;",
"class Test {",
" Stream<String> map(Stream<Integer> xs, Function<Integer, String> fn) {",
" return xs.map(fn::apply);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.Function;",
"import java.util.stream.Stream;",
"class Test {",
" Stream<String> map(Stream<Integer> xs, Function<Integer, String> fn) {",
" return xs.map(fn);",
" }",
"}")
.doTest();
}
@Test
public void positiveWithExtraInheritance() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"import java.util.stream.Stream;",
"class Test {",
" Stream<String> map(Stream<Integer> xs, A fn) {",
" // BUG: Diagnostic contains: (fn)",
" return xs.map(fn::apply);",
" }",
" abstract static class A implements Function<Integer, String> {",
" @Override",
" public String apply(Integer i) {",
" return i.toString();",
" }",
" }",
"}")
.doTest();
}
@Test
public void negativeWithExtraInheritance() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"import java.util.stream.Stream;",
"class Test {",
" Stream<String> map(Stream<Integer> xs, A fn) {",
" return xs.map(fn::frobnicate);",
" }",
" abstract static class A implements Function<Integer, String> {",
" abstract String frobnicate(Integer i);",
" }",
"}")
.doTest();
}
@Test
public void withNonAbstractMethodOnInterface() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"import java.util.stream.Stream;",
"abstract class Test {",
" void test(A a) {",
" // BUG: Diagnostic contains:",
" foo(a::foo);",
" foo(a::bar);",
" }",
" abstract void foo(A a);",
" interface A {",
" String foo(Integer i);",
" default String bar(Integer i) {",
" return null;",
" }",
" }",
"}")
.doTest();
}
@Test
public void positiveCaseViaKnownDelegate() {
helper
.addSourceLines(
"Test.java",
"import com.google.common.base.Predicate;",
"import java.util.function.Function;",
"import java.util.stream.Stream;",
"class Test {",
" Stream<Integer> map(Stream<Integer> xs, Predicate<Integer> p) {",
" // BUG: Diagnostic contains: (p)",
" return xs.filter(p::apply);",
" }",
"}")
.doTest();
}
@Test
public void positiveCaseViaConvert() {
helper
.addSourceLines(
"Test.java",
"import com.google.common.base.Converter;",
"import java.util.stream.Stream;",
"class Test {",
" Stream<String> map(Stream<Integer> xs, Converter<Integer, String> fn) {",
" // BUG: Diagnostic contains: (fn)",
" return xs.map(fn::convert);",
" }",
"}")
.doTest();
}
@Test
public void positiveCaseViaConvert_viaIntermediateType() {
helper
.addSourceLines(
"Test.java",
"import com.google.common.base.Converter;",
"import com.google.common.base.Function;",
"class Test {",
" void a(Converter<Integer, String> fn) {",
" // BUG: Diagnostic contains: b(fn)",
" b(fn::convert);",
" }",
" void b(Function<Integer, String> fn) {}",
"}")
.doTest();
}
@Test
public void ignoreSuper() {
helper
.addSourceLines(
"S.java", //
"class S implements Runnable {",
" public void run() {}",
"}")
.addSourceLines(
"Test.java",
"abstract class Test extends S {",
" abstract void r(Runnable r);",
" public void run() {",
" r(super::run);",
" }",
"}")
.doTest();
}
@Test
public void subType() {
helper
.addSourceLines(
"T.java",
"import java.util.function.Consumer;",
"abstract class T {",
" void f(Consumer<String> c) {}",
" void g(Consumer<Object> c) {",
" f(c::accept);",
" }",
"}")
.doTest();
}
@Test
public void range_isJavaPredicate() {
helper
.addSourceLines(
"T.java",
"import com.google.common.collect.Range;",
"import java.util.stream.Stream;",
"abstract class T {",
" Stream<Long> g(Stream<Long> x, Range<Long> range) {",
" // BUG: Diagnostic contains: filter(range)",
" return x.filter(range::contains);",
" }",
"}")
.doTest();
}
@Test
public void range_isGuavaPredicate() {
helper
.addSourceLines(
"T.java",
"import com.google.common.base.Predicate;",
"import com.google.common.collect.Range;",
"import java.util.stream.Stream;",
"abstract class T {",
" void g(Range<Long> range) {",
" // BUG: Diagnostic contains: b(range)",
" b(range::contains);",
" }",
" abstract void b(Predicate<Long> p);",
"}")
.doTest();
}
}
| 7,946
| 30.411067
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FunctionalInterfaceClashTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class FunctionalInterfaceClashTest {
@Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(FunctionalInterfaceClash.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java", //
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class Test {",
" // BUG: Diagnostic contains: foo(Function<String, String>)",
" void foo(Consumer<String> x) {}",
" void foo(Function<String, String> c) {}",
"}")
.doTest();
}
@Test
public void positiveNullary() {
testHelper
.addSourceLines(
"Test.java", //
"import java.util.concurrent.Callable;",
"public class Test {",
" interface MyCallable {",
" String call();",
" }",
" // BUG: Diagnostic contains: foo(MyCallable)",
" void foo(Callable<String> x) {}",
" void foo(MyCallable c) {}",
"}")
.doTest();
}
@Test
public void positiveInherited() {
testHelper
.addSourceLines(
"Super.java", //
"import java.util.function.Function;",
"class Super {",
" void foo(Function<String, String> x) {}",
"}")
.addSourceLines(
"Test.java", //
"import java.util.function.Consumer;",
"public class Test extends Super {",
" // BUG: Diagnostic contains: Super.foo(Function<String, String>)",
" void foo(Consumer<String> c) {}",
"}")
.doTest();
}
@Test
public void positiveArgs() {
testHelper
.addSourceLines(
"Test.java", //
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class Test {",
" // BUG: Diagnostic contains: foo(Function<String, Integer>)",
" void foo(Consumer<String> c) {}",
" void foo(Function<String, Integer> f) {}",
"}")
.doTest();
}
@Test
public void negativeOverride() {
testHelper
.addSourceLines(
"Super.java", //
"import java.util.function.Consumer;",
"class Super {",
" void foo(Consumer<String> x) {}",
"}")
.addSourceLines(
"Test.java", //
"import java.util.function.Consumer;",
"public class Test extends Super {",
" void foo(Consumer<String> x) {}",
"}")
.doTest();
}
@Test
public void negativeSuperConstructor() {
testHelper
.addSourceLines(
"Super.java", //
"import java.util.function.Function;",
"class Super {",
" Super(Function<String, String> r) {}",
"}")
.addSourceLines(
"Test.java", //
"import java.util.function.Consumer;",
"public class Test extends Super {",
" Test(Consumer<String> r) { super(null); }",
"}")
.doTest();
}
@Test
public void positiveConstructor() {
testHelper
.addSourceLines(
"Test.java", //
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class Test {",
" // BUG: Diagnostic contains: Test(Function<String, String>)",
" Test(Consumer<String> r) {}",
" Test(Function<String, String> c) {}",
"}")
.doTest();
}
@Test
public void positiveStatic() {
testHelper
.addSourceLines(
"Test.java", //
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class Test {",
" // BUG: Diagnostic contains: foo(Function<String, String>)",
" static void foo(Consumer<String> x) {}",
" void foo(Function<String, String> c) {}",
"}")
.doTest();
}
@Test
public void suppressWarningsOnMethod() {
testHelper
.addSourceLines(
"Test.java",
"import java.lang.SuppressWarnings;",
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class Test {",
" @SuppressWarnings(\"FunctionalInterfaceClash\")",
" void foo(Consumer<String> x) {}",
" void foo(Function<String, String> c) {}",
"}")
.doTest();
}
@Test
public void shouldIgnore_transitiveInheritanceWithExpandedVisibility() {
testHelper
.addSourceLines(
"pkg1/FunctionalInterface.java",
"package pkg1;",
"public interface FunctionalInterface {",
" String apply(String s);",
"}")
.addSourceLines(
"pkg2/BaseClass.java",
"package pkg2;",
"import pkg1.FunctionalInterface;",
"public abstract class BaseClass {",
" abstract String doIt(FunctionalInterface fi);",
"}")
.addSourceLines(
"pkg2/DerivedClass.java",
"package pkg2;",
"import pkg1.FunctionalInterface;",
"public class DerivedClass extends BaseClass {",
" @Override public String doIt(FunctionalInterface fi) {",
" return null;",
" }",
"}")
.addSourceLines(
"pkg3/Test.java",
"package pkg3;",
"import pkg1.FunctionalInterface;",
"import pkg2.DerivedClass;",
"public class Test {",
" DerivedClass getDerivedClass() {",
" return new DerivedClass() {",
" @Override public String doIt(FunctionalInterface fi) {",
" return null;",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void negative_multipleClashingOverriddenMethods() {
testHelper
.addSourceLines(
"pkg2/BaseClass.java",
"package pkg2;",
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public abstract class BaseClass {",
" // BUG: Diagnostic contains: When passing lambda arguments to this function",
" abstract void baz(Consumer<String> c);",
" abstract void baz(Function<String, Integer> f);",
"}")
.addSourceLines(
"pkg2/DerivedClass.java",
"package pkg2;",
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class DerivedClass extends BaseClass {",
" @Override void baz(Consumer<String> c) {}",
" @Override void baz(Function<String, Integer> f) {}",
"}")
.doTest();
}
@Test
public void negative_singleClashingOverriddenMethods() {
testHelper
.addSourceLines(
"pkg2/BaseClass.java",
"package pkg2;",
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public abstract class BaseClass {",
" abstract void bar(Consumer<String> c);",
"}")
.addSourceLines(
"pkg2/DerivedClass.java",
"package pkg2;",
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class DerivedClass extends BaseClass {",
" @Override void bar(Consumer<String> c) {}",
"}")
.doTest();
}
@Test
public void positive_overriddenAndNewClashingMethod() {
testHelper
.addSourceLines(
"pkg2/BaseClass.java",
"package pkg2;",
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class BaseClass {",
" void conduct(Consumer<String> c) {}",
"}")
.addSourceLines(
"pkg2/ConductClass.java",
"package pkg2;",
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class ConductClass extends BaseClass {",
" // BUG: Diagnostic contains: disambiguate with:",
" @Override void conduct(Consumer<String> c) {}",
" void conduct(Function<String, Integer> f) {}",
"}")
.doTest();
}
@Test
public void negative_overriddenMethod() {
testHelper
.addSourceLines(
"pkg2/BaseClass.java",
"package pkg2;",
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class BaseClass {",
" void conduct(Consumer<String> c) {}",
"}")
.addSourceLines(
"pkg2/ConductClass.java",
"package pkg2;",
"import java.util.function.Function;",
"import java.util.function.Consumer;",
"public class ConductClass extends BaseClass {",
" @Override void conduct(Consumer<String> c) {}",
"}")
.doTest();
}
@Test
public void positive_overriddenInClassAndNewClashingMethod() {
testHelper
.addSourceLines(
"pkg2/Super.java",
"package pkg2;",
"import java.util.function.Consumer;",
"public abstract class Super {",
" void barr(Consumer<String> c) {}",
"}")
.addSourceLines(
"pkg2/BaseClass.java",
"package pkg2;",
"import java.util.function.Consumer;",
"public abstract class BaseClass extends Super {",
" void barr(Consumer<String> c) {}",
"}")
.addSourceLines(
"pkg2/MyDerivedClass.java",
"package pkg2;",
"import java.util.function.Function;",
"public class MyDerivedClass extends BaseClass {",
" // BUG: Diagnostic contains: disambiguate with:",
" void barr(Function<String, Integer> f) {}",
"}")
.doTest();
}
@Test
public void positive_overridesInClassAndNewClashingPairInSameClass() {
testHelper
.addSourceLines(
"pkg2/Super.java",
"package pkg2;",
"import java.util.function.Consumer;",
"import java.util.function.Function;",
"public abstract class Super {",
" // BUG: Diagnostic contains: When passing lambda arguments to this function",
" void barr(Function<String, Integer> f) {}",
" void barr(Consumer<String> c) {}",
"}")
.addSourceLines(
"pkg2/BaseClass.java",
"package pkg2;",
"import java.util.function.Consumer;",
"import java.util.function.Function;",
"public abstract class BaseClass extends Super {",
" void barr(Function<String, Integer> f) {}",
" void barr(Consumer<String> c) {}",
" // BUG: Diagnostic contains: When passing lambda arguments to this function",
" void foo(Function<Integer, Integer> f) {}",
" void foo(Consumer<Integer> c) {}",
"}")
.doTest();
}
@Test
public void oneIsMoreSpecific_notAmbiguous() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.function.Consumer;",
"public class Test {",
" void foo(Consumer<String> c) {}",
" void foo(SubConsumer<String> c) {}",
" interface SubConsumer<T> extends Consumer<T> {}",
"}")
.doTest();
}
}
| 12,939
| 32.436693
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ComputeIfAbsentAmbiguousReferenceTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link ComputeIfAbsentAmbiguousReference} bug pattern.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@RunWith(JUnit4.class)
public class ComputeIfAbsentAmbiguousReferenceTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ComputeIfAbsentAmbiguousReference.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import java.util.ArrayList;",
"import java.util.HashMap;",
"import java.util.List;",
"import java.util.Map;",
"import java.util.concurrent.atomic.AtomicLong;",
"class Test {",
" private void doWorkAtomicLong(Map<Long, AtomicLong> map) {",
" Long key = 4L;",
" // BUG: Diagnostic contains: ComputeIfAbsentAmbiguousReference",
" map.computeIfAbsent(key, AtomicLong::new).incrementAndGet();",
" }",
"}")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import java.util.Map;",
"import java.util.concurrent.atomic.AtomicLong;",
"import java.util.function.Function;",
"class Test {",
" private void doWork(Map<Long, AtomicLong> map) {",
" Long key = 4L;",
" Function<Long, AtomicLong> longBuilder = AtomicLong::new;",
" map.computeIfAbsent(key, k -> new AtomicLong(k));",
" map.computeIfAbsent(key, longBuilder);",
" map.computeIfAbsent(key, (Function<Long, AtomicLong>) AtomicLong::new);",
" }",
" private void doWorkStringArray(Map<Integer, String[]> map) {",
" Integer key = 4;",
" map.computeIfAbsent(key, String[]::new);",
" }",
" private void doWorkInnerClass1(Map<Long, InnerClass1> map) {",
" map.computeIfAbsent(0L, InnerClass1::new);",
" }",
" /** Class with exactly one 1-argument constructor. **/",
" class InnerClass1 {",
" InnerClass1(long l) {}",
" }",
" private void doWorkInnerClass2(Map<Integer, InnerClass2> map) {",
" map.computeIfAbsent(0, InnerClass2::new);",
" }",
" /** Class with two 1-argument constructors. **/",
" class InnerClass2 {",
" InnerClass2(int i) {}",
" InnerClass2(String s) {}",
" }",
"}")
.doTest();
}
@Test
public void negativeCase_parameterNameMatch() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import java.util.HashMap;",
"import java.util.Map;",
"import java.util.concurrent.atomic.AtomicLong;",
"class Test {",
" private void doWorkAtomicLong(Map<Long, AtomicLong> map) {",
" Long initialValue = 4L;",
" map.computeIfAbsent(initialValue, AtomicLong::new);",
" }",
" private void doWork(Map<Integer, HashMap> map) {",
" Integer initialCapacity = 4;",
" map.computeIfAbsent(initialCapacity, HashMap::new);",
" }",
"}")
.doTest();
}
}
| 4,243
| 36.22807
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ShortCircuitBooleanTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ShortCircuitBoolean}Test */
@RunWith(JUnit4.class)
public class ShortCircuitBooleanTest {
@Test
public void positive() {
CompilationTestHelper.newInstance(ShortCircuitBoolean.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" void f(boolean b1, boolean b2, boolean b3, int i1, int i2) {",
" // BUG: Diagnostic contains: b1 && b2",
" boolean r = b1 & b2;",
" // BUG: Diagnostic contains: b1 || b2",
" r = b1 | b2;",
" // BUG: Diagnostic contains: b1 || !b2 || b3 && b1 && b2",
" r = b1 | !b2 | b3 & b1 & b2;",
" // BUG: Diagnostic contains: b1 || (b2 && b3) && (b1 || b2)",
" r = b1 | (b2 & b3) & (b1 | b2);",
" // BUG: Diagnostic contains: b1 || (b2 && b3)",
" r = b1 | (b2 & b3);",
" // BUG: Diagnostic contains: (b1 || b2) && b3",
" r = (b1 | b2) & b3;",
" // BUG: Diagnostic contains: b1 || b3 && b3",
" r = b1 | b3 && b3;",
" // BUG: Diagnostic contains: b1 || b2 == b3",
" r = b1 | b2 == b3;",
" // BUG: Diagnostic contains: (b1 || b2) != b3",
" r = (b1 | b2) != b3;",
" int i = i1 | i2;",
" i = i1 & i2;",
" i = i1 & i2 | i1;",
" }",
"}")
.doTest();
}
}
| 2,286
| 36.491803
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MustBeClosedCheckerTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link MustBeClosedChecker}. */
@RunWith(JUnit4.class)
public class MustBeClosedCheckerTest {
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(MustBeClosedChecker.class, getClass());
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(MustBeClosedChecker.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("MustBeClosedCheckerPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("MustBeClosedCheckerNegativeCases.java").doTest();
}
@Test
public void refactoring() {
refactoringHelper
.addInput("MustBeClosedCheckerPositiveCases.java")
.addOutput("MustBeClosedCheckerPositiveCases_expected.java")
.allowBreakingChanges() // The fix is best-effort, and some variable names may clash
.doTest();
}
@Test
public void enumInitializer() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.MustBeClosed;",
"import java.io.Closeable;",
"enum Test {",
" A;",
" interface Foo extends Closeable {}",
" @MustBeClosed static Foo createResource() {",
" return null;",
" }",
" private final Foo resource;",
" private final Foo resource2 = createResource();",
" Test() {",
" this.resource = createResource();",
" }",
"}")
.doTest();
}
@Test
public void forLoop() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.annotations.MustBeClosed;",
"class Test {",
" class Closeable implements AutoCloseable {",
" @Override",
" public void close() {}",
" public int method() {",
" return 1;",
" }",
" }",
" class Foo {",
" @MustBeClosed",
" Closeable mustBeClosedMethod() {",
" return null;",
" }",
" }",
" void forLoopCondition() {",
" for (int i = 0; i < new Foo().mustBeClosedMethod().method(); ++i) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.annotations.MustBeClosed;",
"class Test {",
" class Closeable implements AutoCloseable {",
" @Override",
" public void close() {}",
" public int method() {",
" return 1;",
" }",
" }",
" class Foo {",
" @MustBeClosed",
" Closeable mustBeClosedMethod() {",
" return null;",
" }",
" }",
" void forLoopCondition() {",
" try (var closeable = new Foo().mustBeClosedMethod()) {",
" for (int i = 0; i < closeable.method(); ++i) {}",
" }",
" }",
"}")
.doTest();
}
@Ignore("b/236715080")
@Test
public void forLoopUnfixable() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.annotations.MustBeClosed;",
"class Test {",
" class Closeable implements AutoCloseable {",
" @Override",
" public void close() {}",
" public int method() {",
" return 1;",
" }",
" }",
" class Foo {",
" @MustBeClosed",
" Closeable mustBeClosedMethod() {",
" return null;",
" }",
" }",
" void forLoopInitialization() {",
" for (int i = new Foo().mustBeClosedMethod().method(); i > 0; --i) { }",
" }",
" void forLoopUpdate() {",
" for (int i = 0; i < 100; i += new Foo().mustBeClosedMethod().method()) {}",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| 5,239
| 31.955975
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/WithSignatureDiscouragedTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author amalloy@google.com (Alan Malloy)
*/
@RunWith(JUnit4.class)
public class WithSignatureDiscouragedTest {
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(WithSignatureDiscouraged.class, getClass());
@Test
public void named() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ExpressionTree;",
"public class Test {",
" private static final Matcher<ExpressionTree> TO_STRING = ",
" instanceMethod()",
" .anyClass()",
" .withSignature(\"toString\");",
"}")
.addOutputLines(
"Test.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ExpressionTree;",
"public class Test {",
" private static final Matcher<ExpressionTree> TO_STRING = ",
" instanceMethod()",
" .anyClass()",
" .named(\"toString\");",
"}")
.doTest();
}
@Test
public void withEmptyParameterList() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ExpressionTree;",
"public class Test {",
" private static final Matcher<ExpressionTree> TO_STRING = ",
" instanceMethod()",
" .anyClass()",
" .withSignature(\"toString()\");",
"}")
.addOutputLines(
"Test.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ExpressionTree;",
"public class Test {",
" private static final Matcher<ExpressionTree> TO_STRING = ",
" instanceMethod()",
" .anyClass()",
" .named(\"toString\")",
" .withNoParameters();",
"}")
.doTest();
}
@Test
public void withParameters() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ExpressionTree;",
"public class Test {",
" private static final Matcher<ExpressionTree> VALUE_OF = ",
" instanceMethod()",
" .anyClass()",
" .withSignature(\"valueOf(double)\");",
"}")
.addOutputLines(
"Test.java",
"import static com.google.errorprone.matchers.Matchers.instanceMethod;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ExpressionTree;",
"public class Test {",
" private static final Matcher<ExpressionTree> VALUE_OF = ",
" instanceMethod()",
" .anyClass()",
" .named(\"valueOf\")",
" .withParameters(\"double\");",
"}")
.doTest();
}
@Test
public void leaveVarargs() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import static com.google.errorprone.matchers.Matchers.staticMethod;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ExpressionTree;",
"public class Test {",
" private static final Matcher<ExpressionTree> STRING_FORMAT = ",
" staticMethod()",
" .onClass(\"java.lang.String\")",
" .withSignature(\"format(java.lang.String,java.lang.Object...)\");",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void leaveGenerics() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import static com.google.errorprone.matchers.Matchers.staticMethod;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ExpressionTree;",
"public class Test {",
" private static final Matcher<ExpressionTree> TO_STRING = ",
" staticMethod()",
" .onClass(\"com.google.common.collect.ImmutableList\")",
" .withSignature(\"<E>builder()\");",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void dontMigrateArrays() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import static com.google.errorprone.matchers.Matchers.staticMethod;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ExpressionTree;",
"public class Test {",
" private static final Matcher<ExpressionTree> TO_STRING = ",
" staticMethod()",
" .onClass(\"java.lang.String\")",
" .withSignature(\"copyValueOf(char[])\");",
"}")
.expectUnchanged()
.doTest();
}
}
| 6,426
| 36.366279
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DoNotClaimAnnotationsTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link DoNotClaimAnnotations}Test */
@RunWith(JUnit4.class)
public class DoNotClaimAnnotationsTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(DoNotClaimAnnotations.class, getClass());
@Test
public void positive() {
testHelper
.addInputLines(
"Test.java",
"import java.util.Set;",
"import javax.annotation.processing.Processor;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.lang.model.element.TypeElement;",
"abstract class Test implements Processor {",
" @Override",
" public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment"
+ " roundEnv) {",
" return true;",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Set;",
"import javax.annotation.processing.Processor;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.lang.model.element.TypeElement;",
"abstract class Test implements Processor {",
" @Override",
" public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment"
+ " roundEnv) {",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addInputLines(
"Test.java",
"import java.util.Set;",
"import javax.annotation.processing.Processor;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.lang.model.element.TypeElement;",
"abstract class Test implements Processor {",
" @Override",
" public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment"
+ " roundEnv) {",
" return false;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void negative_notAProcessor() {
testHelper
.addInputLines(
"Test.java",
"import java.util.Set;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.lang.model.element.TypeElement;",
"abstract class Test {",
" public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment"
+ " roundEnv) {",
" return true;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void unfixable() {
CompilationTestHelper.newInstance(DoNotClaimAnnotations.class, getClass())
.addSourceLines(
"Test.java",
"import java.util.Set;",
"import javax.annotation.processing.Processor;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.annotation.processing.RoundEnvironment;",
"import javax.lang.model.element.TypeElement;",
"abstract class Test implements Processor {",
" abstract boolean helper();",
" @Override",
" public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment"
+ " roundEnv) {",
" try {",
" // BUG: Diagnostic contains:",
" return helper();",
" } catch (Throwable t) {}",
" return false;",
" }",
"}")
.doTest();
}
}
| 4,774
| 35.450382
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnitParameterMethodNotFoundTest.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JUnitParameterMethodNotFound} */
@RunWith(JUnit4.class)
public class JUnitParameterMethodNotFoundTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JUnitParameterMethodNotFound.class, getClass());
@Test
public void negativeCase_noErrorsFound() {
compilationHelper.addSourceFile("JUnitParameterMethodNotFoundNegativeCase.java").doTest();
}
@Test
public void negativeCase_nonJUnitParamsRunner_noErrorsFound() {
compilationHelper
.addSourceFile("JUnitParameterMethodNotFoundNegativeCaseNonJUnitParamsRunner.java")
.doTest();
}
@Test
public void negativeCase_inheritedMethods_noErrorsFound() {
compilationHelper
.addSourceFile("JUnitParameterMethodNotFoundNegativeCaseBaseClass.java")
.addSourceFile("JUnitParameterMethodNotFoundNegativeCaseSuperClass.java")
.doTest();
}
@Test
public void positiveCase_errorReported() {
compilationHelper.addSourceFile("JUnitParameterMethodNotFoundPositiveCase.java").doTest();
}
}
| 1,866
| 32.945455
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ChainedAssertionLosesContextTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
@RunWith(JUnit4.class)
public class ChainedAssertionLosesContextTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ChainedAssertionLosesContext.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("ChainedAssertionLosesContextPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("ChainedAssertionLosesContextNegativeCases.java").doTest();
}
}
| 1,348
| 31.119048
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LockNotBeforeTryTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link LockNotBeforeTry} bugpattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class LockNotBeforeTryTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(LockNotBeforeTry.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(LockNotBeforeTry.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" try {",
" // BUG: Diagnostic contains:",
" lock.lock();",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" lock.lock();",
" try {",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.doTest();
}
@Test
public void ignoresMultipleLocks() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lockA, ReentrantLock lockB) {",
" try {",
" lockA.lock();",
" lockB.lock();",
" System.out.println(\"hi\");",
" } finally {",
" lockA.unlock();",
" lockB.unlock();",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactorToBefore() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" try {",
" lock.lock();",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" lock.lock();",
" try {",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.doTest();
}
@Test
public void interspersed() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" try {",
" System.out.println(\"hi\");",
" // BUG: Diagnostic contains:",
" lock.lock();",
" System.out.println(\"bye\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void refactorIntermediate() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" lock.lock();",
" System.out.println(\"hi\");",
" try {",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" lock.lock();",
" try {",
" System.out.println(\"hi\");",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactorUnlockOutsideTry() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" lock.lock();",
" System.out.println(\"hi\");",
" lock.unlock();",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" lock.lock();",
" try {",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.doTest();
}
@Test
public void twoRegions() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" lock.lock();",
" System.out.println(\"hi\");",
" lock.unlock();",
" lock.lock();",
" try {",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" lock.lock();",
" try {",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" lock.lock();",
" try {",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.doTest();
}
@Test
public void unclosed() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock) {",
" // BUG: Diagnostic contains:",
" lock.lock();",
" System.out.println(\"hi\");",
" lock.lock();",
" try {",
" System.out.println(\"hi\");",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void receiverless() {
compilationHelper
.addSourceLines(
"Test.java",
"abstract class Test implements java.util.concurrent.locks.Lock {",
" private void test() {",
" lock();",
" try {",
" } finally {",
" unlock();",
" }",
" }",
"}")
.doTest();
}
@Test
public void receiverless2() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.locks.Lock;",
"abstract class Test implements Lock {",
" private void test(Lock l) {",
" lock();",
" l.lock();",
" try {",
" } finally {",
" unlock();",
" l.unlock();",
" }",
" }",
"}")
.doTest();
}
@Test
public void nonInvocationExpression() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantLock;",
"abstract class Test {",
" private void test(ReentrantLock lock) {",
" String s;",
" // BUG: Diagnostic contains:",
" lock.lock();",
" s = lock.toString();",
" lock.unlock();",
" }",
"}")
.doTest();
}
@Test
public void nullCheck() {
refactoringHelper
.addInputLines(
"Test.java",
"import static java.util.Objects.requireNonNull;",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock, Runnable r) {",
" lock.lock();",
" requireNonNull(r);",
" try {",
" r.run();",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"import static java.util.Objects.requireNonNull;",
"import java.util.concurrent.locks.ReentrantLock;",
"class Test {",
" private void test(ReentrantLock lock, Runnable r) {",
" lock.lock();",
" try {",
" requireNonNull(r);",
" r.run();",
" } finally {",
" lock.unlock();",
" }",
" }",
"}")
.doTest();
}
}
| 10,978
| 28.834239
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ClassNewInstanceTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ClassNewInstance}Test */
@RunWith(JUnit4.class)
public class ClassNewInstanceTest {
private BugCheckerRefactoringTestHelper testHelper;
@Before
public void setUp() {
testHelper = BugCheckerRefactoringTestHelper.newInstance(ClassNewInstance.class, getClass());
}
@Test
public void differentHandles() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().newInstance();",
" } catch (InstantiationException e1) {",
" e1.printStackTrace();",
" } catch (IllegalAccessException e2) {",
" e2.printStackTrace();",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (InstantiationException e1) {",
" e1.printStackTrace();",
" } catch (IllegalAccessException e2) {",
" e2.printStackTrace();",
" } catch (ReflectiveOperationException e2) {",
" throw new LinkageError(e2.getMessage(), e2);",
" }",
" }",
"}")
.doTest();
}
@Test
public void existingRoeCase() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().newInstance();",
" } catch (InstantiationException e) {",
" } catch (ReflectiveOperationException e) {",
" // ¯\\_(ツ)_/¯",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (InstantiationException e) {",
" } catch (ReflectiveOperationException e) {",
" // ¯\\_(ツ)_/¯",
" }",
" }",
"}")
.doTest();
}
@Test
public void positive() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().newInstance();",
" } catch (InstantiationException e) {",
" e.printStackTrace();",
" } catch (IllegalAccessException e) {",
" e.printStackTrace();",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (ReflectiveOperationException e) {",
" e.printStackTrace();",
" }",
" }",
"}")
.doTest();
}
@Test
public void positiveUnion() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().newInstance();",
" } catch (InstantiationException | IllegalAccessException e0) {",
" e0.printStackTrace();",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (ReflectiveOperationException e0) {",
" e0.printStackTrace();",
" }",
" }",
"}")
.doTest();
}
@Test
public void positiveROE() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().newInstance();",
" } catch (ReflectiveOperationException e) {",
" e.printStackTrace();",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (ReflectiveOperationException e) {",
" e.printStackTrace();",
" }",
" }",
"}")
.doTest();
}
@Test
public void throwsException() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() throws Exception {",
" getClass().newInstance();",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() throws Exception {",
" getClass().getDeclaredConstructor().newInstance();",
" }",
"}")
.doTest();
}
@Test
public void throwsROE() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() throws ReflectiveOperationException {",
" getClass().newInstance();",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() throws ReflectiveOperationException {",
" getClass().getDeclaredConstructor().newInstance();",
" }",
"}")
.doTest();
}
@Test
public void throwsIndividual() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() throws InstantiationException, IllegalAccessException {",
" getClass().newInstance();",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.lang.reflect.InvocationTargetException;",
"class Test {",
" void f()",
" throws InstantiationException, IllegalAccessException,"
+ " InvocationTargetException,",
" NoSuchMethodException {",
" getClass().getDeclaredConstructor().newInstance();",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() throws Exception {",
" getClass().getDeclaredConstructor().newInstance();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void catchesDoesntThrow() {
testHelper
.addInputLines(
"in/Test.java",
"import java.io.IOException;",
"class Test {",
" void f() throws IOException {",
" try {",
" getClass().newInstance();",
" } catch (ReflectiveOperationException e) {}",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.io.IOException;",
"class Test {",
" void f() throws IOException {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (ReflectiveOperationException e) {}",
" }",
"}")
.doTest();
}
@Test
public void negativeThrows() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() throws Exception {",
" getClass().getDeclaredConstructor().newInstance();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void mergeWhitespace() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().newInstance();",
" } catch (InstantiationException e) {",
" // uh oh",
" } catch (IllegalAccessException e) {",
" // uh oh",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (ReflectiveOperationException e) {",
" // uh oh",
" }",
" }",
"}")
.doTest();
}
@Test
public void overlap() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() throws Exception {",
" getClass().newInstance().getClass().newInstance();",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() throws Exception {",
" getClass().getDeclaredConstructor().newInstance()"
+ ".getClass().getDeclaredConstructor().newInstance();",
" }",
"}")
.doTest();
}
@Test
public void inCatch() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() throws Exception {",
" try {",
" getClass().newInstance();",
" } catch (InstantiationException e) {",
" getClass().newInstance();",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() throws Exception {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (ReflectiveOperationException e) {",
" getClass().getDeclaredConstructor().newInstance();",
" }",
" }",
"}")
.doTest();
}
@Test
public void withFinally() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() throws Exception {",
" try {",
" getClass().newInstance();",
" } finally {}",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() throws Exception {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } finally {}",
" }",
"}")
.doTest();
}
@Test
public void inCatchRepeated() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() throws InstantiationException, IllegalAccessException {",
" try {",
" getClass().newInstance();",
" } catch (InstantiationException e) {",
" getClass().newInstance();",
" } catch (IllegalAccessException e) {",
" getClass().newInstance();",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.lang.reflect.InvocationTargetException;",
"class Test {",
" void f()",
" throws InstantiationException, IllegalAccessException,"
+ " InvocationTargetException,",
" NoSuchMethodException {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (InstantiationException e) {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (ReflectiveOperationException e) {",
" getClass().getDeclaredConstructor().newInstance();",
" }",
" }",
"}")
.doTest();
}
@Test
public void additionalCatchClause() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" Object f() {",
" try {",
" return getClass().newInstance();",
" } catch (InstantiationException ex) {",
" // Suppress exception.",
" } catch (IllegalAccessException ex) {",
" // Suppress exception.",
" } catch (ExceptionInInitializerError ex) {",
" // Suppress exception.",
" } catch (SecurityException ex) {",
" // Suppress exception.",
" }",
" return null;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" Object f() {",
" try {",
" return getClass().getDeclaredConstructor().newInstance();",
" } catch (ReflectiveOperationException ex) {",
" // Suppress exception.",
" } catch (ExceptionInInitializerError ex) {",
" // Suppress exception.",
" } catch (SecurityException ex) {",
" // Suppress exception.",
" }",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void catchAndThrows() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" Object f() throws InstantiationException, IllegalAccessException {",
" try {",
" return getClass().newInstance();",
" } catch (ReflectiveOperationException ex) {",
" return getClass().newInstance();",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.lang.reflect.InvocationTargetException;",
"class Test {",
" Object f()",
" throws InstantiationException, IllegalAccessException,"
+ " InvocationTargetException,",
" NoSuchMethodException {",
" try {",
" return getClass().getDeclaredConstructor().newInstance();",
" } catch (ReflectiveOperationException ex) {",
" return getClass().getDeclaredConstructor().newInstance();",
" }",
" }",
"}")
.doTest();
}
@Test
public void mixedMulticatch() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().newInstance();",
" } catch (InstantiationException e) {",
" // InstantiationException",
" } catch (IllegalAccessException | NullPointerException e) {",
" throw new AssertionError(e);",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (InstantiationException e) {",
" // InstantiationException",
" } catch (ReflectiveOperationException | NullPointerException e) {",
" throw new AssertionError(e);",
" }",
" }",
"}")
.doTest();
}
@Test
public void freshVar() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f(Exception e) {",
" try {",
" getClass().newInstance();",
" } catch (InstantiationException e1) {",
" // one",
" } catch (IllegalAccessException e1) {",
" // two",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f(Exception e) {",
" try {",
" getClass().getDeclaredConstructor().newInstance();",
" } catch (InstantiationException e1) {",
" // one",
" } catch (IllegalAccessException e1) {",
" // two",
" } catch (ReflectiveOperationException e1) {",
" throw new LinkageError(e1.getMessage(), e1);",
" }",
" }",
"}")
.doTest();
}
}
| 17,828
| 29.686747
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ImpossibleNullComparisonTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author flx@google.com (Felix Berger)
*/
@RunWith(JUnit4.class)
@Ignore("b/130670448")
public final class ImpossibleNullComparisonTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ImpossibleNullComparison.class, getClass());
@Test
public void scalarCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void test() {",
" TestProtoMessage message = TestProtoMessage.newBuilder().build();",
" // BUG: Diagnostic contains: message.hasMessage()",
" if (message.getMessage() != null) {}",
" // BUG: Diagnostic contains: !message.hasMessage()",
" if (message.getMessage() == null) {}",
" // BUG: Diagnostic contains: message.hasMessage()",
" if (null != message.getMessage()) {}",
" // BUG: Diagnostic contains: message.getMessage().hasField()",
" if (message.getMessage().getField() != null) {}",
" }",
"}")
.doTest();
}
@Test
public void listCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"class Test {",
" void test() {",
" TestProtoMessage message = TestProtoMessage.newBuilder().build();",
" TestFieldProtoMessage field = message.getMessage();",
" // BUG: Diagnostic contains: !message.getMultiFieldList().isEmpty()",
" if (message.getMultiFieldList() != null) {}",
" // BUG: Diagnostic contains: message.getMultiFieldList().isEmpty()",
" if (null == message.getMultiFieldList()) {}",
" // BUG: Diagnostic contains: message.getMultiFieldCount() > 1",
" if (message.getMultiField(1) != null) {}",
" // BUG: Diagnostic contains: message.getMultiFieldCount() <= 1",
" if (message.getMultiField(1) == null) {}",
" }",
"}")
.doTest();
}
@Test
public void intermediateVariable() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import java.util.List;",
"class Test {",
" void test() {",
" TestProtoMessage message = TestProtoMessage.newBuilder().build();",
" TestFieldProtoMessage field = message.getMessage();",
" List<TestFieldProtoMessage> fields = message.getMultiFieldList();",
" // BUG: Diagnostic contains: message.hasMessage()",
" if (field != null) {}",
" // BUG: Diagnostic contains: !message.getMultiFieldList().isEmpty()",
" if (fields != null) {}",
" }",
"}")
.doTest();
}
@Test
public void negativeCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" public void test() {",
" TestProtoMessage message = TestProtoMessage.newBuilder().build();",
" Object object = new Object();",
" if (message.getMessage() != object) {}",
" if (object != message.getMessage()) {}",
" if (message.getMessage().getField() != object) {}",
" if (message.getMultiFieldList() != object) {}",
" if (object == message.getMultiFieldList()) {}",
" }",
"}")
.doTest();
}
@Test
public void proto3() {
compilationHelper
.addSourceLines(
"TestProto3.java",
"import com.google.errorprone.bugpatterns.proto.Proto3Test.TestProto3Message;",
"public class TestProto3 {",
" public boolean doIt(TestProto3Message proto3Message) {",
" // BUG: Diagnostic matches: NO_FIX",
" return proto3Message.getMyString() == null;",
" }",
"}")
.expectErrorMessage("NO_FIX", input -> !input.contains("hasMyString()"))
.doTest();
}
@Test
public void messageOrBuilderGetField() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.protobuf.Descriptors.FieldDescriptor;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"public class Test {",
" public boolean doIt(TestProtoMessage mob, FieldDescriptor f) {",
" // BUG: Diagnostic contains:",
" return mob.getField(f) == null;",
" }",
"}")
.doTest();
}
@Test
public void messageOrBuilderGetFieldCast() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.protobuf.Descriptors.FieldDescriptor;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"public class Test {",
" public boolean doIt(TestProtoMessage mob, FieldDescriptor f) {",
" String s = ((String) mob.getField(f));",
" // BUG: Diagnostic contains:",
" return s == null;",
" }",
"}")
.doTest();
}
@Test
public void extendableMessageGetExtension1param() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.protobuf.ExtensionLite;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"public class Test {",
" public void test(TestProtoMessage e, ExtensionLite extensionLite) {",
" // BUG: Diagnostic contains:",
" boolean a = e.getExtension(extensionLite) == null;",
" }",
"}")
.doTest();
}
@Test
public void messageOrBuilderGetRepeatedField() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.protobuf.Descriptors.FieldDescriptor;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"public class Test {",
" public void doIt(TestProtoMessage mob, FieldDescriptor f) {",
" // BUG: Diagnostic contains:",
" boolean a = mob.getRepeatedField(f, 0) == null;",
" }",
"}")
.doTest();
}
@Test
public void extendableMessageGetExtension2param() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.protobuf.ExtensionLite;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"public class Test {",
" public void test(TestProtoMessage e, ExtensionLite extensionLite) {",
" // BUG: Diagnostic contains:",
" boolean a = e.getExtension(extensionLite, 0) == null;",
" }",
"}")
.doTest();
}
@Test
public void repeated() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.protobuf.ExtensionLite;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import java.util.List;",
"public class Test {",
" public void test(ExtensionLite<TestProtoMessage,",
" List<TestFieldProtoMessage>> e, TestProtoMessage message) {",
" // BUG: Diagnostic contains:",
" boolean y = message.getExtension(e) == null;",
" }",
"}")
.doTest();
}
@Test
public void repeated2() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.protobuf.Extension.MessageType;",
"import com.google.protobuf.ExtensionLite;",
"import com.google.protobuf.GeneratedMessage;",
"import com.sun.tools.javac.code.Type;",
"import com.google.common.collect.ImmutableList;",
"import java.util.List;",
"public class Test {",
"public static <MessageType extends GeneratedMessage.ExtendableMessage<MessageType>,",
"Type extends GeneratedMessage>",
"List<Type> getRepeatedExtensionObjects(",
"GeneratedMessage.ExtendableMessage<MessageType> mob,",
" ExtensionLite<MessageType, List<Type>> extension) {",
" ImmutableList.Builder extensionList = ImmutableList.builder();",
" int extensionCount = mob.getExtensionCount(extension);",
" for (int extensionIndex = 0; extensionIndex < extensionCount; ++extensionIndex) {",
" // BUG: Diagnostic contains:",
" boolean y = mob.getExtension(extension) == null;",
" extensionList.add(mob.getExtension(extension));",
" }",
" return extensionList.build();",
"}",
"}")
.addModules("jdk.compiler/com.sun.tools.javac.code")
.doTest();
}
@Test
public void preconditions() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkNotNull;",
"import static com.google.common.base.Verify.verifyNotNull;",
"import static java.util.Objects.requireNonNull;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import java.util.List;",
"class Test {",
" void test() {",
" TestProtoMessage message = TestProtoMessage.newBuilder().build();",
" TestFieldProtoMessage field = message.getMessage();",
" // BUG: Diagnostic contains: This value cannot be null",
" // remove this line",
" checkNotNull(field);",
" // BUG: Diagnostic contains: This value cannot be null",
" // remove this line",
" checkNotNull(message.getMessage());",
" // BUG: Diagnostic contains: This value cannot be null",
" // remove this line",
" verifyNotNull(message.getMessage());",
" // BUG: Diagnostic contains: This value cannot be null",
" // remove this line",
" checkNotNull(message.getMultiFieldList());",
" // BUG: Diagnostic contains: This value cannot be null",
" // remove this line",
" checkNotNull(message.getMessage(), new Object());",
" // BUG: Diagnostic contains: This value cannot be null",
" // remove this line",
" checkNotNull(message.getMultiFieldList(), new Object());",
" // BUG: Diagnostic contains: This value cannot be null",
" // remove this line",
" checkNotNull(message.getMessage(), \"%s\", new Object());",
" // BUG: Diagnostic contains: This value cannot be null",
" // remove this line",
" checkNotNull(message.getMultiFieldList(), \"%s\", new Object());",
" // BUG: Diagnostic contains: fieldMessage = message.getMessage();",
" TestFieldProtoMessage fieldMessage = checkNotNull(message.getMessage());",
" // BUG: Diagnostic contains: fieldMessage2 = message.getMessage()",
" TestFieldProtoMessage fieldMessage2 = checkNotNull(message.getMessage(), \"M\");",
" // BUG: Diagnostic contains: message.getMessage().toString();",
" checkNotNull(message.getMessage()).toString();",
" // BUG: Diagnostic contains: message.getMessage().toString();",
" checkNotNull(message.getMessage(), \"Message\").toString();",
" // BUG: Diagnostic contains: TestFieldProtoMessage fieldCopy = field;",
" TestFieldProtoMessage fieldCopy = requireNonNull(field);",
" }",
"}")
.doTest();
}
@Test
public void assertions() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.junit.Assert.assertNotNull;",
"import com.google.common.truth.extensions.proto.ProtoTruth;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import java.util.List;",
"class Test {",
" void test() {",
" TestProtoMessage message = TestProtoMessage.newBuilder().build();",
" TestFieldProtoMessage field = message.getMessage();",
" // BUG: Diagnostic contains: assertTrue(\"Message\", message.hasMessage());",
" assertNotNull(\"Message\", message.getMessage());",
" // BUG: Diagnostic contains: assertThat(message.hasMessage()).isTrue()",
" assertThat(message.getMessage()).isNotNull();",
" // BUG: Diagnostic contains: assertThat(message.hasMessage()).isTrue()",
" ProtoTruth.assertThat(message.getMessage()).isNotNull();",
" }",
"}")
.doTest();
}
@Test
public void assertions_negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.junit.Assert.assertNotNull;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import java.util.List;",
"class Test {",
" void test() {",
" TestProtoMessage message = TestProtoMessage.newBuilder().build();",
" TestFieldProtoMessage field = message.getMessage();",
" assertNotNull(\"Message\", message.getMessage());",
" assertThat(message.getMessage()).isNotNull();",
" }",
"}")
.setArgs(ImmutableList.of("-XepOpt:ProtoFieldNullComparison:MatchTestAssertions=false"))
.doTest();
}
@Test
public void optional() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"import java.util.Optional;",
"class Test {",
" Optional<?> test() {",
" TestProtoMessage message = TestProtoMessage.newBuilder().build();",
" // BUG: Diagnostic contains: Optional.of(message.getMessage())",
" return Optional.ofNullable(message.getMessage());",
" }",
"}")
.doTest();
}
@Test
public void guavaOptional() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"import java.util.Optional;",
"class Test {",
" Optional<?> test() {",
" TestProtoMessage message = TestProtoMessage.newBuilder().build();",
" // BUG: Diagnostic contains: Optional.of(message.getMessage())",
" return Optional.ofNullable(message.getMessage());",
" }",
"}")
.doTest();
}
@Test
public void optionalGet() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" public boolean o(Optional<String> o) {",
" // BUG: Diagnostic contains: o.isEmpty()",
" return o.get() == null;",
" }",
"}")
.doTest();
}
@Test
public void guavaOptionalGet() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"public class Test {",
" public boolean o(Optional<String> o) {",
" // BUG: Diagnostic contains: !o.isPresent()",
" return o.get() == null;",
" }",
"}")
.doTest();
}
@Test
public void multimapGet() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Multimap;",
"public class Test {",
" public boolean o(Multimap<String, String> m) {",
" // BUG: Diagnostic contains: !m.containsKey(\"foo\")",
" return m.get(\"foo\") == null;",
" }",
"}")
.doTest();
}
@Test
public void listMultimapGet() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ListMultimap;",
"public class Test {",
" public boolean o(ListMultimap<String, String> m) {",
" // BUG: Diagnostic contains: !m.containsKey(\"foo\")",
" return m.get(\"foo\") == null;",
" }",
"}")
.doTest();
}
@Test
public void tables() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Table;",
"public class Test {",
" public void o(Table<String, String, String> t) {",
" // BUG: Diagnostic contains: !t.containsRow(\"foo\")",
" boolean b1 = t.row(\"foo\") == null;",
" // BUG: Diagnostic contains: !t.containsColumn(\"foo\")",
" boolean b2 = t.column(\"foo\") == null;",
" }",
"}")
.doTest();
}
}
| 19,475
| 39.406639
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NCopiesOfCharTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link NCopiesOfChar}Test */
@RunWith(JUnit4.class)
public class NCopiesOfCharTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NCopiesOfChar.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java", //
"import java.util.Collections;",
"class Test {{",
" // BUG: Diagnostic contains: nCopies(10, ' ');",
" Collections.nCopies(' ', 10);",
"}}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java", //
"import java.util.Collections;",
"class Test {{",
" Collections.nCopies(10, ' ');",
"}}")
.doTest();
}
}
| 1,629
| 28.107143
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FutureReturnValueIgnoredTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit4.class)
public class FutureReturnValueIgnoredTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FutureReturnValueIgnored.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("FutureReturnValueIgnoredPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("FutureReturnValueIgnoredNegativeCases.java").doTest();
}
@Test
public void classAnnotationButCanIgnoreReturnValue() {
compilationHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"public class Lib {",
" @com.google.errorprone.annotations.CanIgnoreReturnValue",
" public static java.util.concurrent.Future<?> f() { return null; }",
"}")
.addSourceLines(
"Test.java", //
"class Test {",
" void m() {",
" lib.Lib.f();",
" }",
"}")
.doTest();
}
@Test
public void completableFutureReturnValue() {
compilationHelper
.addSourceLines(
"test.java",
"import java.util.concurrent.CompletableFuture;",
"class Test {",
" void f(CompletableFuture<?> cf) {",
" cf.exceptionally(t -> null);",
" }",
"}")
.doTest();
}
@Test
public void completableFutureReturnValueJdk9() {
compilationHelper
.addSourceLines(
"test.java",
"import java.util.concurrent.CompletableFuture;",
"import static java.util.concurrent.TimeUnit.MILLISECONDS;",
"class Test {",
" void f(CompletableFuture<?> cf) {",
" cf.completeAsync(() -> null);",
" cf.completeAsync(() -> null, null);",
" cf.orTimeout(0, MILLISECONDS);",
" cf.completeOnTimeout(null, 0, MILLISECONDS);",
" }",
"}")
.doTest();
}
}
| 2,913
| 29.673684
| 91
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EqualsHashCodeTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link EqualsHashCode}Test */
@RunWith(JUnit4.class)
public class EqualsHashCodeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(EqualsHashCode.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("EqualsHashCodeTestPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("EqualsHashCodeTestNegativeCases.java").doTest();
}
@Test
public void superClassWithoutHashCode() {
compilationHelper
.addSourceLines("Super.java", "abstract class Super {}")
.addSourceLines(
"Test.java",
"class Test extends Super {",
" // BUG: Diagnostic contains:",
" public boolean equals(Object o) { return false; }",
"}")
.doTest();
}
@Test
public void inherited() {
compilationHelper
.addSourceLines(
"Super.java",
"class Super {",
" public int hashCode() {",
" return 42;",
" }",
"}")
.addSourceLines(
"Test.java",
"class Test extends Super {",
" public boolean equals(Object o) { return false; }",
"}")
.doTest();
}
@Test
public void interfaceEquals() {
compilationHelper
.addSourceLines("I.java", "interface I {", " boolean equals(Object o);", "}")
.doTest();
}
@Test
public void abstractHashCode() {
compilationHelper
.addSourceLines(
"Super.java",
"abstract class Super {",
" public abstract boolean equals(Object o);",
" public abstract int hashCode();",
"}")
.doTest();
}
@Test
public void abstractNoHashCode() {
compilationHelper
.addSourceLines(
"Super.java",
"abstract class Super {",
" // BUG: Diagnostic contains:",
" public abstract boolean equals(Object o);",
"}")
.doTest();
}
@Test
public void suppressOnEquals() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"EqualsHashCode\")",
" public boolean equals(Object o) { return false; }",
"}")
.doTest();
}
@Test
public void nopEquals() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public boolean equals(Object o) {",
" return super.equals(o);",
" }",
"}")
.doTest();
}
@Test
public void nopEqualsWithNullable() {
compilationHelper
.addSourceLines(
"Test.java",
"import javax.annotation.Nullable;",
"class Test {",
" public boolean equals(@Nullable Object o) {",
" return super.equals(o);",
" }",
"}")
.doTest();
}
}
| 3,849
| 26.112676
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ComparingThisWithNullTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link ComparingThisWithNull}. */
@RunWith(JUnit4.class)
public class ComparingThisWithNullTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(ComparingThisWithNull.class, getClass());
@Test
public void thisIsNull() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: ComparingThisWithNull",
" if (this == null) {",
" String x = \"Test\";",
" }",
" }",
"}")
.doTest();
}
@Test
public void nullIsThis() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: ComparingThisWithNull",
" if (null == this) {",
" String x = \"Test\";",
" }",
" }",
"}")
.doTest();
}
@Test
public void thisIsNotNull() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: ComparingThisWithNull",
" if (this != null) {",
" String x = \"Test\";",
" }",
" }",
"}")
.doTest();
}
@Test
public void nullIsNotThis() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: ComparingThisWithNull",
" if (null != this) {",
" String x = \"Test\";",
" }",
" }",
"}")
.doTest();
}
@Test
public void null_negative() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" Object o = new Object();",
" if (null != o) {",
" String x = \"Test\";",
" }",
" }",
"}")
.doTest();
}
@Test
public void this_negative() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" Object o = new Object();",
" if (this != o) {",
" String x = \"Test\";",
" }",
" }",
"}")
.doTest();
}
@Test
public void nullNot_negative() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" Object o = new Object();",
" if (null == o) {",
" String x = \"Test\";",
" }",
" }",
"}")
.doTest();
}
@Test
public void thisNot_negative() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" Object o = new Object();",
" if (this == o) {",
" String x = \"Test\";",
" }",
" }",
"}")
.doTest();
}
}
| 4,027
| 24.333333
| 81
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedVariableTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author awturner@google.com (Andy Turner)
*/
@RunWith(JUnit4.class)
public class UnnecessaryBoxedVariableTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryBoxedVariable.class, getClass());
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(UnnecessaryBoxedVariable.class, getClass());
@Test
public void cases() {
helper
.addInput("testdata/UnnecessaryBoxedVariableCases.java")
.addOutput("testdata/UnnecessaryBoxedVariableCases_expected.java")
.doTest();
}
@Test
public void suppression() {
helper
.addInputLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"UnnecessaryBoxedVariable\")",
" private int a(Integer o) {",
" return o;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void lambdas() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" interface Boxed<O> { void a(O b); }",
" void boxed(Boxed<?> b) {}",
" private void test() {",
" boxed((Double a) -> { double b = a + 1; });",
" }",
"}")
.doTest();
}
@Test
public void lambdaReturn() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" interface F {",
" int f(Integer i);",
" }",
" Test() {",
" F f = (Integer i) -> {",
" return i;",
" };",
" }",
"}")
.doTest();
}
}
| 2,643
| 28.054945
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OptionalOfRedundantMethodTest.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link OptionalOfRedundantMethod}. */
@RunWith(JUnit4.class)
public class OptionalOfRedundantMethodTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(OptionalOfRedundantMethod.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(OptionalOfRedundantMethod.class, getClass());
@Test
public void positive_ifPresent() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: ifPresent",
" Optional.of(\"test\").ifPresent(String::length);",
" }",
"}")
.doTest();
}
@Test
public void positive_ifPresent_refactoring_ofNullableFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" Optional.of(\"test\").ifPresent(String::length);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" Optional.ofNullable(\"test\").ifPresent(String::length);",
" }",
"}")
.doTest();
}
@Test
public void positive_orElse() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: orElse",
" Optional.of(\"test\").orElse(\"test2\");",
" }",
"}")
.doTest();
}
@Test
public void positive_orElse_refactoring_ofNullableFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" String f() {",
" return Optional.of(\"test\").orElse(\"test2\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" String f() {",
" return Optional.ofNullable(\"test\").orElse(\"test2\");",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void positive_orElse_refactoring_simplifyExpressionFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" String f() {",
" return Optional.of(\"test\").orElse(\"test2\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" String f() {",
" return \"test\";",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void positive_orElseGet() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: orElseGet",
" Optional.of(\"test\").orElseGet(() -> \"test2\");",
" }",
"}")
.doTest();
}
@Test
public void positive_orElseGet_refactoring_ofNullableFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" String f() {",
" return Optional.of(\"test\").orElseGet(() -> \"test2\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" String f() {",
" return Optional.ofNullable(\"test\").orElseGet(() -> \"test2\");",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void positive_orElseGet_refactoring_simplifyExpressionFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" String f() {",
" return Optional.of(\"test\").orElseGet(() -> \"test2\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" String f() {",
" return \"test\";",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void positive_orElseThrow() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"import com.google.common.collect.ImmutableMap;",
"class Test {",
" static String f(ImmutableMap<String,String> map){",
" // BUG: Diagnostic contains: orElseThrow",
" return Optional.of(map.get(\"test\")).orElseThrow(IllegalArgumentException::new);",
" }",
"}")
.doTest();
}
@Test
public void positive_orElseThrow_refactoring_ofNullableFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"import com.google.common.collect.ImmutableMap;",
"class Test {",
" static String f(ImmutableMap<String,String> map){",
" return Optional.of(map.get(\"test\")).orElseThrow(IllegalArgumentException::new);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"import com.google.common.collect.ImmutableMap;",
"class Test {",
" static String f(ImmutableMap<String,String> map){",
" return"
+ " Optional.ofNullable(map.get(\"test\")).orElseThrow(IllegalArgumentException::new);",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void positive_orElseThrow_refactoring_simplifyExpressionFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"import com.google.common.collect.ImmutableMap;",
"class Test {",
" static String f(ImmutableMap<String,String> map){",
" return Optional.of(map.get(\"test\")).orElseThrow(IllegalArgumentException::new);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"import com.google.common.collect.ImmutableMap;",
"class Test {",
" static String f(ImmutableMap<String,String> map){",
" return map.get(\"test\");",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void positive_isPresent() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: isPresent",
" if(Optional.of(\"test\").isPresent()) {}",
" }",
"}")
.doTest();
}
@Test
public void positive_isPresent_refactoring_ofNullableFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" if(Optional.of(\"test\").isPresent()) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" if(Optional.ofNullable(\"test\").isPresent()) {}",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void positive_isPresent_refactoring_simplifyExpressionFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" if(Optional.of(\"test\").isPresent()) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f() {",
" if(true) {}",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void positive_guavaIsPresent() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: isPresent",
" Optional.of(\"test\").isPresent();",
" }",
"}")
.doTest();
}
@Test
public void positive_guavaIsPresent_refactoring_fromNullableFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" Optional.of(\"test\").isPresent();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" Optional.fromNullable(\"test\").isPresent();",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void positive_guavaIsPresent_refactoring_simplifyExpressionFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" if(Optional.of(\"test\").isPresent()){}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" if(true){}",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void positive_guavaOr() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: or",
" Optional.of(\"test\").or(\"\");",
" }",
"}")
.doTest();
}
@Test
public void positive_guavaOr_refactoring_fromNullableFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" Optional.of(\"test\").or(\"\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" Optional.fromNullable(\"test\").or(\"\");",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void positive_guavaOr_refactoring_simplifyExpressionFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" String f() {",
" return Optional.of(\"test\").or(\"\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" String f() {",
" return \"test\";",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void positive_guavaOrNull() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: orNull",
" Optional.of(\"test\").orNull();",
" }",
"}")
.doTest();
}
@Test
public void positive_guavaOrNull_refactoring_fromNullableFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" Optional.of(\"test\").orNull();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" void f() {",
" Optional.fromNullable(\"test\").orNull();",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void positive_guavaOrNull_refactoring_simplifyExpressionFix() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" String f() {",
" return Optional.of(\"test\").orNull();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" String f() {",
" return \"test\";",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void negative_ifPresent() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f(Optional<String> maybeString) {",
" maybeString.ifPresent(String::length);",
" }",
"}")
.doTest();
}
@Test
public void negative_orElse() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f(String value) {",
" Optional.of(value).filter(x -> x.length() < 5).orElse(\"test\");",
" }",
"}")
.doTest();
}
@Test
public void negative_guavaIsPresent() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Optional<String> maybeString) {",
" return maybeString.isPresent();",
" }",
"}")
.doTest();
}
}
| 16,233
| 28.678245
| 104
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MissingRefasterAnnotationTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.common.base.Predicates;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link MissingRefasterAnnotation}. */
@RunWith(JUnit4.class)
public final class MissingRefasterAnnotationTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(MissingRefasterAnnotation.class, getClass())
.expectErrorMessage(
"X",
Predicates.containsPattern(
"The Refaster template contains a method without any Refaster annotations"));
@Test
public void testIdentification() {
compilationTestHelper
.addSourceLines(
"A.java",
"import com.google.errorprone.refaster.annotation.AfterTemplate;",
"import com.google.errorprone.refaster.annotation.AlsoNegation;",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;",
"import java.util.Map;",
"",
"class A {",
" // BUG: Diagnostic matches: X",
" static final class MethodLacksBeforeTemplateAnnotation {",
" @BeforeTemplate",
" boolean before1(String string) {",
" return string.equals(\"\");",
" }",
"",
" // @BeforeTemplate is missing",
" boolean before2(String string) {",
" return string.length() == 0;",
" }",
"",
" @AfterTemplate",
" @AlsoNegation",
" boolean after(String string) {",
" return string.isEmpty();",
" }",
" }",
"",
" // BUG: Diagnostic matches: X",
" static final class MethodLacksAfterTemplateAnnotation {",
" @BeforeTemplate",
" boolean before(String string) {",
" return string.equals(\"\");",
" }",
"",
" // @AfterTemplate is missing",
" boolean after(String string) {",
" return string.isEmpty();",
" }",
" }",
"",
" // BUG: Diagnostic matches: X",
" abstract class MethodLacksPlaceholderAnnotation<K, V> {",
" // @Placeholder is missing",
" abstract V function(K key);",
"",
" @BeforeTemplate",
" void before(Map<K, V> map, K key) {",
" if (!map.containsKey(key)) {",
" map.put(key, function(key));",
" }",
" }",
"",
" @AfterTemplate",
" void after(Map<K, V> map, K key) {",
" map.computeIfAbsent(key, k -> function(k));",
" }",
" }",
"",
" static final class ValidRefasterTemplate {",
" @BeforeTemplate",
" void unusedPureFunctionCall(Object o) {",
" o.toString();",
" }",
" }",
"",
" static final class NotARefasterTemplate {",
" @Override",
" public String toString() {",
" return \"This is not a Refaster template\";",
" }",
" }",
"}")
.doTest();
}
}
| 4,141
| 35.654867
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NonCanonicalStaticMemberImportTest.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link NonCanonicalStaticMemberImport}Test */
@RunWith(JUnit4.class)
public class NonCanonicalStaticMemberImportTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NonCanonicalStaticMemberImport.class, getClass());
@Test
public void positiveMethod() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"public class A {",
" public static final int foo() { return 42; }",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {",
"}")
.addSourceLines(
"b/Test.java",
"package b;",
"// BUG: Diagnostic contains: import static a.A.foo;",
"import static b.B.foo;",
"class Test {}")
.doTest();
}
@Test
public void positiveField() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"public class A {",
" public static final int CONST = 42;",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {",
"}")
.addSourceLines(
"b/Test.java",
"package b;",
"// BUG: Diagnostic contains: import static a.A.CONST;",
"import static b.B.CONST;",
"class Test {}")
.doTest();
}
// We can't test e.g. a.B.Inner.CONST (a double non-canonical reference), because
// they're illegal.
@Test
public void positiveClassAndField() {
compilationHelper
.addSourceLines(
"a/Super.java",
"package a;",
"public class Super {",
" public static final int CONST = 42;",
"}")
.addSourceLines(
"a/A.java",
"package a;",
"public class A {",
" public static class Inner extends Super {}",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {",
"}")
.addSourceLines(
"b/Test.java",
"package b;",
"// BUG: Diagnostic contains: import static a.Super.CONST;",
"import static a.A.Inner.CONST;",
"class Test {}")
.doTest();
}
@Test
public void negativeMethod() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"public class A {",
" public static final int foo() { return 42; }",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {",
"}")
.addSourceLines(
"b/Test.java", //
"package b;",
"import static a.A.foo;",
"class Test {}")
.doTest();
}
@Test
public void negativeField() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"public class A {",
" public static final int CONST = 42;",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {",
"}")
.addSourceLines(
"b/Test.java", //
"package b;",
"import static a.A.CONST;",
"class Test {}")
.doTest();
}
@Test
public void negativeClassAndField() {
compilationHelper
.addSourceLines(
"a/Super.java",
"package a;",
"public class Super {",
" public static final int CONST = 42;",
"}")
.addSourceLines(
"a/A.java",
"package a;",
"public class A {",
" public static class Inner extends Super {}",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {",
"}")
.addSourceLines(
"b/Test.java", //
"package b;",
"import static a.Super.CONST;",
"class Test {}")
.doTest();
}
}
| 5,263
| 27.454054
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MultipleUnaryOperatorsInMethodCallTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author sulku@google.com (Marsela Sulku)
*/
@RunWith(JUnit4.class)
public class MultipleUnaryOperatorsInMethodCallTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(MultipleUnaryOperatorsInMethodCall.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceFile("MultipleUnaryOperatorsInMethodCallPositiveCases.java")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceFile("MultipleUnaryOperatorsInMethodCallNegativeCases.java")
.doTest();
}
}
| 1,406
| 30.266667
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/VarTypeNameTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link VarTypeName}Test */
@RunWith(JUnit4.class)
public class VarTypeNameTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(VarTypeName.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java", //
"// BUG: Diagnostic contains:",
"class Test<var> {",
"// BUG: Diagnostic contains:",
" class var {}",
"// BUG: Diagnostic contains:",
" public <var> void foo(var foo) {}",
"}")
.setArgs(ImmutableList.of("-source", "8", "-target", "8"))
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" int var;",
"}")
.setArgs(ImmutableList.of("-source", "8", "-target", "8"))
.doTest();
}
}
| 1,776
| 28.616667
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilderTest.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class UnnecessaryStringBuilderTest {
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryStringBuilder.class, getClass());
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(UnnecessaryStringBuilder.class, getClass());
@Test
public void positive() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" void f(String hello) {",
" System.err.println(new StringBuilder().append(hello).append(\"world\"));",
" System.err.println(new StringBuilder(hello).append(\"world\"));",
" System.err.println(new StringBuilder(10).append(hello).append(\"world\"));",
" System.err.println(new StringBuilder(hello).append(\"world\").toString());",
" System.err.println(new StringBuilder().toString());",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" void f(String hello) {",
" System.err.println(hello + \"world\");",
" System.err.println(hello + \"world\");",
" System.err.println(hello + \"world\");",
" System.err.println(hello + \"world\");",
" System.err.println(\"\");",
" }",
"}")
.doTest();
}
@Test
public void variable() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" void f(String hello) {",
" String a = new StringBuilder().append(hello).append(\"world\").toString();",
" StringBuilder b = new StringBuilder().append(hello).append(\"world\");",
" StringBuilder c = new StringBuilder().append(hello).append(\"world\");",
" System.err.println(b);",
" System.err.println(b + \"\");",
" System.err.println(c);",
" c.append(\"goodbye\");",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" void f(String hello) {",
" String a = hello + \"world\";",
" String b = hello + \"world\";",
" StringBuilder c = new StringBuilder().append(hello).append(\"world\");",
" System.err.println(b);",
" System.err.println(b + \"\");",
" System.err.println(c);",
" c.append(\"goodbye\");",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f(Iterable<String> xs) {",
" StringBuilder sb = new StringBuilder();",
" for (String s : xs) {",
" sb.append(s);",
" }",
" System.err.println(sb);",
" }",
"}")
.doTest();
}
@Test
public void negativeMethodReference() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f(Iterable<String> xs) {",
" StringBuilder sb = new StringBuilder();",
" xs.forEach(sb::append);",
" System.err.println(sb);",
" }",
"}")
.doTest();
}
@Test
public void needsParens() {
refactoringHelper
.addInputLines(
"Test.java",
"abstract class Test {",
" abstract void g(String x);",
" void f(boolean b, String hello) {",
" g(new StringBuilder().append(b ? hello : \"\").append(\"world\").toString());",
" }",
"}")
.addOutputLines(
"Test.java",
"abstract class Test {",
" abstract void g(String x);",
" void f(boolean b, String hello) {",
" g((b ? hello : \"\") + \"world\");",
" }",
"}")
.doTest();
}
@Test
public void varType() {
refactoringHelper
.addInputLines(
"Test.java",
"abstract class Test {",
" void f() {",
" var sb = new StringBuilder().append(\"hello\");",
" System.err.println(sb);",
" }",
"}")
.addOutputLines(
"Test.java",
"abstract class Test {",
" void f() {",
" var sb = \"hello\";",
" System.err.println(sb);",
" }",
"}")
.doTest();
}
}
| 5,596
| 32.315476
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CheckReturnValueTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Joiner;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit4.class)
public class CheckReturnValueTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(CheckReturnValue.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(CheckReturnValue.class, getClass());
@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void positiveCases() {
compilationHelper.addSourceFile("CheckReturnValuePositiveCases.java").doTest();
}
@Test
public void customCheckReturnValueAnnotation() {
compilationHelper
.addSourceLines(
"foo/bar/CheckReturnValue.java",
"package foo.bar;",
"public @interface CheckReturnValue {}")
.addSourceLines(
"test/TestCustomCheckReturnValueAnnotation.java",
"package test;",
"import foo.bar.CheckReturnValue;",
"public class TestCustomCheckReturnValueAnnotation {",
" @CheckReturnValue",
" public String getString() {",
" return \"string\";",
" }",
" public void doIt() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" getString();",
" }",
"}")
.doTest();
}
@Test
public void customCanIgnoreReturnValueAnnotation() {
compilationHelper
.addSourceLines(
"foo/bar/CanIgnoreReturnValue.java",
"package foo.bar;",
"public @interface CanIgnoreReturnValue {}")
.addSourceLines(
"test/TestCustomCanIgnoreReturnValueAnnotation.java",
"package test;",
"import foo.bar.CanIgnoreReturnValue;",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class TestCustomCanIgnoreReturnValueAnnotation {",
" @CanIgnoreReturnValue",
" public String ignored() {",
" return null;",
" }",
" public void doIt() {",
" ignored();",
" }",
"}")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("CheckReturnValueNegativeCases.java").doTest();
}
@Test
public void packageAnnotation() {
compilationHelper
.addSourceLines(
"package-info.java", //
"@com.google.errorprone.annotations.CheckReturnValue",
"package lib;")
.addSourceLines(
"lib/Lib.java",
"package lib;",
"public class Lib {",
" public static int f() { return 42; }",
"}")
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" lib.Lib.f();",
" }",
"}")
.doTest();
}
@Test
public void classAnnotation() {
compilationHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Lib {",
" public static int f() { return 42; }",
"}")
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" lib.Lib.f();",
" }",
"}")
.doTest();
}
// Don't match void-returning methods in packages with @CRV
@Test
public void voidReturningMethodInAnnotatedPackage() {
compilationHelper
.addSourceLines(
"package-info.java", //
"@com.google.errorprone.annotations.CheckReturnValue",
"package lib;")
.addSourceLines(
"lib/Lib.java",
"package lib;",
"public class Lib {",
" public static void f() {}",
"}")
.addSourceLines(
"Test.java", //
"class Test {",
" void m() {",
" lib.Lib.f();",
" }",
"}")
.doTest();
}
@Test
public void badCRVOnProcedure() {
compilationHelper
.addSourceLines(
"Test.java",
"package lib;",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Test {",
" // BUG: Diagnostic contains: CheckReturnValue",
" // @CheckReturnValue may not be applied to void-returning methods",
" @com.google.errorprone.annotations.CheckReturnValue public static void f() {}",
"}")
.doTest();
}
@Test
public void badCRVOnPseudoProcedure() {
compilationHelper
.addSourceLines(
"Test.java",
"package lib;",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Test {",
" // BUG: Diagnostic contains: CheckReturnValue",
" // @CheckReturnValue may not be applied to void-returning methods",
" @com.google.errorprone.annotations.CheckReturnValue public static Void f() {",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void packageAnnotationButCanIgnoreReturnValue() {
compilationHelper
.addSourceLines(
"package-info.java",
"@com.google.errorprone.annotations.CheckReturnValue",
"package lib;")
.addSourceLines(
"lib/Lib.java",
"package lib;",
"public class Lib {",
" @com.google.errorprone.annotations.CanIgnoreReturnValue",
" public static int f() { return 42; }",
"}")
.addSourceLines(
"Test.java", //
"class Test {",
" void m() {",
" lib.Lib.f();",
" }",
"}")
.doTest();
}
@Test
public void classAnnotationButCanIgnoreReturnValue() {
compilationHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Lib {",
" @com.google.errorprone.annotations.CanIgnoreReturnValue",
" public static int f() { return 42; }",
"}")
.addSourceLines(
"Test.java", //
"class Test {",
" void m() {",
" lib.Lib.f();",
" }",
"}")
.doTest();
}
@Test
public void badCanIgnoreReturnValueOnProcedure() {
compilationHelper
.addSourceLines(
"Test.java",
"package lib;",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Test {",
" // BUG: Diagnostic contains: CheckReturnValue",
" // @CanIgnoreReturnValue may not be applied to void-returning methods",
" @com.google.errorprone.annotations.CanIgnoreReturnValue public static void f() {}",
"}")
.doTest();
}
@Test
public void nestedClassAnnotation() {
compilationHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Lib {",
" public static class Inner {",
" public static class InnerMost {",
" public static int f() { return 42; }",
" }",
" }",
"}")
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" lib.Lib.Inner.InnerMost.f();",
" }",
"}")
.doTest();
}
@Test
public void nestedClassWithCanIgnoreAnnotation() {
compilationHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Lib {",
" @com.google.errorprone.annotations.CanIgnoreReturnValue",
" public static class Inner {",
" public static class InnerMost {",
" public static int f() { return 42; }",
" }",
" }",
"}")
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" lib.Lib.Inner.InnerMost.f();",
" }",
"}")
.doTest();
}
@Test
public void packageWithCanIgnoreAnnotation() {
compilationHelper
.addSourceLines(
"package-info.java",
"@com.google.errorprone.annotations.CheckReturnValue",
"package lib;")
.addSourceLines(
"lib/Lib.java",
"package lib;",
"@com.google.errorprone.annotations.CanIgnoreReturnValue",
"public class Lib {",
" public static int f() { return 42; }",
"}")
.addSourceLines(
"Test.java", //
"class Test {",
" void m() {",
" lib.Lib.f();",
" }",
"}")
.doTest();
}
@Test
public void errorBothClass() {
compilationHelper
.addSourceLines(
"Test.java",
"@com.google.errorprone.annotations.CanIgnoreReturnValue",
"@com.google.errorprone.annotations.CheckReturnValue",
"// BUG: Diagnostic contains: @CheckReturnValue and @CanIgnoreReturnValue cannot"
+ " be applied to the same class",
"class Test {}")
.doTest();
}
@Test
public void errorBothMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" @com.google.errorprone.annotations.CanIgnoreReturnValue",
" @com.google.errorprone.annotations.CheckReturnValue",
" // BUG: Diagnostic contains: @CheckReturnValue and @CanIgnoreReturnValue cannot"
+ " be applied to the same method",
" void m() {}",
"}")
.doTest();
}
// Don't match Void-returning methods in packages with @CRV
@Test
public void javaLangVoidReturningMethodInAnnotatedPackage() {
compilationHelper
.addSourceLines(
"package-info.java",
"@com.google.errorprone.annotations.CheckReturnValue",
"package lib;")
.addSourceLines(
"lib/Lib.java",
"package lib;",
"public class Lib {",
" public static Void f() {",
" return null;",
" }",
"}")
.addSourceLines(
"Test.java", //
"class Test {",
" void m() {",
" lib.Lib.f();",
" }",
"}")
.doTest();
}
@Test
public void ignoreVoidReturningMethodReferences() {
compilationHelper
.addSourceLines(
"Lib.java",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Lib {",
" public static void consume(Object o) {}",
"}")
.addSourceLines(
"Test.java",
"class Test {",
" void m(java.util.List<Object> xs) {",
" xs.forEach(Lib::consume);",
" }",
"}")
.doTest();
}
/** Test class containing a method annotated with @CRV. */
public static final class CRVTest {
@com.google.errorprone.annotations.CheckReturnValue
public static int f() {
return 42;
}
private CRVTest() {}
}
@Test
public void noCRVonClasspath() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" com.google.errorprone.bugpatterns.CheckReturnValueTest.CRVTest.f();",
" }",
"}")
.withClasspath(CRVTest.class, CheckReturnValueTest.class)
.doTest();
}
@Test
public void constructor() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" @com.google.errorprone.annotations.CheckReturnValue",
" public Test() {}",
" public static void foo() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" new Test();",
" }",
"}")
.doTest();
}
@Test
public void constructor_telescoping() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" @com.google.errorprone.annotations.CheckReturnValue",
" public Test() {}",
" public Test(int foo) { this(); }",
" public static void foo() {",
" Test foo = new Test(42);",
" }",
"}")
.doTest();
}
@Test
public void constructor_superCall() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" @com.google.errorprone.annotations.CheckReturnValue",
" public Test() {}",
" static class SubTest extends Test { SubTest() { super(); } }",
" public static void foo() {",
" Test derived = new SubTest();",
" }",
"}")
.doTest();
}
@Test
public void constructor_anonymousClassInheritsCIRV() {
compilationHelperLookingAtAllConstructors()
.addSourceLines(
"Test.java",
"class Test {",
" @com.google.errorprone.annotations.CanIgnoreReturnValue",
" public Test() {}",
" public static void foo() {",
" new Test() {};",
" new Test() {{ System.out.println(\"Lookie, instance initializer\"); }};",
" }",
"}")
.doTest();
}
@Test
public void constructor_anonymousClassInheritsCRV() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" @com.google.errorprone.annotations.CheckReturnValue",
" public Test() {}",
" public static void foo() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" new Test() {};",
" }",
"}")
.doTest();
}
@Test
public void constructor_hasOuterInstance() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" class Inner {",
" @com.google.errorprone.annotations.CheckReturnValue",
" public Inner() {}",
" }",
" public static void foo() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" new Test().new Inner() {};",
" }",
"}")
.doTest();
}
@Test
public void constructor_anonymousClassInheritsCRV_syntheticConstructor() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" @com.google.errorprone.annotations.CheckReturnValue",
" static class Nested {}",
" public static void foo() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" new Nested() {};", // The "called" constructor is synthetic, but within @CRV Nested
" }",
"}")
.doTest();
}
@Test
public void constructor_inheritsFromCrvInterface() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" @com.google.errorprone.annotations.CheckReturnValue",
" static interface IFace {}",
" public static void foo() {",
// TODO(b/226203690): It's arguable that this might need to be @CRV?
// The superclass of the anonymous class is Object, not IFace, but /shrug
" new IFace() {};",
" }",
"}")
.doTest();
}
@Test
public void constructor_throwingContexts() {
compilationHelper
.addSourceLines(
"Foo.java",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Foo {}")
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" try {",
" new Foo();",
" org.junit.Assert.fail();",
" } catch (Exception expected) {}",
" org.junit.Assert.assertThrows(IllegalArgumentException.class, () -> new Foo());",
" }",
"}")
.doTest();
}
@Test
public void constructor_reference() {
compilationHelper
.addSourceLines(
"Foo.java",
"@com.google.errorprone.annotations.CheckReturnValue",
"public class Foo {}")
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" Runnable ignoresResult = Foo::new;",
" }",
"}")
.doTest();
}
@Test
public void constructor_withoutCrvAnnotation() {
compilationHelperLookingAtAllConstructors()
.addSourceLines(
"Test.java",
"class Test {",
" public Test() {}",
" public static void foo() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" new Test();",
" }",
"}")
.doTest();
}
@Test
public void allMethods_withoutCIRVAnnotation() {
compilationHelperLookingAtAllMethods()
.addSourceLines(
"Test.java",
"class Test {",
" public int bar() { return 42; }",
" public static void foo() {",
" // BUG: Diagnostic contains: CheckReturnValue",
" new Test().bar();",
" }",
"}")
.doTest();
}
// In the following test methods, we define parallel skeletons of classes like java.util.List,
// because the real java.util.List may have had @CanIgnoreReturnValue annotations inserted.
@Test
public void allMethods_withExternallyConfiguredIgnoreList() {
compileWithExternalApis("my.java.util.List#add(java.lang.Object)")
.addSourceLines(
"Test.java",
"import my.java.util.List;",
"class Test {",
" public static void foo(List<Integer> x) {",
" x.add(42);",
" // BUG: Diagnostic contains: CheckReturnValue",
" x.get(0);",
" }",
"}")
.addSourceLines(
"my/java/util/List.java",
"package my.java.util;",
"public interface List<E> {",
" boolean add(E e);",
" E get(int index);",
"}")
.doTest();
}
@Test
public void packagesRule() {
compilationHelperWithPackagePatterns("my.java.util")
.addSourceLines(
"Test.java",
"import my.java.util.List;",
"import my.java.util.regex.Pattern;",
"class Test {",
" public static void foo(List<Integer> list, Pattern pattern) {",
" // BUG: Diagnostic contains: CheckReturnValue",
" list.get(0);",
" // BUG: Diagnostic contains: CheckReturnValue",
" pattern.matcher(\"blah\");",
" }",
"}")
.addSourceLines(
"my/java/util/List.java",
"package my.java.util;",
"public interface List<E> {",
" E get(int index);",
"}")
.addSourceLines(
"my/java/util/regex/Pattern.java",
"package my.java.util.regex;",
"public interface Pattern {",
" String matcher(CharSequence input);",
"}")
.doTest();
}
@Test
public void packagesRule_negativePattern() {
compilationHelperWithPackagePatterns("my.java.util", "-my.java.util.regex")
.addSourceLines(
"Test.java",
"import my.java.util.List;",
"import my.java.util.regex.Pattern;",
"class Test {",
" public static void foo(List<Integer> list, Pattern pattern) {",
" // BUG: Diagnostic contains: CheckReturnValue",
" list.get(0);",
" pattern.matcher(\"blah\");",
" }",
"}")
.addSourceLines(
"my/java/util/List.java",
"package my.java.util;",
"public interface List<E> {",
" E get(int index);",
"}")
.addSourceLines(
"my/java/util/regex/Pattern.java",
"package my.java.util.regex;",
"public interface Pattern {",
" String matcher(CharSequence input);",
"}")
.doTest();
}
@Test
public void packagesRule_negativePattern_doesNotMakeOptional() {
// A negative pattern just makes the packages rule itself not apply to that package and its
// subpackages if it otherwise would because of a positive pattern on a superpackage. It doesn't
// make APIs in that package CIRV.
compilationHelperWithPackagePatterns("my.java.util", "-my.java.util.regex")
.addSourceLines(
"Test.java",
"import my.java.util.List;",
"import my.java.util.regex.Pattern;",
"import my.java.util.regex.PatternSyntaxException;",
"class Test {",
" public static void foo(List<Integer> list, Pattern pattern) {",
" // BUG: Diagnostic contains: CheckReturnValue",
" list.get(0);",
" pattern.matcher(\"blah\");",
" // BUG: Diagnostic contains: CheckReturnValue",
" new PatternSyntaxException(\"\", \"\", 0);",
" }",
"}")
.addSourceLines(
"my/java/util/List.java",
"package my.java.util;",
"public interface List<E> {",
" E get(int index);",
"}")
.addSourceLines(
"my/java/util/regex/Pattern.java",
"package my.java.util.regex;",
"public interface Pattern {",
" String matcher(CharSequence input);",
"}")
.addSourceLines(
"my/java/util/regex/PatternSyntaxException.java",
"package my.java.util.regex;",
"public class PatternSyntaxException extends IllegalArgumentException {",
" public PatternSyntaxException(String desc, String regex, int index) {}",
"}")
.doTest();
}
@Test
public void refactoringAssignsToOriginalBasedOnSubstitutedTypes() {
refactoringHelper
.addInputLines(
"Builder.java",
"@com.google.errorprone.annotations.CheckReturnValue",
"interface Builder<B extends Builder<B>> {",
" B setFoo(String s);",
"}")
.expectUnchanged()
.addInputLines(
"SomeBuilder.java", //
"interface SomeBuilder extends Builder<SomeBuilder> {}")
.expectUnchanged()
.addInputLines(
"Test.java",
"class Test {",
" void f(SomeBuilder builder, String s) {",
" builder.setFoo(s);",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" void f(SomeBuilder builder, String s) {",
" builder = builder.setFoo(s);",
" }",
"}")
.doTest();
}
@Test
public void suggestCanIgnoreReturnValueForMethodInvocation() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"class Test {",
" void foo() {",
" makeBarOrThrow();",
" }",
" String makeBarOrThrow() {",
" throw new UnsupportedOperationException();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.annotations.CanIgnoreReturnValue;",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"class Test {",
" void foo() {",
" makeBarOrThrow();",
" }",
" @CanIgnoreReturnValue",
" String makeBarOrThrow() {",
" throw new UnsupportedOperationException();",
" }",
"}")
.doTest();
}
@Test
public void suggestCanIgnoreReturnValueForMethodReference() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"class Test {",
" Runnable r = this::makeBarOrThrow;",
" String makeBarOrThrow() {",
" throw new UnsupportedOperationException();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.annotations.CanIgnoreReturnValue;",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"class Test {",
" Runnable r = this::makeBarOrThrow;",
" @CanIgnoreReturnValue",
" String makeBarOrThrow() {",
" throw new UnsupportedOperationException();",
" }",
"}")
.doTest();
}
@Test
public void suggestCanIgnoreReturnValueForConstructor() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"class Test {",
" Test() {}",
" void run() {",
" new Test();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.annotations.CanIgnoreReturnValue;",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"class Test {",
" @CanIgnoreReturnValue",
" Test() {}",
" void run() {",
" new Test();",
" }",
"}")
.doTest();
}
@Test
public void suggestCanIgnoreReturnValueAndRemoveCheckReturnValue() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.annotations.CheckReturnValue;",
"class Test {",
" void foo() {",
" makeBarOrThrow();",
" }",
" @CheckReturnValue",
" String makeBarOrThrow() {",
" throw new UnsupportedOperationException();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.annotations.CanIgnoreReturnValue;",
"import com.google.errorprone.annotations.CheckReturnValue;",
"class Test {",
" void foo() {",
" makeBarOrThrow();",
" }",
" @CanIgnoreReturnValue",
" String makeBarOrThrow() {",
" throw new UnsupportedOperationException();",
" }",
"}")
.doTest();
}
@Test
public void doesNotSuggestCanIgnoreReturnValueForOtherFile() {
refactoringHelper
.addInputLines(
"Lib.java",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"class Lib {",
" String makeBarOrThrow() {",
" throw new UnsupportedOperationException();",
" }",
"}")
.expectUnchanged()
.addInputLines(
"Test.java",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"class Test {",
" void foo(Lib l) {",
" l.makeBarOrThrow();",
" }",
"}")
// The checker doesn't suggest CIRV, so it applies a different fix instead.
.addOutputLines(
"Test.java",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"class Test {",
" void foo(Lib l) {",
" var unused = l.makeBarOrThrow();",
" }",
"}")
.doTest();
}
@Test
public void suggestsVarUnusedForConstructor() {
refactoringHelper
.addInputLines(
"Test.java",
"@com.google.errorprone.annotations.CheckReturnValue",
"class Test {",
" void go() {",
" new Test();",
" }",
"}")
.addOutputLines(
"Test.java",
"@com.google.errorprone.annotations.CheckReturnValue",
"class Test {",
" void go() {",
" var unused = new Test();",
" }",
"}")
.doTest();
}
@Test
public void suggestsVarUnused2() {
refactoringHelper
.addInputLines(
"Lib.java",
"import com.google.errorprone.annotations.CheckReturnValue;",
"@CheckReturnValue",
"interface Lib {",
" int a();",
" int b();",
"}")
.expectUnchanged()
.addInputLines(
"Test.java",
"class Test {",
" void foo(Lib lib) {",
" var unused = lib.a();",
" lib.b();",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" void foo(Lib lib) {",
" var unused = lib.a();",
" var unused2 = lib.b();",
" }",
"}")
.doTest();
}
private CompilationTestHelper compilationHelperLookingAtAllConstructors() {
return compilationHelper.setArgs(
"-XepOpt:" + CheckReturnValue.CHECK_ALL_CONSTRUCTORS + "=true");
}
private CompilationTestHelper compilationHelperLookingAtAllMethods() {
return compilationHelper.setArgs("-XepOpt:" + CheckReturnValue.CHECK_ALL_METHODS + "=true");
}
private CompilationTestHelper compileWithExternalApis(String... apis) {
try {
Path file = temporaryFolder.newFile().toPath();
Files.writeString(file, Joiner.on('\n').join(apis), UTF_8);
return compilationHelper.setArgs(
"-XepOpt:" + CheckReturnValue.CHECK_ALL_METHODS + "=true",
"-XepOpt:CheckReturnValue:ApiExclusionList=" + file);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private CompilationTestHelper compilationHelperWithPackagePatterns(String... patterns) {
return compilationHelper.setArgs(
"-XepOpt:" + CheckReturnValue.CRV_PACKAGES + "=" + Joiner.on(',').join(patterns),
"-XepOpt:" + CheckReturnValue.CHECK_ALL_CONSTRUCTORS + "=true");
}
}
| 32,910
| 30.921435
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InterruptionTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link Interruption}Test */
@RunWith(JUnit4.class)
public class InterruptionTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(Interruption.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.Future;",
"class Test {",
" void f(Future<?> f, boolean b) {",
" // BUG: Diagnostic contains: f.cancel(false)",
" f.cancel(true);",
" // BUG: Diagnostic contains: f.cancel(false)",
" f.cancel(b);",
" }",
"}")
.doTest();
}
@Test
public void positiveClosingFuture() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.util.concurrent.ClosingFuture;",
"class Test {",
" void f(ClosingFuture<?> f) {",
" // BUG: Diagnostic contains: f.cancel(false)",
" f.cancel(true);",
" }",
"}")
.doTest();
}
@Test
public void positiveInterrupt() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" void f(Thread t) {",
" // BUG: Diagnostic contains:",
" t.interrupt();",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.Future;",
"class Test {",
" void f(Future<?> f) {",
" f.cancel(false);",
" }",
"}")
.doTest();
}
@Test
public void negativeWasInterrupted() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.util.concurrent.AbstractFuture;",
"class Test extends AbstractFuture<Object> {",
" void f() {",
" cancel(wasInterrupted());",
" }",
"}")
.doTest();
}
@Test
public void negativeDelegate() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.util.concurrent.AbstractFuture;",
"import java.util.concurrent.Future;",
"class Test extends AbstractFuture<Object> {",
" void f(Future<?> f) {",
" new AbstractFuture<Object>() {",
" @Override",
" public boolean cancel(boolean mayInterruptIfRunning) {",
" return f.cancel(mayInterruptIfRunning);",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void negativeInterrupt() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f(Thread t) {",
" Thread.currentThread().interrupt();",
" }",
"}")
.doTest();
}
@Test
public void negativeInTestonlyCode() {
compilationHelper
.addSourceLines(
"Test.java",
"import org.junit.Test;",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"import java.util.concurrent.Future;",
"@RunWith(JUnit4.class)",
"class FutureTest {",
" Future<?> f;",
" @Test",
" public void t() {",
" f.cancel(true);",
" }",
"}")
.setArgs("-XepCompilingTestOnlyCode")
.doTest();
}
}
| 4,525
| 27.465409
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CanonicalDurationTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link CanonicalDuration}Test */
@RunWith(JUnit4.class)
public class CanonicalDurationTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(CanonicalDuration.class, getClass());
@Test
public void refactoringJavaTime() {
helper
.addInputLines(
"in/A.java", //
"package a;",
"import java.time.Duration;",
"public class A {",
" static final int CONST = 86400;",
" {",
" Duration.ofSeconds(86400);",
" java.time.Duration.ofSeconds(86400);",
" Duration.ofSeconds(CONST);",
" Duration.ofMillis(0);",
" Duration.ofMillis(4611686018427387904L);",
" Duration.ofDays(1);",
" }",
"}")
.addOutputLines(
"out/A.java", //
"package a;",
"import java.time.Duration;",
"public class A {",
" static final int CONST = 86400;",
" {",
" Duration.ofDays(1);",
" java.time.Duration.ofDays(1);",
" Duration.ofSeconds(CONST);",
" Duration.ofMillis(0);",
" Duration.ofMillis(4611686018427387904L);",
" Duration.ofDays(1);",
" }",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void refactoringJoda() {
helper
.addInputLines(
"in/A.java", //
"package a;",
"import org.joda.time.Duration;",
"public class A {",
" static final int CONST = 86400;",
" {",
" Duration.standardSeconds(86400);",
" org.joda.time.Duration.standardSeconds(86400);",
" Duration.standardSeconds(CONST);",
" Duration zero = Duration.standardSeconds(0);",
" Duration.standardDays(1);",
" }",
"}")
.addOutputLines(
"out/A.java", //
"package a;",
"import org.joda.time.Duration;",
"public class A {",
" static final int CONST = 86400;",
" {",
" Duration.standardDays(1);",
" org.joda.time.Duration.standardDays(1);",
" Duration.standardSeconds(CONST);",
" Duration zero = Duration.ZERO;",
" Duration.standardDays(1);",
" }",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void refactoringJavaTimeStaticImport() {
helper
.addInputLines(
"in/A.java", //
"package a;",
"import static java.time.Duration.ofSeconds;",
"import java.time.Duration;",
"public class A {",
" {",
" ofSeconds(86400);",
" }",
"}")
.addOutputLines(
"out/A.java", //
"package a;",
"",
"import static java.time.Duration.ofDays;",
"import static java.time.Duration.ofSeconds;",
"",
"import java.time.Duration;",
"",
"public class A {",
" {",
" ofDays(1);",
" }",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void refactoringJodaStaticImport() {
helper
.addInputLines(
"in/A.java", //
"package a;",
"import static org.joda.time.Duration.standardSeconds;",
"public class A {",
" {",
" standardSeconds(86400);",
" standardSeconds(0).getStandardSeconds();",
" }",
"}")
.addOutputLines(
"out/A.java", //
"package a;",
"import static org.joda.time.Duration.standardDays;",
"import static org.joda.time.Duration.standardSeconds;",
"",
"import org.joda.time.Duration;",
"public class A {",
" {",
" standardDays(1);",
" Duration.ZERO.getStandardSeconds();",
" }",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void ignoredMethod() {
helper
.addInputLines(
"A.java",
"package a;",
"import java.time.Duration;",
"public class A {",
" static final int S = 60;",
" static final int M = 60;",
" static final int H = 24;",
" {",
" Duration.ofSeconds(S);",
" Duration.ofMinutes(H);",
" Duration.ofHours(24);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void consistentWithinExpression() {
helper
.addInputLines(
"A.java",
"package a;",
"import static java.time.Duration.ofSeconds;",
"import static java.util.Arrays.asList;",
"import java.time.Duration;",
"import java.util.List;",
"public class A {",
" // The 120 is left alone here because 121 can't be converted too.",
" static final List<Duration> negative = asList(ofSeconds(120), ofSeconds(121));",
"",
" static final List<Duration> positive = asList(ofSeconds(120), ofSeconds(180));",
"}")
.addOutputLines(
"A.java",
"package a;",
"import static java.time.Duration.ofMinutes;",
"import static java.time.Duration.ofSeconds;",
"import static java.util.Arrays.asList;",
"import java.time.Duration;",
"import java.util.List;",
"public class A {",
" // The 120 is left alone here because 121 can't be converted too.",
" static final List<Duration> negative = asList(ofSeconds(120), ofSeconds(121));",
"",
" static final List<Duration> positive = asList(ofMinutes(2), ofMinutes(3));",
"}")
.doTest();
}
@Test
public void fixConstantExpressions() {
helper
.addInputLines(
"A.java",
"package a;",
"import static java.time.Duration.ofSeconds;",
"import java.time.Duration;",
"public class A {",
" static final Duration positive = ofSeconds(2 * 60);",
"}")
.addOutputLines(
"A.java",
"package a;",
"import static java.time.Duration.ofMinutes;",
"import static java.time.Duration.ofSeconds;",
"import java.time.Duration;",
"public class A {",
" static final Duration positive = ofMinutes(2);",
"}")
.doTest();
}
}
| 7,774
| 31.531381
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnit3TestNotRunTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author rburny@google.com (Radoslaw Burny)
*/
@RunWith(JUnit4.class)
public class JUnit3TestNotRunTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JUnit3TestNotRun.class, getClass());
private final BugCheckerRefactoringTestHelper refactorHelper =
BugCheckerRefactoringTestHelper.newInstance(JUnit3TestNotRun.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("JUnit3TestNotRunPositiveCases.java").doTest();
}
@Test
public void misspelledTest() {
refactorHelper
.addInputLines(
"in/PositiveCases.java",
"import junit.framework.TestCase;",
"import org.junit.Test;",
"public class PositiveCases extends TestCase {",
" public void tesName1() {}",
" public void ttestName2() {}",
" public void teestName3() {}",
" public void tstName4() {}",
" public void tetName5() {}",
" public void etstName6() {}",
" public void tsetName7() {}",
" public void teatName8() {}",
" public void TestName9() {}",
" public void TEST_NAME_10() {}",
" public void tesname11() {}",
"}")
.addOutputLines(
"out/PositiveCases.java",
"import junit.framework.TestCase;",
"import org.junit.Test;",
"public class PositiveCases extends TestCase {",
" public void testName1() {}",
" public void testName2() {}",
" public void testName3() {}",
" public void testName4() {}",
" public void testName5() {}",
" public void testName6() {}",
" public void testName7() {}",
" public void testName8() {}",
" public void testName9() {}",
" public void test_NAME_10() {}",
" public void testname11() {}",
"}")
.doTest();
}
@Test
public void substitutionShouldBeWellFormed() {
refactorHelper
.addInputLines(
"in/PositiveCases.java",
"import junit.framework.TestCase;",
"import org.junit.Test;",
"public class PositiveCases extends TestCase {",
" public void tesBasic() {}",
" public void tesMoreSpaces( ) {}",
" public void",
" tesMultiline() {}",
"}")
.addOutputLines(
"out/PositiveCases.java",
"import junit.framework.TestCase;",
"import org.junit.Test;",
"public class PositiveCases extends TestCase {",
" public void testBasic() {}",
" public void testMoreSpaces() {}",
" public void testMultiline() {}",
"}")
.doTest();
}
@Test
public void privateNamedTest() {
compilationHelper
.addSourceLines(
"Test.java",
"import junit.framework.TestCase;",
"public class Test extends TestCase {",
" // BUG: Diagnostic contains:",
" private void testDoesStuff() {}",
"}")
.doTest();
}
@Test
public void privateMisspelledTest() {
compilationHelper
.addSourceLines(
"Test.java",
"import junit.framework.TestCase;",
"public class Test extends TestCase {",
" // BUG: Diagnostic contains:",
" private void tsetDoesStuff() {}",
"}")
.doTest();
}
@Test
public void hasModifiersAndThrows() {
refactorHelper
.addInputLines(
"in/DoesStuffTest.java",
"import junit.framework.TestCase;",
"import org.junit.Test;",
"public class DoesStuffTest extends TestCase {",
" private static void tsetDoesStuff() throws Exception {}",
"}")
.addOutputLines(
"out/DoesStuffTest.java",
"import junit.framework.TestCase;",
"import org.junit.Test;",
"public class DoesStuffTest extends TestCase {",
" public void testDoesStuff() throws Exception {}",
"}")
.doTest();
}
@Test
public void hasParameters_butOtherwiseLooksLikeATestMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"import junit.framework.TestCase;",
"public class Test extends TestCase {",
" // BUG: Diagnostic contains:",
" public void testDoesStuff(boolean param) {}",
"}")
.doTest();
}
@Test
public void suppressionWorks() {
compilationHelper
.addSourceLines(
"Test.java",
"import junit.framework.TestCase;",
"public class Test extends TestCase {",
" @SuppressWarnings(\"JUnit3TestNotRun\")",
" public void testDoesStuff(boolean param) {}",
"}")
.doTest();
}
@Test
public void hasParameters_butInABaseClass() {
compilationHelper
.addSourceLines(
"TestBase.java",
"import junit.framework.TestCase;",
"public class TestBase extends TestCase {",
" public void testDoesStuff(boolean param) {}",
"}")
.doTest();
}
@Test
public void hasParameters_calledElsewhere_noFinding() {
compilationHelper
.addSourceLines(
"Test.java",
"import junit.framework.TestCase;",
"public class Test extends TestCase {",
" public void testActually() { testDoesStuff(true); }",
" public void testDoesStuff(boolean param) {}",
"}")
.doTest();
}
@Test
public void hasParameters_isOverride_noFinding() {
compilationHelper
.addSourceLines(
"Foo.java", //
"interface Foo {",
" void testDoesStuff(boolean param);",
"}")
.addSourceLines(
"Test.java",
"import junit.framework.TestCase;",
"public class Test extends TestCase implements Foo {",
" public void testDoesStuff(boolean param) {}",
"}")
.doTest();
}
@Test
public void noModifiers() {
refactorHelper
.addInputLines(
"in/DoesStuffTest.java",
"import junit.framework.TestCase;",
"import org.junit.Test;",
"public class DoesStuffTest extends TestCase {",
" void tsetDoesStuff() {}",
"}")
.addOutputLines(
"out/DoesStuffTest.java",
"import junit.framework.TestCase;",
"import org.junit.Test;",
"public class DoesStuffTest extends TestCase {",
" public void testDoesStuff() {}",
"}")
.doTest();
}
@Test
public void negativeCase1() {
compilationHelper.addSourceFile("JUnit3TestNotRunNegativeCase1.java").doTest();
}
@Test
public void negativeCase2() {
compilationHelper.addSourceFile("JUnit3TestNotRunNegativeCase2.java").doTest();
}
@Test
public void negativeCase3() {
compilationHelper.addSourceFile("JUnit3TestNotRunNegativeCase3.java").doTest();
}
@Test
public void negativeCase4() {
compilationHelper.addSourceFile("JUnit3TestNotRunNegativeCase4.java").doTest();
}
@Test
public void negativeCase5() {
compilationHelper
.addSourceFile("JUnit3TestNotRunNegativeCase3.java") // needed as a dependency
.addSourceFile("JUnit3TestNotRunNegativeCase5.java")
.doTest();
}
}
| 8,538
| 30.86194
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnusedTypeParameterTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class UnusedTypeParameterTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(UnusedTypeParameter.class, getClass());
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(UnusedTypeParameter.class, getClass());
@Test
public void positiveOnClass() {
helper
.addSourceLines(
"Test.java", //
"// BUG: Diagnostic contains:",
"final class Test<T> {}")
.doTest();
}
@Test
public void refactoring() {
refactoring
.addInputLines(
"Test.java", //
"final class Test<T> {}")
.addOutputLines(
"Test.java", //
"final class Test {}")
.doTest();
}
@Test
public void refactoringWithTwoParameters() {
refactoring
.addInputLines(
"Test.java", //
"final class Test<A, B> {",
" B get() { return null; }",
"}")
.addOutputLines(
"Test.java", //
"final class Test<B> {",
" B get() { return null; }",
"}")
.doTest();
}
@Test
public void refactoringWithGtgt() {
refactoring
.addInputLines(
"Test.java", //
"final class Test<A extends java.util.List<?>> {}")
.addOutputLines(
"Test.java", //
"final class Test {}")
.doTest();
}
@Test
public void positiveOnMethod() {
helper
.addSourceLines(
"Test.java", //
"final class Test {",
" // BUG: Diagnostic contains:",
" private <T> void test() {}",
"}")
.doTest();
}
@Test
public void methodCouldBeOverridden_negativeFinding() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" <T> void test() {}",
"}")
.doTest();
}
@Test
public void negative() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" private <T> boolean contains(java.util.Set<T> set, T elem) {",
" return set.contains(elem);",
" }",
"}")
.doTest();
}
}
| 3,178
| 25.714286
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StreamToIterableTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link StreamToIterable}. */
@RunWith(JUnit4.class)
public final class StreamToIterableTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(StreamToIterable.class, getClass());
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(StreamToIterable.class, getClass());
@Test
public void lambdaWithinEnhancedForLoop_recreatedEachTime_noFinding() {
helper
.addSourceLines(
"Test.java",
"import java.util.stream.Stream;",
"class Test {",
" void test() {",
" for (int i : (Iterable<Integer>) () -> Stream.of(1, 2, 3).iterator()) {}",
" }",
"}")
.doTest();
}
@Test
public void withinEnhancedForLoop_noFinding() {
helper
.addSourceLines(
"Test.java",
"import java.util.stream.Stream;",
"class Test {",
" void test() {",
" Stream<Integer> stream = Stream.of(1, 2, 3);",
" for (int i : (Iterable<Integer>) () -> stream.iterator()) {}",
" }",
"}")
.doTest();
}
@Test
public void methodReferenceRefactoredToExplicitCollection() {
refactoring
.addInputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import java.util.List;",
"import java.util.stream.Stream;",
"class Test {",
" void test(List<Integer> i) {",
" addAll(Stream.of(1, 2, 3)::iterator);",
" }",
" void addAll(Iterable<Integer> ints) {}",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import java.util.List;",
"import java.util.stream.Stream;",
"class Test {",
" void test(List<Integer> i) {",
" addAll(Stream.of(1, 2, 3).collect(toImmutableList()));",
" }",
" void addAll(Iterable<Integer> ints) {}",
"}")
.doTest();
}
@Test
public void lambdaRefactoredToExplicitCollection() {
refactoring
.addInputLines(
"Test.java",
"import java.util.List;",
"import java.util.stream.Stream;",
"class Test {",
" void test(List<Integer> i) {",
" Stream<Integer> stream = Stream.of(1, 2, 3);",
" addAll(() -> stream.iterator());",
" }",
" void addAll(Iterable<Integer> ints) {}",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import java.util.List;",
"import java.util.stream.Stream;",
"class Test {",
" void test(List<Integer> i) {",
" Stream<Integer> stream = Stream.of(1, 2, 3);",
" addAll(stream.collect(toImmutableList()));",
" }",
" void addAll(Iterable<Integer> ints) {}",
"}")
.doTest();
}
}
| 4,113
| 34.162393
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FuturesGetCheckedIllegalExceptionTypeTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FuturesGetCheckedIllegalExceptionType}. */
@RunWith(JUnit4.class)
public class FuturesGetCheckedIllegalExceptionTypeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FuturesGetCheckedIllegalExceptionType.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceFile("FuturesGetCheckedIllegalExceptionTypePositiveCases.java")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceFile("FuturesGetCheckedIllegalExceptionTypeNegativeCases.java")
.doTest();
}
}
| 1,425
| 32.952381
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SuppressWarningsWithoutExplanationTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link SuppressWarningsWithoutExplanation}. */
@RunWith(JUnit4.class)
public final class SuppressWarningsWithoutExplanationTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(
new SuppressWarningsWithoutExplanation(/* emitDummyFixes= */ true), getClass());
@Test
public void rawTypesSuppressed() {
helper
.addInputLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"deprecation\")",
" void test() {}",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"deprecation\") // Safe because...",
" void test() {}",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void multipleSuppressedWarnings() {
helper
.addInputLines(
"Test.java",
"class Test {",
" @SuppressWarnings({\"deprecation\", \"another\"})",
" void test() {}",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" @SuppressWarnings({\"deprecation\", \"another\"}) // Safe because...",
" void test() {}",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void negative() {
helper
.addInputLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"someotherwarning\")",
" void test() {}",
"}")
.expectUnchanged()
.doTest(TEXT_MATCH);
}
@Test
public void hasInlineComment() {
helper
.addInputLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"rawtypes\") // foo",
" void test() {}",
"}")
.expectUnchanged()
.doTest(TEXT_MATCH);
}
@Test
public void suppressedOnEntiereClass() {
helper
.addInputLines(
"Test.java",
"@Deprecated",
"@SuppressWarnings(\"deprecation\") // foo",
"class Test {",
" void test() {}",
"}")
.expectUnchanged()
.doTest(TEXT_MATCH);
}
@Test
public void hasCommentBefore() {
helper
.addInputLines(
"Test.java",
"class Test {",
" // foo",
" @SuppressWarnings(\"deprecation\")",
" void test() {}",
"}")
.expectUnchanged()
.doTest(TEXT_MATCH);
}
@Test
public void hasJavadocBefore() {
helper
.addInputLines(
"Test.java",
"class Test {",
" /**",
" * Frobnicates.",
" * This comment might explain why it's safe.",
" */",
" @SuppressWarnings(\"deprecation\")",
" void test() {}",
"}")
.expectUnchanged()
.doTest(TEXT_MATCH);
}
}
| 3,885
| 26.757143
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ExtendingJUnitAssertTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author kayco@google.com (Kayla Walker)
*/
@RunWith(JUnit4.class)
public class ExtendingJUnitAssertTest {
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(ExtendingJUnitAssert.class, getClass());
@Test
public void positive() {
refactoringTestHelper
.addInputLines(
"in/Foo.java",
"import org.junit.Assert;",
"class Foo extends Assert {",
"public void test() {",
"assertEquals(5, 5);",
"}",
"}")
.addOutputLines(
"in/Foo.java",
"import static org.junit.Assert.assertEquals;",
"import org.junit.Assert;",
"class Foo {",
"public void test() {",
"assertEquals(5, 5);",
"}",
"}")
.doTest();
}
@Test
public void positiveWithGenerics() {
refactoringTestHelper
.addInputLines(
"in/Foo.java",
"import org.junit.Assert;",
"class Foo<T extends String> extends Assert {",
"public void test() {",
"assertEquals(5, 5);",
"assertNull(2);",
"assertNotNull(3);",
"}",
"}")
.addOutputLines(
"in/Foo.java",
"import static org.junit.Assert.assertEquals;",
"import static org.junit.Assert.assertNotNull;",
"import static org.junit.Assert.assertNull;",
"import org.junit.Assert;",
"class Foo<T extends String> {",
"public void test() {",
"assertEquals(5, 5);",
"assertNull(2);",
"assertNotNull(3);",
"}",
"}")
.doTest();
}
@Test
public void positiveWithImplements() {
refactoringTestHelper
.addInputLines(
"in/Foo.java",
"import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;",
"import org.junit.Assert;",
"abstract class Foo extends Assert implements ClassTreeMatcher {",
"public void test() {",
"assertEquals(5, 5);",
"}",
"}")
.addOutputLines(
"in/Foo.java",
"import static org.junit.Assert.assertEquals;",
"import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;",
"import org.junit.Assert;",
"abstract class Foo implements ClassTreeMatcher {",
"public void test() {",
"assertEquals(5, 5);",
"}",
"}")
.doTest();
}
}
| 3,457
| 30.436364
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TypeParameterUnusedInFormalsTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class TypeParameterUnusedInFormalsTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(TypeParameterUnusedInFormals.class, getClass());
@Test
public void evilCastImpl() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test {",
" // BUG: Diagnostic contains:",
" static <T> T doCast(Object o) { T t = (T) o; return t; }",
"}")
.doTest();
}
@Test
public void leadingParam() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test {",
" // BUG: Diagnostic contains:",
" static <U extends Object, T> T doCast(U o) { T t = (T) o; return t; }",
"}")
.doTest();
}
@Test
public void trailingParam() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test {",
" // BUG: Diagnostic contains:",
" static <T, U extends Object> T doCast(U o) { T t = (T) o; return t; }",
"}")
.doTest();
}
@Test
public void leadingAndTrailingParam() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test {",
" // BUG: Diagnostic contains:",
" static <V extends Object, T, U extends Object> T doCast(U o, V v) { T t = (T) o;"
+ " return t; }",
"}")
.doTest();
}
@Test
public void superBound() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test {",
" // BUG: Diagnostic contains:",
" static <T extends Number> T doCast(Object o) { return (T) o; }",
"}")
.doTest();
}
@Test
public void okFBound() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test {",
" interface Foo<T> {}",
" static <T extends Foo<T>> T doCast(Object o) { return (T) o; }",
"}")
.doTest();
}
@Test
public void wildbound() {
compilationHelper
.addSourceLines(
"Test.java",
"package foo.bar;",
"class Test {",
" interface Foo<T> {}",
" // BUG: Diagnostic contains:",
" static <T extends Foo<?>> T doCast(Object o) { return (T) o; }",
"}")
.doTest();
}
@Test
public void okGenericFactory() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"class Test {",
" static <T> List<T> newList() { return null; }",
"}")
.doTest();
}
@Test
public void okWithParam() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"class Test {",
" static <T> T noop(T t) { return t; }",
"}")
.doTest();
}
@Test
public void okNotMyParam() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"class Test<T> {",
" T noop(T t) { return t; }",
"}")
.doTest();
}
@Test
public void abstractMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"abstract class Test {",
" // BUG: Diagnostic contains:",
" abstract <T> T badMethod();",
"}")
.doTest();
}
@Test
public void objectCast() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains:",
" <T> T badMethod(String s) { return (T) s; }",
"}")
.doTest();
}
@Test
public void issue343() {
compilationHelper
.addSourceLines(
"Test.java",
"interface Test {",
" interface Visitor1<X, Y> {}",
" interface Visitor2<X, Y> {}",
" <R,",
" R1 extends R,",
" R2 extends R,",
" X1 extends Exception,",
" X2 extends Exception,",
" V extends Visitor1<R1, X1> & Visitor2<R2, X2>>",
" R accept_(V v) throws X1, X2;",
"}")
.doTest();
}
// regression test for b/28055418
@Test
public void classTypeParameter() {
compilationHelper
.addSourceLines("Test.java", "abstract class Test<T> {", " abstract T get(String s);", "}")
.doTest();
}
// regression test for b/35385704
@Test
public void typeAnnotation() {
compilationHelper
.addSourceLines(
"A.java",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Target;",
"@Target(ElementType.TYPE_USE)",
"@interface A {}")
.addSourceLines(
"Test.java", //
"class Test {",
" <T> T f(@A T x) {",
" return x;",
" }",
"}")
.doTest();
}
}
| 6,173
| 25.843478
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ExpectedExceptionCheckerTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ExpectedExceptionChecker}Test. */
@RunWith(JUnit4.class)
public class ExpectedExceptionCheckerTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(ExpectedExceptionChecker.class, getClass());
@Test
public void expect() {
testHelper
.addInputLines(
"in/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Test;",
"import org.junit.Rule;",
"import org.hamcrest.CoreMatchers;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" if (true) {",
" Path p = Paths.get(\"NOSUCH\");",
" thrown.expect(IOException.class);",
" thrown.expect(CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",
" thrown.expectCause(",
" CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",
" thrown.expectMessage(\"error\");",
" thrown.expectMessage(CoreMatchers.containsString(\"error\"));",
" Files.readAllBytes(p);",
" assertThat(Files.exists(p)).isFalse();",
" }",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.hamcrest.MatcherAssert.assertThat;",
"import static org.junit.Assert.assertThrows;",
"",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.hamcrest.CoreMatchers;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" if (true) {",
" Path p = Paths.get(\"NOSUCH\");",
" IOException thrown =",
" assertThrows(IOException.class, () -> Files.readAllBytes(p));",
" assertThat(thrown,",
" CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",
" assertThat(thrown.getCause(),",
" CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",
" assertThat(thrown).hasMessageThat().contains(\"error\");",
" assertThat(thrown.getMessage(), CoreMatchers.containsString(\"error\"));",
" assertThat(Files.exists(p)).isFalse();",
" }",
" }",
"}")
.doTest();
}
@Test
public void noExceptionType() {
testHelper
.addInputLines(
"in/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.hamcrest.CoreMatchers;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" thrown.expect(CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",
" Files.readAllBytes(p);",
" Files.readAllBytes(p);",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.hamcrest.MatcherAssert.assertThat;",
"import static org.junit.Assert.assertThrows;",
"",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.hamcrest.CoreMatchers;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" Throwable thrown = assertThrows(Throwable.class, () -> {",
" Files.readAllBytes(p);",
" Files.readAllBytes(p);",
" });",
" assertThat(thrown, CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",
" }",
"}")
.doTest();
}
@Test
public void noExpectations() {
testHelper
.addInputLines(
"in/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.hamcrest.CoreMatchers;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" thrown.expect(IOException.class);",
" Files.readAllBytes(p);",
" assertThat(Files.exists(p)).isFalse();",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.junit.Assert.assertThrows;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.hamcrest.CoreMatchers;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" assertThrows(IOException.class, () -> Files.readAllBytes(p));",
" assertThat(Files.exists(p)).isFalse();",
" }",
"}")
.doTest();
}
@Test
public void nonExpressionStatement() {
testHelper
.addInputLines(
"in/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" thrown.expect(IOException.class);",
" Files.readAllBytes(p);",
" if (true) Files.readAllBytes(p);",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.junit.Assert.assertThrows;",
"",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" assertThrows(IOException.class, () -> {",
" Files.readAllBytes(p);",
" if (true) Files.readAllBytes(p);",
" });",
" }",
"}")
.doTest();
}
// https://github.com/hamcrest/JavaHamcrest/issues/27
@Test
public void isA_hasCauseThat() {
testHelper
.addInputLines(
"in/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Test;",
"import org.junit.Rule;",
"import org.hamcrest.CoreMatchers;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" thrown.expect(IOException.class);",
" thrown.expectCause(CoreMatchers.isA(IOException.class));",
" thrown.expectCause(org.hamcrest.core.Is.isA(IOException.class));",
" Files.readAllBytes(p);",
" assertThat(Files.exists(p)).isFalse();",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.junit.Assert.assertThrows;",
"",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.hamcrest.CoreMatchers;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" IOException thrown =",
" assertThrows(IOException.class, () -> Files.readAllBytes(p));",
" assertThat(thrown).hasCauseThat().isInstanceOf(IOException.class);",
" assertThat(thrown).hasCauseThat().isInstanceOf(IOException.class);",
" assertThat(Files.exists(p)).isFalse();",
" }",
"}")
.doTest();
}
@Test
public void typedMatcher() {
testHelper
.addInputLines(
"in/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Test;",
"import org.junit.Rule;",
"import org.hamcrest.Matcher;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" Matcher<IOException> matcher;",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" thrown.expect(matcher);",
" Files.readAllBytes(p);",
" assertThat(Files.exists(p)).isFalse();",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.hamcrest.MatcherAssert.assertThat;",
"import static org.junit.Assert.assertThrows;",
"",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.hamcrest.Matcher;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" Matcher<IOException> matcher;",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" IOException thrown =",
" assertThrows(IOException.class, () -> Files.readAllBytes(p));",
" assertThat(thrown, matcher);",
" assertThat(Files.exists(p)).isFalse();",
" }",
"}")
.doTest();
}
@Test
public void nothingButAsserts() {
testHelper
.addInputLines(
"in/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" thrown.expect(RuntimeException.class);",
" assertThat(false).isFalse();",
" assertThat(true).isTrue();",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void test() throws Exception {",
" assertThat(false).isFalse();",
" assertThat(true).isTrue();",
" }",
"}")
.doTest();
}
@Test
public void removeExplicitFail() {
testHelper
.addInputLines(
"in/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.junit.Assert.fail;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Test;",
"import org.junit.Rule;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void testThrow() throws Exception {",
" thrown.expect(IOException.class);",
" throw new IOException();",
" }",
" @Test",
" public void one() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" thrown.expect(IOException.class);",
" Files.readAllBytes(p);",
" assertThat(Files.exists(p)).isFalse();",
" fail();",
" }",
" @Test",
" public void two() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" thrown.expect(IOException.class);",
" Files.readAllBytes(p);",
" assertThat(Files.exists(p)).isFalse();",
" throw new AssertionError();",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.junit.Assert.assertThrows;",
"import static org.junit.Assert.fail;",
"",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void testThrow() throws Exception {",
" }",
" @Test",
" public void one() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" assertThrows(IOException.class, () -> Files.readAllBytes(p));",
" assertThat(Files.exists(p)).isFalse();",
" }",
" @Test",
" public void two() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" assertThrows(IOException.class, () -> Files.readAllBytes(p));",
" assertThat(Files.exists(p)).isFalse();",
" }",
"}")
.doTest();
}
// https://github.com/google/error-prone/issues/1072
@Test
public void i1072() {
testHelper
.addInputLines(
"in/ExceptionTest.java",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void testThrow(Class<? extends Throwable> clazz) throws Exception {",
" thrown.expect(clazz);",
" clazz.toString();",
" }",
"}")
.addOutputLines(
"in/ExceptionTest.java",
"import static org.junit.Assert.assertThrows;",
"import org.junit.Rule;",
"import org.junit.Test;",
"import org.junit.rules.ExpectedException;",
"class ExceptionTest {",
" @Rule ExpectedException thrown = ExpectedException.none();",
" @Test",
" public void testThrow(Class<? extends Throwable> clazz) throws Exception {",
" assertThrows(Throwable.class, () -> clazz.toString());",
" }",
"}")
.doTest();
}
}
| 19,062
| 39.732906
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SuppressWarningsDeprecatedTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link SuppressWarningsDeprecated}.
*
* @author sjnickerson@google.com (Simon Nickerson)
*/
@RunWith(JUnit4.class)
public class SuppressWarningsDeprecatedTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(SuppressWarningsDeprecated.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("SuppressWarningsDeprecatedPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("SuppressWarningsDeprecatedNegativeCases.java").doTest();
}
}
| 1,405
| 30.244444
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CharacterGetNumericValueTest.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.common.truth.Truth.assertThat;
import com.google.errorprone.CompilationTestHelper;
import com.ibm.icu.lang.UCharacter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link CharacterGetNumericValue} */
@RunWith(JUnit4.class)
public class CharacterGetNumericValueTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(CharacterGetNumericValue.class, getClass());
@Test
public void characterGetNumericValue_unexpectedBehavior() {
// Verify that the unexpected behavior still holds
// Expect 'A' - 'Z' to map to 10 - 35
for (int c = (int) 'A'; c < (int) 'Z'; c++) {
assertThat(Character.getNumericValue((char) c)).isEqualTo(c - (int) 'A' + 10);
assertThat(Character.getNumericValue(c)).isEqualTo(c - (int) 'A' + 10);
}
assertThat(Character.getNumericValue('Ⅴ' /* U+2164, Roman numeral 5 */)).isEqualTo(5);
assertThat(Character.getNumericValue('V')).isEqualTo(31);
}
@Test
public void uCharacterGetNumericValue_unexpectedBehavior() {
// Verify that the unexpected behavior still holds
// Expect 'A' - 'Z' to map to 10 - 35
for (int c = (int) 'A'; c < (int) 'Z'; c++) {
assertThat(UCharacter.getNumericValue((char) c)).isEqualTo(c - (int) 'A' + 10);
assertThat(UCharacter.getNumericValue(c)).isEqualTo(c - (int) 'A' + 10);
}
assertThat(UCharacter.getNumericValue('Ⅴ' /* U+2164, Roman numeral 5 */)).isEqualTo(5);
assertThat(UCharacter.getNumericValue('V')).isEqualTo(31);
}
@Test
public void characterDigit_expectedBehavior() {
assertThat(Character.digit('Z', 36)).isEqualTo(35);
assertThat(Character.digit('௧' /* U+0BE7, Tamil digit 1 */, 36)).isEqualTo(1);
assertThat(Character.digit('௲' /* U+0BF2, Tamil number 1000 */, 36)).isEqualTo(-1);
assertThat(Character.digit('Ⅴ' /* U+2164, Roman numeral 5 */, 36)).isEqualTo(-1);
}
@Test
public void uCharacterDigit_expectedBehavior() {
assertThat(UCharacter.digit('Z', 36)).isEqualTo(35);
assertThat(UCharacter.digit('௧' /* U+0BE7, Tamil digit 1 */, 36)).isEqualTo(1);
assertThat(UCharacter.digit('௲' /* U+0BF2, Tamil number 1000 */, 36)).isEqualTo(-1);
assertThat(UCharacter.digit('Ⅴ' /* U+2164, Roman numeral 5 */, 36)).isEqualTo(-1);
}
@Test
public void character_getNumericValue_char() {
helper
.addSourceLines(
"Test.java",
"import java.lang.Character;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: CharacterGetNumericValue",
" Character.getNumericValue('A');",
" }",
"}")
.doTest();
}
@Test
public void character_getNumericValue_int() {
helper
.addSourceLines(
"Test.java",
"import java.lang.Character;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: CharacterGetNumericValue",
" Character.getNumericValue(41);",
" }",
"}")
.doTest();
}
@Test
public void uCharacter_getNumericValue_char() {
helper
.addSourceLines(
"Test.java",
"import com.ibm.icu.lang.UCharacter;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: CharacterGetNumericValue",
" UCharacter.getNumericValue(41);",
" }",
"}")
.doTest();
}
@Test
public void uCharacter_getNumericValue_int() {
helper
.addSourceLines(
"Test.java",
"import com.ibm.icu.lang.UCharacter;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: CharacterGetNumericValue",
" UCharacter.getNumericValue(41);",
" }",
"}")
.doTest();
}
}
| 4,609
| 33.402985
| 91
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JdkObsoleteTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import java.util.Enumeration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link JdkObsolete}Test */
@RunWith(JUnit4.class)
public class JdkObsoleteTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(JdkObsolete.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"import java.nio.file.Path;",
"class Test {",
" {",
" // BUG: Diagnostic contains:",
" new java.util.LinkedList<>();",
" // BUG: Diagnostic contains:",
" new java.util.Stack<>();",
" // BUG: Diagnostic contains:",
" new java.util.Vector<>();",
" // BUG: Diagnostic contains:",
" new java.util.Hashtable<>();",
" // BUG: Diagnostic contains:",
" new StringBuffer();",
" // BUG: Diagnostic contains:",
" new java.util.Hashtable<Object, Object>() {};",
" }",
"}")
.doTest();
}
@Test
public void stringBuffer_appendReplacement() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.regex.Matcher;",
"class Test {",
" void f(Matcher m) {",
" StringBuffer sb = new StringBuffer();",
" m.appendReplacement(sb, null);",
" }",
"}")
.doTest();
}
@Test
public void stringBuffer_appendTail() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.regex.Matcher;",
"class Test {",
" void f(Matcher m) {",
" StringBuffer sb = new StringBuffer();",
" m.appendTail(sb);",
" }",
"}")
.doTest();
}
@Test
public void positiveExtends() {
testHelper
.addSourceLines(
"Test.java",
"import java.nio.file.Path;",
"class Test {",
" // BUG: Diagnostic contains:",
" abstract class A implements java.util.Enumeration<Object> {}",
" // BUG: Diagnostic contains:",
" abstract class B implements java.util.SortedSet<Object> {}",
" // BUG: Diagnostic contains:",
" abstract class C implements java.util.SortedMap<Object, Object> {}",
" // BUG: Diagnostic contains:",
" abstract class D extends java.util.Dictionary<Object, Object> {}",
"}")
.doTest();
}
@Test
public void refactoring() {
BugCheckerRefactoringTestHelper.newInstance(JdkObsolete.class, getClass())
.addInputLines(
"in/Test.java", //
"import java.util.*;",
"class Test {",
" Deque<Object> d = new LinkedList<>();",
" List<Object> l = new LinkedList<>();",
" {",
" l = new LinkedList<>();",
" }",
" LinkedList<Object> ll = new LinkedList<>();",
" List<Object> lll = new LinkedList<Object>() {{",
" add(null); // yikes",
" }};",
"}")
.addOutputLines(
"out/Test.java", //
"import java.util.*;",
"class Test {",
" Deque<Object> d = new ArrayDeque<>();",
" List<Object> l = new ArrayList<>();",
" {",
" l = new ArrayList<>();",
" }",
" LinkedList<Object> ll = new LinkedList<>();",
" List<Object> lll = new LinkedList<Object>() {{",
" add(null); // yikes",
" }};",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void stringBufferRefactoringTest() {
BugCheckerRefactoringTestHelper.newInstance(JdkObsolete.class, getClass())
.addInputLines(
"in/Test.java", //
"class Test {",
" String f() {",
" StringBuffer sb = new StringBuffer();",
" return sb.append(42).toString();",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"class Test {",
" String f() {",
" StringBuilder sb = new StringBuilder();",
" return sb.append(42).toString();",
" }",
"}")
.doTest();
}
@Test
public void stringBufferRefactoringTest_usingVar() {
BugCheckerRefactoringTestHelper.newInstance(JdkObsolete.class, getClass())
.addInputLines(
"in/Test.java", //
"class Test {",
" String f() {",
" var sb = new StringBuffer();",
" return sb.append(42).toString();",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"class Test {",
" String f() {",
" var sb = new StringBuilder();",
" return sb.append(42).toString();",
" }",
"}")
.doTest();
}
/** A test input. */
public interface Lib {
Enumeration<Integer> foos();
}
@Test
public void obsoleteOverride() {
testHelper
.addSourceLines(
"Test.java",
"import " + Lib.class.getCanonicalName() + ";",
"import java.util.Enumeration;",
"class Test implements Lib {",
" public Enumeration<Integer> foos() {",
" return new Enumeration<Integer>() {",
" @Override public boolean hasMoreElements() { return false; }",
" @Override public Integer nextElement() { return null; }",
" };",
" }",
"}")
.doTest();
}
@Test
public void additionalRefactorings() {
BugCheckerRefactoringTestHelper.newInstance(JdkObsolete.class, getClass())
.addInputLines(
"in/Test.java", //
"import java.util.*;",
"import java.util.function.*;",
"class Test {",
" Supplier<Deque<Object>> a = () -> new LinkedList<>();",
" Supplier<Deque<Object>> b = () -> {",
" return new LinkedList<>();",
" };",
" Supplier<Deque<Object>> c = LinkedList::new;",
" Deque<Object> f() {",
" return new LinkedList<>();",
" }",
" void g(Deque<Object> x) {}",
" {",
" g(new LinkedList<>());",
" }",
" {",
" List<LinkedList<String>> xs = new ArrayList<>();",
" List<List<String>> ys = new ArrayList<>();",
" xs.add(new LinkedList<>());",
" ys.add(new LinkedList<>());",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"import java.util.*;",
"import java.util.function.*;",
"class Test {",
" Supplier<Deque<Object>> a = () -> new ArrayDeque<>();",
" Supplier<Deque<Object>> b = () -> {",
" return new ArrayDeque<>();",
" };",
" Supplier<Deque<Object>> c = ArrayDeque::new;",
" Deque<Object> f() {",
" return new ArrayDeque<>();",
" }",
" void g(Deque<Object> x) {}",
" {",
" g(new ArrayDeque<>());",
" }",
" {",
" List<LinkedList<String>> xs = new ArrayList<>();",
" List<List<String>> ys = new ArrayList<>();",
" xs.add(new LinkedList<>());",
" ys.add(new ArrayList<>());",
" }",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void obsoleteMocking() {
testHelper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.when;",
"import " + Lib.class.getCanonicalName() + ";",
"import java.util.Enumeration;",
"class Test {",
" void test(Lib lib) {",
" when(lib.foos())",
" .thenReturn(",
" new Enumeration<Integer>() {",
" public boolean hasMoreElements() {",
" return false;",
" }",
" public Integer nextElement() {",
" return null;",
" }",
" });",
" }",
"}")
.doTest();
}
@Test
public void navigableSetRepro() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.NavigableSet;",
"import java.util.Optional;",
"class Test {",
" Optional<Object> fail1(Optional<NavigableSet<Object>> myOptionalSet) {",
" return myOptionalSet.map(NavigableSet::first);",
" }",
" Optional<Object> fail2(Optional<NavigableSet<Object>> myOptionalSet) {",
" return myOptionalSet.map(NavigableSet::last);",
" }",
"}")
.doTest();
}
@Test
public void navigableMapInheritedMethod() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Map;",
"import java.util.Set;",
"import java.util.NavigableMap;",
"class Test {",
" void f(NavigableMap<String, Integer> m) {",
" for (Integer e : m.values()) {",
" }",
" }",
"}")
.doTest();
}
@Test
public void indirect() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.SortedSetMultimap;",
"import com.google.common.collect.TreeMultimap;",
"class Test {",
" void f() {",
" SortedSetMultimap<String, String> myMultimap = TreeMultimap.create();",
" String myValue = myMultimap.get(\"foo\").first();",
" }",
"}")
.doTest();
}
}
| 11,124
| 31.817109
| 88
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DeadThreadTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link DeadThread}Test */
@RunWith(JUnit4.class)
public class DeadThreadTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(DeadThread.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" {",
" // BUG: Diagnostic contains:",
" new Thread();",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" {",
" new Thread().start();",
" }",
"}")
.doTest();
}
}
| 1,545
| 25.655172
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeLocalTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FieldCanBeLocal}. */
@RunWith(JUnit4.class)
public final class FieldCanBeLocalTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(FieldCanBeLocal.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(FieldCanBeLocal.class, getClass());
@Test
public void simplePositive() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains:",
" private int a;",
" int foo() {",
" a = 1;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void suppressedByUnusedPrefix() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int unusedA;",
" int foo() {",
" unusedA = 1;",
" return unusedA;",
" }",
"}")
.doTest();
}
@Test
public void multipleAssignments() {
refactoringTestHelper
.addInputLines(
"Test.java",
"class Test {",
" private int a;",
" int foo() {",
" a = 1;",
" a = 2;",
" return a;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int foo() {",
" int a = 1;",
" a = 2;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void hasFieldAnnotation_noMatch() {
helper
.addSourceLines(
"Field.java",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.RetentionPolicy;",
"import java.lang.annotation.Target;",
"@Target(ElementType.FIELD)",
"@Retention(RetentionPolicy.RUNTIME)",
"@interface Field {}")
.addSourceLines(
"Test.java",
"class Test {",
" @Field private int a;",
" int foo() {",
" a = 1;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void hasVariableAnnotation_matchesAndAnnotationCopied() {
refactoringTestHelper
.addInputLines(
"Field.java",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.RetentionPolicy;",
"import java.lang.annotation.Target;",
"@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE})",
"@Retention(RetentionPolicy.RUNTIME)",
"@interface Field {}")
.expectUnchanged()
.addInputLines(
"Test.java",
"class Test {",
" @Field private int a;",
" int foo() {",
" a = 1;",
" return a;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int foo() {",
" @Field int a = 1;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void multipleVariableAnnotations() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import javax.annotation.Nonnull;",
"import javax.annotation.Nullable;",
"class Test {",
" @Nonnull /* foo */ @Nullable private Integer a;",
" int foo() {",
" a = 1;",
" return a;",
" }",
"}")
.addOutputLines(
"Test.java",
"import javax.annotation.Nonnull;",
"import javax.annotation.Nullable;",
"class Test {",
"",
" int foo() {",
" @Nonnull /* foo */ @Nullable Integer a = 1;",
" return a;",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void hasTypeUseAnnotation_match() {
refactoringTestHelper
.addInputLines(
"Field.java",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.RetentionPolicy;",
"import java.lang.annotation.Target;",
"@Target(ElementType.TYPE_USE)",
"@Retention(RetentionPolicy.RUNTIME)",
"@interface Field {}")
.expectUnchanged()
.addInputLines(
"Test.java",
"class Test {",
" @Field private int a;",
" int foo() {",
" a = 1;",
" return a;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int foo() {",
" @Field int a = 1;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void suppressedOnMethod() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"FieldCanBeLocal\")",
" private int a;",
" int foo() {",
" a = 1;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void suppressedOnClass() {
helper
.addSourceLines(
"Test.java",
"@SuppressWarnings(\"FieldCanBeLocal\")",
"class Test {",
" private int a;",
" int foo() {",
" a = 1;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void inlineConditional_noWarning() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int a;",
" int foo(int b) {",
" a = b > 2 ? a : b;",
" return a;",
" }",
" int bar(int b) {",
" a = b;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void fieldIsPublic_noMatch() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" public int a;",
" int foo() {",
" a = 1;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void usedBeforeAssigment_noMatch() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" public int a;",
" int foo() {",
" if (a < 0) {",
" return 0;",
" }",
" a = 1;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void usedInMultipleMethods_alwaysAssignedFirst_positive() {
refactoringTestHelper
.addInputLines(
"Test.java",
"class Test {",
" private int a;",
" int foo() {",
" a = 1;",
" return a;",
" }",
" int bar() {",
" a = 2;",
" return a;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int foo() {",
" int a = 1;",
" return a;",
" }",
" int bar() {",
" int a = 2;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void qualifiedWithThis_refactoringRemovesThis() {
refactoringTestHelper
.addInputLines(
"Test.java",
"class Test {",
" private int a;",
" int foo() {",
" this.a = 1;",
" return a;",
" }",
" int bar() {",
" this.a = 2;",
" return a;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int foo() {",
" int a = 1;",
" return a;",
" }",
" int bar() {",
" int a = 2;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void assignmentToFieldOfSameName_isRemoved() {
refactoringTestHelper
.addInputLines(
"Test.java",
"class Test {",
" private int a;",
" Test(int a) {",
" this.a = a;",
" int b = a + 2;",
" }",
" int foo() {",
" this.a = 1;",
" return a;",
" }",
" int bar() {",
" this.a = 2;",
" return a;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" Test(int a) {",
" int b = a + 2;",
" }",
" int foo() {",
" int a = 1;",
" return a;",
" }",
" int bar() {",
" int a = 2;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void usedBeforeReassignment_noMatch() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int a;",
" int foo() {",
" a = a + 1;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void fieldAssignedOnField() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" class Sub {",
" private int a;",
" int a() {",
" return a;",
" }",
" }",
" private Sub sub;",
" Test(Sub sub) {",
" this.sub = sub;",
" }",
" void foo() {",
" sub.a = 1;",
" }",
"}")
.doTest();
}
@Test
public void usedWithinClassScope_noMatch() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Predicate;",
"class Test {",
" private Integer a;",
" Predicate<Integer> predicate = b -> a == b;",
" Test(int a) {",
" this.a = a;",
" }",
" public void set(int a) {",
" this.a = a;",
" }",
"}")
.doTest();
}
@Test
public void usedWithinLambda_noWarning() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Predicate;",
"class Test {",
" private Integer a;",
" Test(int a) {",
" this.a = a;",
" }",
" public Predicate<Integer> set(int a) {",
" this.a = a;",
" return x -> x == this.a;",
" }",
"}")
.doTest();
}
@Test
public void usedWithinLambdaMemberSelect() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Predicate;",
"import java.util.stream.Stream;",
"import java.util.Collections;",
"class Test {",
" private Integer a;",
" Test(int a) {",
" this.a = a;",
" }",
" public Stream<Integer> set(int a) {",
" this.a = a;",
" return Collections.<Integer>emptyList().stream()",
" .filter(x -> x == this.a)",
" .filter(x -> x > 0);",
" }",
"}")
.doTest();
}
@Test
public void usedInStaticInitializer() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" static {",
" Test[] tests = new Test[0];",
" for (Test test : tests) {",
" int b = test.a;",
" }",
" }",
" private Integer a;",
" Test(int a) {",
" this.a = a;",
" }",
"}")
.doTest();
}
@Test
public void unusedPrivateMethod() {
helper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Keep;",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.RetentionPolicy;",
"import java.lang.annotation.Target;",
"import javax.inject.Inject;",
"public class Test {",
" @Keep private int a;",
" @ProvidesCustom private int b;",
" public int test(int aa, int bb) {",
" a = aa;",
" b = bb;",
" return a + b;",
" }",
" @Keep",
" @Target(ElementType.FIELD)",
" @Retention(RetentionPolicy.SOURCE)",
" private @interface ProvidesCustom {}",
"}")
.doTest();
}
@Test
public void accessedInOtherMethod() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int x;",
" int f() {",
" x = 42;",
" g();",
" return x;",
" }",
" void g() {",
" x = 46;",
" }",
"}")
.doTest();
}
}
| 14,940
| 25.775986
| 85
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryLongToIntConversionTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers.FIRST;
import static com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers.SECOND;
import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test for {@link com.google.errorprone.bugpatterns.UnnecessaryLongToIntConversion}. */
@RunWith(JUnit4.class)
public class UnnecessaryLongToIntConversionTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(UnnecessaryLongToIntConversion.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryLongToIntConversion.class, getClass());
@Test
public void longParameterLongToIntPositiveCases() {
compilationHelper.addSourceFile("UnnecessaryLongToIntConversionPositiveCases.java").doTest();
}
@Test
public void longParameterLongToIntNegativeCases() {
compilationHelper.addSourceFile("UnnecessaryLongToIntConversionNegativeCases.java").doTest();
}
// Test the suggested fixes, first removing the conversion and second replacing it with a call to
// {@code Longs.constrainToRange()} instead.
@Test
public void suggestRemovingTypeCast() {
refactoringHelper
.addInputLines(
"in/A.java",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong((int) x);",
" }",
"}")
.addOutputLines(
"out/A.java",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong(x);",
" }",
"}")
.setFixChooser(FIRST)
.doTest(TEXT_MATCH);
}
@Test
public void suggestRemovingTypeCastWithoutSpacing() {
refactoringHelper
.addInputLines(
"in/A.java",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong((int)x);",
" }",
"}")
.addOutputLines(
"out/A.java",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong(x);",
" }",
"}")
.setFixChooser(FIRST)
.doTest(TEXT_MATCH);
}
@Test
public void suggestReplacingTypeCastWithConstrainToRange() {
refactoringHelper
.addInputLines(
"in/A.java",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong((int) x);",
" }",
"}")
.addOutputLines(
"out/A.java",
"import com.google.common.primitives.Longs;",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong(Longs.constrainToRange(x, Integer.MIN_VALUE, Integer.MAX_VALUE));",
" }",
"}")
.setFixChooser(SECOND)
.doTest(TEXT_MATCH);
}
@Test
public void suggestReplacingTypeCastWithoutSpacingWithConstrainToRange() {
refactoringHelper
.addInputLines(
"in/A.java",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong((int)x);",
" }",
"}")
.addOutputLines(
"out/A.java",
"import com.google.common.primitives.Longs;",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong(Longs.constrainToRange(x, Integer.MIN_VALUE, Integer.MAX_VALUE));",
" }",
"}")
.setFixChooser(SECOND)
.doTest(TEXT_MATCH);
}
@Test
public void suggestRemovingStaticMethod() {
refactoringHelper
.addInputLines(
"in/A.java",
"import com.google.common.primitives.Ints;",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong(Ints.checkedCast(x));",
" }",
"}")
.addOutputLines(
"out/A.java",
"import com.google.common.primitives.Ints;",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong(x);",
" }",
"}")
.setFixChooser(FIRST)
.doTest(TEXT_MATCH);
}
@Test
public void suggestRemovingStaticMethodWithBoxedLongArgument() {
refactoringHelper
.addInputLines(
"in/A.java",
"import com.google.common.primitives.Ints;",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" Long x = Long.valueOf(1);",
" acceptsLong(Ints.checkedCast(x));",
" }",
"}")
.addOutputLines(
"out/A.java",
"import com.google.common.primitives.Ints;",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" Long x = Long.valueOf(1);",
" acceptsLong(x);",
" }",
"}")
.setFixChooser(FIRST)
.doTest(TEXT_MATCH);
}
@Test
public void suggestReplacingStaticMethodWithConstrainToRange() {
refactoringHelper
.addInputLines(
"in/A.java",
"import java.lang.Math;",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong(Math.toIntExact(x));",
" }",
"}")
.addOutputLines(
"out/A.java",
"import com.google.common.primitives.Longs;",
"import java.lang.Math;",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" long x = 1L;",
" acceptsLong(Longs.constrainToRange(x, Integer.MIN_VALUE, Integer.MAX_VALUE));",
" }",
"}")
.setFixChooser(SECOND)
.doTest(TEXT_MATCH);
}
@Test
public void suggestRemovingInstanceMethod() {
refactoringHelper
.addInputLines(
"in/A.java",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" Long x = Long.valueOf(1);",
" acceptsLong(x.intValue());",
" }",
"}")
.addOutputLines(
"out/A.java",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" Long x = Long.valueOf(1);",
" acceptsLong(x);",
" }",
"}")
.setFixChooser(FIRST)
.doTest(TEXT_MATCH);
}
@Test
public void suggestReplacingInstanceMethodWithConstrainToRange() {
refactoringHelper
.addInputLines(
"in/A.java",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" Long x = Long.valueOf(1);",
" acceptsLong(x.intValue());",
" }",
"}")
.addOutputLines(
"out/A.java",
"import com.google.common.primitives.Longs;",
"public class A {",
" void acceptsLong(long value) {}",
" void foo() {",
" Long x = Long.valueOf(1);",
" acceptsLong(Longs.constrainToRange(x, Integer.MIN_VALUE, Integer.MAX_VALUE));",
" }",
"}")
.setFixChooser(SECOND)
.doTest(TEXT_MATCH);
}
}
| 9,180
| 31.101399
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DoNotMockCheckerTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.auto.value.processor.AutoValueProcessor;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.annotations.DoNotMock;
import java.lang.annotation.Retention;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
/**
* Tests for {@link DoNotMockChecker}.
*
* @author amalloy@google.com (Alan Malloy)
*/
@RunWith(JUnit4.class)
public final class DoNotMockCheckerTest {
private static final String DO_NOT_MOCK_REASON =
"the reason why OtherDoNotMockObject is DoNotMock";
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(DoNotMockChecker.class, getClass())
.addSourceLines(
"lib/DoNotMockObjects.java",
"package lib;",
"import org.mockito.Mockito;",
"import com.google.errorprone.annotations.DoNotMock;",
"import java.lang.annotation.Inherited;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.RetentionPolicy;",
"class DoNotMockObjects {",
"",
" class MockableObject {}",
" @DoNotMock(\"" + DO_NOT_MOCK_REASON + "\") class DoNotMockObject {",
" DoNotMockObject(String s) {}",
" DoNotMockObject() {}",
" }",
" @DoNotMock(\"\") class OtherDoNotMockObject {}",
"",
" @Inherited",
" @DoNotMock(\"" + DO_NOT_MOCK_REASON + "\")",
" @Retention(RetentionPolicy.RUNTIME)",
" @interface MetaDoNotMock {}",
" @MetaDoNotMock static class MetaDoNotMockObject {}",
"",
" @MetaDoNotMock @Retention(RetentionPolicy.RUNTIME)",
" @interface DoubleMetaDoNotMock {}",
" @DoubleMetaDoNotMock static class DoubleMetaAnnotatedDoNotMock {}",
"",
" class ExtendsDoNotMockObject extends DoNotMockObject {}",
" class ExtendsMetaDoNotMockObject extends MetaDoNotMockObject {}",
"",
" @DoNotMock(\"" + DO_NOT_MOCK_REASON + "\") interface DoNotMockInterface {}",
" @MetaDoNotMock interface MetaDoNotMockInterface {}",
" class ImplementsDoNotMockInterfaceObject implements DoNotMockInterface {}",
" class ImplementsMetaDoNotMockInterfaceObject",
" implements MetaDoNotMockInterface {} ",
"}");
@Test
public void matchesMockitoDotMock_doNotMock() {
testHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"import org.mockito.Mockito;",
"import lib.DoNotMockObjects.*;",
"class Lib {",
"",
" public static void f() { ",
" Mockito.spy(MockableObject.class);",
"// BUG: Diagnostic contains: "
+ String.format(
"Do not mock '%s'; %s is annotated as @DoNotMock: %s",
"lib.DoNotMockObjects.DoNotMockObject",
"lib.DoNotMockObjects.DoNotMockObject",
DO_NOT_MOCK_REASON),
" Mockito.mock(DoNotMockObject.class);",
"// BUG: Diagnostic contains: "
+ String.format(
"Do not mock '%s'; %s is annotated as @DoNotMock: %s",
"lib.DoNotMockObjects.OtherDoNotMockObject",
"lib.DoNotMockObjects.OtherDoNotMockObject",
"It is annotated as DoNotMock."),
" Mockito.spy(OtherDoNotMockObject.class);",
" }",
"}")
.doTest();
}
@Test
public void matchesMockitoMockAnnotation_doNotMock() {
testHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"import org.mockito.Mock;",
"import org.mockito.Spy;",
"import lib.DoNotMockObjects.*;",
"class Lib {",
"",
" @Mock MockableObject mockableObject;",
" // BUG: Diagnostic contains: "
+ String.format(
"Do not mock '%s'; %s is annotated as @DoNotMock: %s",
"lib.DoNotMockObjects.DoNotMockObject",
"lib.DoNotMockObjects.DoNotMockObject",
DO_NOT_MOCK_REASON),
" @Mock DoNotMockObject unmockableObject;",
" // BUG: Diagnostic contains: "
+ String.format(
"Do not mock '%s'; %s is annotated as @DoNotMock: %s",
"lib.DoNotMockObjects.DoNotMockInterface",
"lib.DoNotMockObjects.DoNotMockInterface",
DO_NOT_MOCK_REASON),
" @Mock DoNotMockInterface doNotMockInterface;",
" @Spy MockableObject unspyableObject;",
" // BUG: Diagnostic contains:",
" @Spy DoNotMockObject spyableObject;",
"}")
.doTest();
}
@Test
public void matchesMockAnnotation_doNotMock_extends() {
testHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"import org.mockito.Mock;",
"import org.mockito.Spy;",
"import lib.DoNotMockObjects.*;",
"class Lib {",
"",
" // BUG: Diagnostic contains: "
+ String.format(
"Do not mock '%s' (which is-a '%s'); %s is annotated as @DoNotMock: %s.",
"lib.DoNotMockObjects.ExtendsDoNotMockObject",
"lib.DoNotMockObjects.DoNotMockObject",
"lib.DoNotMockObjects.DoNotMockObject",
DO_NOT_MOCK_REASON),
" @Mock ExtendsDoNotMockObject extendsDoNotMockObject;",
" // BUG: Diagnostic contains: "
+ String.format(
"Do not mock '%s' (which is-a '%s'); %s",
"lib.DoNotMockObjects.ExtendsMetaDoNotMockObject",
"lib.DoNotMockObjects.MetaDoNotMockObject",
String.format(
"%s is annotated as @%s (which is annotated as @DoNotMock): %s",
"lib.DoNotMockObjects.MetaDoNotMockObject",
"lib.DoNotMockObjects.MetaDoNotMock",
DO_NOT_MOCK_REASON)),
" @Mock ExtendsMetaDoNotMockObject extendsMetaDoNotMockObject;",
" @Mock MockableObject mockableObject;",
"}")
.doTest();
}
@Test
public void matchesMockAnnotation_doNotMock_implements() {
testHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"import org.mockito.Mock;",
"import org.mockito.Spy;",
"import lib.DoNotMockObjects.*;",
"class Lib {",
"",
" // BUG: Diagnostic contains: "
+ String.format(
"Do not mock '%s' (which is-a '%s'); %s is annotated as @DoNotMock: %s.",
"lib.DoNotMockObjects.ImplementsDoNotMockInterfaceObject",
"lib.DoNotMockObjects.DoNotMockInterface",
"lib.DoNotMockObjects.DoNotMockInterface",
DO_NOT_MOCK_REASON),
" @Mock ImplementsDoNotMockInterfaceObject implementsDoNotMockInterfaceObject;",
" // BUG: Diagnostic contains: "
+ String.format(
"Do not mock '%s' (which is-a '%s'); %s",
"lib.DoNotMockObjects.ImplementsMetaDoNotMockInterfaceObject",
"lib.DoNotMockObjects.MetaDoNotMockInterface",
String.format(
"%s is annotated as @%s (which is annotated as @DoNotMock): %s",
"lib.DoNotMockObjects.MetaDoNotMockInterface",
"lib.DoNotMockObjects.MetaDoNotMock",
DO_NOT_MOCK_REASON)),
" @Mock ImplementsMetaDoNotMockInterfaceObject"
+ " implementsMetaDoNotMockInterfaceObject;",
" @Mock MockableObject mockableObject;",
"}")
.doTest();
}
@Test
public void matchesMockAnnotation_metaDoNotMock() {
testHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"import org.mockito.Mock;",
"import lib.DoNotMockObjects.*;",
"class Lib {",
"",
" // BUG: Diagnostic contains:",
" @Mock MetaDoNotMockObject metaAnnotatedDoNotMockObject;",
" // BUG: Diagnostic contains:",
" @Mock MetaDoNotMockInterface metaDoNotMockInterface;",
" @Mock MockableObject mockableObject;",
" @Mock DoubleMetaAnnotatedDoNotMock doubleMetaAnnotatedDoNotMock; // mockable",
"}")
.doTest();
}
@Test
public void matchesMockitoDotMock_autoValue() {
testHelper
.addSourceLines(
"lib/Lib.java",
"package lib;",
"import org.mockito.Mockito;",
"import lib.AutoValueObjects.*;",
"public class Lib {",
"",
" class MockableObject {}",
"",
" public static void f() { ",
" Mockito.mock(MockableObject.class);",
" // BUG: Diagnostic contains:",
" Mockito.mock(DoNotMockMyAutoValue.class);",
" Mockito.mock(MyAutoValue.class);",
" MyAutoValue myAutoValue = MyAutoValue.create(1);",
" DoNotMockMyAutoValue doNotMockMyAutoValue = DoNotMockMyAutoValue.create(1);",
" }",
"}")
.addSourceLines(
"lib/MyAutoValue.java",
"package lib;",
"import com.google.auto.value.AutoValue;",
"import com.google.errorprone.annotations.DoNotMock;",
"class AutoValueObjects {",
" @DoNotMock(\"" + DO_NOT_MOCK_REASON + "\")",
" @AutoValue public abstract static class DoNotMockMyAutoValue {",
" public abstract int getFoo();",
" static DoNotMockMyAutoValue create(int foo) {",
" return new AutoValue_AutoValueObjects_DoNotMockMyAutoValue(foo);",
" }",
" }",
" @AutoValue public abstract static class MyAutoValue {",
" public abstract int getBar();",
" static MyAutoValue create(int bar) {",
" return new AutoValue_AutoValueObjects_MyAutoValue(bar);",
" }",
" }",
"}")
.setArgs(ImmutableList.of("-processor", AutoValueProcessor.class.getName()))
.doTest();
}
@Test
public void typaram() {
CompilationTestHelper.newInstance(DoNotMockChecker.class, getClass())
.addSourceLines(
"Test.java",
"import org.mockito.Mockito;",
"import org.mockito.Mock;",
"class Test<E> {",
" @Mock E e;",
" <T> T f(T x) {",
" T m = Mockito.spy(x);",
" return m;",
" }",
"}")
.doTest();
}
@Test
public void rawClass() {
CompilationTestHelper.newInstance(DoNotMockChecker.class, getClass())
.addSourceLines(
"Test.java",
"import org.mockito.Mockito;",
"class Test {",
" <T> T evil(Class<T> clazz) {",
" return (T) Mockito.mock((Class) clazz);",
" }",
"}")
.doTest();
}
@Test
public void mockArray() {
CompilationTestHelper.newInstance(DoNotMockChecker.class, getClass())
.addSourceLines(
"Test.java",
"import java.lang.annotation.Annotation;",
"import org.mockito.Mock;",
"class Test {",
" @Mock Annotation[] annotations;",
"}")
.doTest();
}
/** Example meta-annotation to put on the test's classpath. */
@Retention(RUNTIME)
@DoNotMock("unmockable")
public @interface AnnotationWithDoNotMock {}
/** An example usage of this meta-annotation. */
@AnnotationWithDoNotMock
public static class AnnotatedClass {}
// test the check's behaviour if a mocked type is annotated, but the annotation's classfile
// is missing from the compilation classpath
@Test
public void noMetaAnnotationIncompleteClasspath() {
CompilationTestHelper.newInstance(DoNotMockChecker.class, getClass())
.addSourceLines(
"Test.java",
"import " + AnnotatedClass.class.getCanonicalName() + ";",
"import org.mockito.Mock;",
"class Test {",
" @Mock AnnotatedClass x;",
"}")
.withClasspath(
AnnotatedClass.class, DoNotMockCheckerTest.class, DoNotMock.class, Mock.class)
.doTest();
}
}
| 13,829
| 38.401709
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ForOverrideCheckerTest.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@code ForOverrideChecker}. */
@RunWith(JUnit4.class)
public class ForOverrideCheckerTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ForOverrideChecker.class, getClass())
.addSourceLines(
"test/ExtendMe.java",
"package test;",
"import com.google.errorprone.annotations.ForOverride;",
"public class ExtendMe {",
" @ForOverride",
" protected int overrideMe() { return 1; }",
" @ForOverride",
" protected int overrideMe(int a) { return 1; }",
"",
" public final void callMe() {",
" overrideMe();",
" }",
"}");
@Test
public void canApplyForOverrideToProtectedMethod() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"import com.google.errorprone.annotations.ForOverride;",
"public class Test {",
" @ForOverride protected void myMethod() {}",
"}")
.doTest();
}
@Test
public void canApplyForOverrideToPackagePrivateMethod() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"import com.google.errorprone.annotations.ForOverride;",
"public class Test {",
" @ForOverride void myMethod() {}",
"}")
.doTest();
}
@Test
public void cannotApplyForOverrideToPublicMethod() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"import com.google.errorprone.annotations.ForOverride;",
"public class Test {",
" // BUG: Diagnostic contains: @ForOverride must have protected or package-private"
+ " visibility",
" @ForOverride public void myMethod() {}",
"}")
.doTest();
}
@Test
public void cannotApplyForOverrideToPrivateMethod() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"import com.google.errorprone.annotations.ForOverride;",
"public class Test {",
" // BUG: Diagnostic contains: @ForOverride must have protected or package-private"
+ " visibility",
" @ForOverride private void myMethod() {}",
"}")
.doTest();
}
@Test
public void cannotApplyForOverrideToInterfaceMethod() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"import com.google.errorprone.annotations.ForOverride;",
"public interface Test {",
" // BUG: Diagnostic contains: @ForOverride must have protected or package-private"
+ " visibility",
" @ForOverride void myMethod();",
"}")
.doTest();
}
@Test
public void userCanCallAppropriateMethod() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"public class Test extends test.ExtendMe {",
" public void googleyMethod() {",
" callMe();",
" }",
"}")
.doTest();
}
@Test
public void userInSamePackageCannotCallMethod() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"public class Test {",
" public void tryCall() {",
" ExtendMe extendMe = new ExtendMe();",
" // BUG: Diagnostic contains: must not be invoked",
" extendMe.overrideMe();",
" }",
"}")
.doTest();
}
@Test
public void userCannotCallDefault() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"public class Test extends test.ExtendMe {",
" public void circumventer() {",
" // BUG: Diagnostic contains: must not be invoked",
" overrideMe();",
" }",
"}")
.doTest();
}
@Test
public void userCannotCallOverridden() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test2;",
"public class Test extends test.ExtendMe {",
" @Override",
" protected int overrideMe() {",
" System.err.println(\"Capybaras are semi-aquatic.\");",
" return 1;",
" }",
" public void circumventer() {",
" // BUG: Diagnostic contains: must not be invoked",
" overrideMe();",
" }",
"}")
.doTest();
}
@Test
public void userCanCallSuperFromOverridden() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test2;",
"public class Test extends test.ExtendMe {",
" @Override",
" protected int overrideMe() {",
" return super.overrideMe();",
" }",
"}")
.doTest();
}
@Test
public void userCanCallSuperFromOverridden_explicitQualification() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test2;",
"public class Test extends test.ExtendMe {",
" @Override",
" protected int overrideMe() {",
// This is identical to the above, with a slightly less common explicit qualification
" return Test.super.overrideMe();",
" }",
"}")
.doTest();
}
@Test
public void userCannotCallSuperFromNonOverriddenMethod() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test2;",
"public class Test extends test.ExtendMe {",
" protected void circumventer() {",
" // BUG: Diagnostic contains: must not be invoked",
" super.overrideMe();",
" }",
"}")
.doTest();
}
@Test
public void userCannotCallSuperFromFieldInitializer() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test2;",
"public class Test extends test.ExtendMe {",
" // BUG: Diagnostic contains: must not be invoked",
" private final int k = super.overrideMe();",
"}")
.doTest();
}
@Test
public void userCannotCallSuperFromAnonymousInnerClassInOverride() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test2;",
"public class Test extends test.ExtendMe {",
" @Override",
" protected int overrideMe() {",
" return new Object() {",
" // BUG: Diagnostic contains: must not be invoked",
" final int k = Test.super.overrideMe();",
"",
" int foo() {",
" // BUG: Diagnostic contains: must not be invoked",
" return Test.super.overrideMe();",
" }",
" }.foo();",
" }",
"}")
.doTest();
}
@Test
public void userCannotMakeMethodPublic() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test2;",
"public class Test extends test.ExtendMe {",
" // BUG: Diagnostic contains: overrides @ForOverride method test.ExtendMe.overrideMe",
" public int overrideMe() {",
" return 1;",
" }",
" // BUG: Diagnostic contains: overrides @ForOverride method test.ExtendMe.overrideMe",
" public int overrideMe(int a) {",
" return 1;",
" }",
"}")
.doTest();
}
@Test
public void definerCanCallFromInnerClass() {
compilationHelper
.addSourceLines(
"test/OuterClass.java",
"package test;",
"import com.google.errorprone.annotations.ForOverride;",
"public class OuterClass {",
" @ForOverride",
" protected void forOverride() { }",
" private class InnerClass {",
" void invoke() {",
" forOverride();",
" }",
" }",
"}")
.doTest();
}
@Test
public void definerCanCallFromAnonymousInnerClass() {
compilationHelper
.addSourceLines(
"test/OuterClass.java",
"package test;",
"import com.google.errorprone.annotations.ForOverride;",
"public class OuterClass {",
" @ForOverride",
" protected void forOverride() { }",
" public Runnable getRunner() {",
" return new Runnable() {",
" public void run() {",
" forOverride();",
" }",
" };",
" }",
"}")
.doTest();
}
}
| 10,056
| 30.232919
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ThrowNullTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ThrowNull}Test */
@RunWith(JUnit4.class)
public class ThrowNullTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(ThrowNull.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: throw new NullPointerException();",
" throw null;",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" void f() {",
" throw new NullPointerException();",
" }",
"}")
.doTest();
}
}
| 1,604
| 26.672414
| 81
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AutoValueSubclassLeakedTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.auto.value.processor.AutoValueProcessor;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link AutoValueSubclassLeaked}. */
@RunWith(JUnit4.class)
public final class AutoValueSubclassLeakedTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(AutoValueSubclassLeaked.class, getClass())
.setArgs(ImmutableList.of("-processor", AutoValueProcessor.class.getName()));
@Test
public void positive() {
helper
.addSourceLines(
"Test.java",
"package test;",
"import com.google.auto.value.AutoValue;",
"class Test {",
" @AutoValue",
" abstract static class Foo {",
" abstract int foo();",
" }",
"}")
.addSourceLines(
"Bar.java",
"package test;",
"class Bar {",
" public static Test.Foo create(int i) {",
" // BUG: Diagnostic contains:",
" return new AutoValue_Test_Foo(i);",
" }",
"}")
.doTest();
}
@Test
public void negativeBuilder() {
helper
.addSourceLines(
"Test.java",
"package test;",
"import com.google.auto.value.AutoValue;",
"class Test {",
" @AutoValue",
" abstract static class Foo {",
" abstract int foo();",
" @AutoValue.Builder",
" abstract static class Builder {",
" abstract Builder setFoo(int i);",
" abstract Foo build();",
" }",
" public static Builder builder() {",
" return new AutoValue_Test_Foo.Builder();",
" }",
" }",
"}")
.doTest();
}
@Test
public void negative() {
helper
.addSourceLines(
"Test.java",
"package test;",
"import com.google.auto.value.AutoValue;",
"class Test {",
" @AutoValue",
" abstract static class Foo {",
" abstract int foo();",
" public static Foo create(int i) {",
" return new AutoValue_Test_Foo(i);",
" }",
" }",
"}")
.doTest();
}
@Test
public void generatedCode() {
helper
.addSourceLines(
"Test.java",
"package test;",
"import com.google.auto.value.AutoValue;",
"class Test {",
" @AutoValue",
" abstract static class Foo {",
" abstract int foo();",
" }",
"}")
.addSourceLines(
"Bar.java",
"package test;",
"import javax.annotation.processing.Generated;",
"",
"@Generated(\"generator\")",
"class Bar {",
" public static Test.Foo create(int i) {",
" return new AutoValue_Test_Foo(i);",
" }",
"}")
.doTest();
}
}
| 3,913
| 29.578125
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnicodeDirectionalityCharactersTest.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link UnicodeDirectionalityCharacters}. */
@RunWith(JUnit4.class)
public final class UnicodeDirectionalityCharactersTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(UnicodeDirectionalityCharacters.class, getClass());
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(
UnicodeDirectionalityCharacters.class, getClass());
@Test
public void negative() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" final int noUnicodeHereBoss = 1;",
"}")
.doTest();
}
@Test
public void positive() {
helper
.addSourceLines(
"Test.java", //
"// BUG: Diagnostic contains:",
"/** \u202A */",
"class Test {",
" final int noUnicodeHereBoss = 1;",
"}")
.doTest();
}
@Test
public void refactoring() {
refactoring
.addInputLines(
"Test.java", //
"// BUG: Diagnostic contains:",
"/** \u202A */",
"class Test {",
" final int noUnicodeHereBoss = 1;",
"}")
.addOutputLines(
"Test.java", //
"// BUG: Diagnostic contains:",
"/** \\u202A */",
"class Test {",
" final int noUnicodeHereBoss = 1;",
"}")
.doTest();
}
}
| 2,340
| 29.012821
| 91
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeStaticTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static org.junit.Assume.assumeTrue;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.util.RuntimeVersion;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link FieldCanBeStatic}Test */
@RunWith(JUnit4.class)
public class FieldCanBeStaticTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(FieldCanBeStatic.class, getClass());
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FieldCanBeStatic.class, getClass());
@Test
public void simpleCase() {
helper
.addInputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private final Duration myDuration = Duration.ofMillis(1);",
" public Duration d() {",
" return this.myDuration;",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private static final Duration MY_DURATION = Duration.ofMillis(1);",
" public Duration d() {",
" return MY_DURATION;",
" }",
"}")
.doTest();
}
@Test
public void instantWithPureMethod() {
helper
.addInputLines(
"Test.java",
"import java.time.Instant;",
"class Test {",
" private final Instant instant = Instant.ofEpochMilli(1);",
"}")
.addOutputLines(
"Test.java",
"import java.time.Instant;",
"class Test {",
" private static final Instant INSTANT = Instant.ofEpochMilli(1);",
"}")
.doTest();
}
@Test
public void instantWithNonPureMethod() {
helper
.addInputLines(
"Test.java",
"import java.time.Instant;",
"class Test {",
" private final Instant instant = Instant.now();",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void refersToStaticVariable() {
helper
.addInputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private static final int millis = 1;",
" private final Duration myDuration = Duration.ofMillis(millis);",
" public Duration d() {",
" return this.myDuration;",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private static final int millis = 1;",
" private static final Duration MY_DURATION = Duration.ofMillis(millis);",
" public Duration d() {",
" return MY_DURATION;",
" }",
"}")
.doTest();
}
@Test
public void refersToInstanceVariable() {
helper
.addInputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" final int millis = 1;",
" private final Duration myDuration = Duration.ofMillis(millis);",
" public Duration d() {",
" return this.myDuration;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void notPrivate_noMatch() {
helper
.addInputLines(
"Test.java", //
"import java.time.Duration;",
"class Test {",
" public final Duration d = Duration.ofMillis(1);",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void notFinal_noMatch() {
helper
.addInputLines(
"Test.java", //
"import java.time.Duration;",
"class Test {",
" private Duration d = Duration.ofMillis(1);",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void exemptedAnnotation_noMatch() {
helper
.addInputLines(
"Test.java",
"import com.google.inject.testing.fieldbinder.Bind;",
"import java.time.Duration;",
"class Test {",
" @Bind private final Duration d = Duration.ofMillis(1);",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void possibleImpureInitializer_noMatch() {
helper
.addInputLines(
"Test.java", //
"import java.time.Duration;",
"class Test {",
" private final Duration d = getDuration();",
" Duration getDuration() {",
" return null;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains:",
" private final int primitive = 3;",
" // BUG: Diagnostic contains:",
" private final String string = \"string\";",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" private static final String staticFinalInitializer;",
" static {",
" staticFinalInitializer = \"string\";",
" }",
" private static final String staticFinal = \"string\";",
" private int nonFinal = 3;",
" private static int staticNonFinal = 4;",
" private final Object finalMutable = new Object();",
" private final int nonLiteral = new java.util.Random().nextInt();",
" private final Person pojo = new Person(\"Bob\", 42);",
" private static class Person {",
" final String name;",
" final int age;",
" Person(String name, int age) {",
" this.name = name;",
" this.age = age;",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactoring() {
helper
.addInputLines(
"Test.java",
"class Test {",
" private final int foo = 1;",
" private final int BAR_FIELD = 2;",
" int f() {",
" return foo + BAR_FIELD;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" private static final int FOO = 1;",
" private static final int BAR_FIELD = 2;",
" int f() {",
" return FOO + BAR_FIELD;",
" }",
"}")
.doTest();
}
@Test
public void inner() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" class I {",
" private final Duration D = Duration.ofMillis(1);",
" // BUG: Diagnostic contains: can be static",
" private final int I = 42;",
" }",
" static class S {",
" // BUG: Diagnostic contains: can be static",
" private final Duration D = Duration.ofMillis(1);",
" // BUG: Diagnostic contains: can be static",
" private final int I = 42;",
" }",
" void f() {",
" class L {",
" private final Duration D = Duration.ofMillis(1);",
" // BUG: Diagnostic contains: can be static",
" private final int I = 42;",
" }",
" new Object() {",
" private final Duration D = Duration.ofMillis(1);",
" // BUG: Diagnostic contains: can be static",
" private final int I = 42;",
" };",
" }",
"}")
.doTest();
}
@Test
public void record() {
assumeTrue(RuntimeVersion.isAtLeast16());
compilationHelper
.addSourceLines(
"ExampleClass.java",
"package example;",
"public final class ExampleClass {",
" public record OtherRecord(String value) {}",
" public record SomeRecord(OtherRecord value) {",
" public static SomeRecord fromValue(final OtherRecord value) {",
" return new SomeRecord(value);",
" }",
" }",
" private ExampleClass() {",
" }",
"}")
.doTest();
}
@Test
public void instanceFieldsCannotBeStatic() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" private final int foo;",
" Test(int foo) {",
" this.foo = foo;",
" }",
"}")
.doTest();
}
}
| 9,807
| 29.178462
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NamedLikeContextualKeywordTest.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static org.junit.Assume.assumeTrue;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.util.RuntimeVersion;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link NamedLikeContextualKeywordTest}. */
@RunWith(JUnit4.class)
public final class NamedLikeContextualKeywordTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(NamedLikeContextualKeyword.class, getClass());
@Test
public void instanceMethodName_error() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" static Throwable foo;",
" public Test() {",
" }",
" ",
" // BUG: Diagnostic contains: [NamedLikeContextualKeyword]",
" public void yield() { ",
" foo = new NullPointerException(\"uh oh\");",
" }",
"}")
.setArgs(ImmutableList.of("-XepOpt:NamedLikeContextualKeyword:EnableMethodNames"))
.doTest();
}
@Test
public void staticMethodName_error() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" static Throwable foo;",
" public Test() {",
" }",
" ",
" // BUG: Diagnostic contains: [NamedLikeContextualKeyword]",
" public static void yield() { ",
" foo = new NullPointerException(\"uh oh\");",
" }",
"}")
.setArgs(ImmutableList.of("-XepOpt:NamedLikeContextualKeyword:EnableMethodNames"))
.doTest();
}
@Test
public void className_error() {
helper
.addSourceLines(
"module.java",
"// BUG: Diagnostic contains: [NamedLikeContextualKeyword]",
"class module {",
" public module() {",
" }",
"}")
.setArgs(ImmutableList.of("-XepOpt:NamedLikeContextualKeyword:EnableClassNames"))
.doTest();
}
@Test
public void yieldInSwitch_noError() {
assumeTrue(RuntimeVersion.isAtLeast14());
helper
.addSourceLines(
"Test.java",
"class Test {",
" public Test(int foo) {",
" int x = switch(foo) {",
" case 17: ",
" yield 17;",
" default:",
" yield 0;",
" };",
" }",
"}")
.setArgs(
ImmutableList.of(
"-XepOpt:NamedLikeContextualKeyword:EnableMethodNames",
"-XepOpt:NamedLikeContextualKeyword:EnableClassNames"))
.doTest();
}
@Test
public void interfaceImplementation_noError() {
helper
.addSourceLines(
"Test.java",
"class Test implements RegrettablyNamedInterface {",
" static Throwable foo;",
" public Test() {",
" }",
" ",
" public void yield() { ",
" foo = new NullPointerException(\"uh oh\");",
" }",
"}")
.addSourceLines(
"RegrettablyNamedInterface.java",
"interface RegrettablyNamedInterface {",
" @SuppressWarnings(\"NamedLikeContextualKeyword\")",
" void yield();",
"}")
.setArgs(
ImmutableList.of(
"-XepOpt:NamedLikeContextualKeyword:EnableMethodNames",
"-XepOpt:NamedLikeContextualKeyword:EnableClassNames"))
.doTest();
}
@Test
public void nonAnnotatedOverride_noError() {
helper
.addSourceLines(
"Test.java",
"class Test extends RegrettablyNamedClass {",
" static Throwable foo;",
" public Test() {",
" }",
" ",
" public void yield() { ",
" foo = new NullPointerException(\"uh oh\");",
" }",
"}")
.addSourceLines(
"RegrettablyNamedClass.java",
"class RegrettablyNamedClass {",
" @SuppressWarnings(\"NamedLikeContextualKeyword\")",
" void yield() {}",
"}")
.setArgs(
ImmutableList.of(
"-XepOpt:NamedLikeContextualKeyword:EnableMethodNames",
"-XepOpt:NamedLikeContextualKeyword:EnableClassNames"))
.doTest();
}
@Test
public void annotatedOverride_noError() {
helper
.addSourceLines(
"Test.java",
"class Test extends RegrettablyNamedClass {",
" static Throwable foo;",
" public Test() {",
" }",
" ",
" @Override",
" public void yield() { ",
" foo = new NullPointerException(\"uh oh\");",
" }",
"}")
.addSourceLines(
"RegrettablyNamedClass.java",
"class RegrettablyNamedClass {",
" @SuppressWarnings(\"NamedLikeContextualKeyword\")",
" void yield() {}",
"}")
.setArgs(
ImmutableList.of(
"-XepOpt:NamedLikeContextualKeyword:EnableMethodNames",
"-XepOpt:NamedLikeContextualKeyword:EnableClassNames"))
.doTest();
}
@Test
public void positive() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" // BUG: Diagnostic contains: [NamedLikeContextualKeyword]",
" void yield() {}",
" {",
" // BUG: Diagnostic contains: this.yield();",
" yield();",
" }",
"}")
.setArgs(
ImmutableList.of(
"--release",
"11",
"-XepOpt:NamedLikeContextualKeyword:EnableMethodNames",
"-XepOpt:NamedLikeContextualKeyword:EnableClassNames"))
.doTest();
}
@Test
public void enclosing() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" class A {",
" // BUG: Diagnostic contains: [NamedLikeContextualKeyword]",
" void yield() {}",
" class B {",
" class C {",
" {",
" // BUG: Diagnostic contains: A.this.yield();",
" yield();",
" }",
" }",
" }",
" }",
"}")
.setArgs(
ImmutableList.of(
"--release",
"11",
"-XepOpt:NamedLikeContextualKeyword:EnableMethodNames",
"-XepOpt:NamedLikeContextualKeyword:EnableClassNames"))
.doTest();
}
@Test
public void staticMethod() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: [NamedLikeContextualKeyword]",
" static void yield() {}",
" static class I {",
" {",
" // BUG: Diagnostic contains: Test.yield();",
" yield();",
" }",
" }",
"}")
.setArgs(
ImmutableList.of(
"--release",
"11",
"-XepOpt:NamedLikeContextualKeyword:EnableMethodNames",
"-XepOpt:NamedLikeContextualKeyword:EnableClassNames"))
.doTest();
}
}
| 8,247
| 30.007519
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ImmutableSetForContainsTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ImmutableSetForContains}. */
@RunWith(JUnit4.class)
public final class ImmutableSetForContainsTest {
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(ImmutableSetForContains.class, getClass());
@Test
public void immutableListOf_onlyContainsReplaces() {
refactoringHelper
.addInputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST_1 =",
" ImmutableList.<String>builder().add(\"hello\").build();",
" private static final ImmutableList<String> MY_LIST_2 = ImmutableList.of(\"hello\");",
" private static final ImmutableList<String> MY_LIST_3 =",
" new ArrayList<String>().stream().collect(toImmutableList());",
" private static final ImmutableList<String> MY_LIST_4 =",
" new ImmutableList.Builder<String>().add(\"hello\").build();",
" private void myFunc() {",
" boolean myBool1 = MY_LIST_1.contains(\"he\");",
" boolean myBool2 = MY_LIST_2.containsAll(new ArrayList<String>());",
" boolean myBool3 = MY_LIST_3.isEmpty();",
" boolean myBool4 = MY_LIST_4.isEmpty();",
" }",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import static com.google.common.collect.ImmutableSet.toImmutableSet;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableSet<String> MY_LIST_1 =",
" ImmutableSet.<String>builder().add(\"hello\").build();",
" private static final ImmutableSet<String> MY_LIST_2 = ImmutableSet.of(\"hello\");",
" private static final ImmutableSet<String> MY_LIST_3 =",
" new ArrayList<String>().stream().collect(toImmutableSet());",
" private static final ImmutableSet<String> MY_LIST_4 =",
" new ImmutableSet.Builder<String>().add(\"hello\").build();",
" private void myFunc() {",
" boolean myBool1 = MY_LIST_1.contains(\"he\");",
" boolean myBool2 = MY_LIST_2.containsAll(new ArrayList<String>());",
" boolean myBool3 = MY_LIST_3.isEmpty();",
" boolean myBool4 = MY_LIST_4.isEmpty();",
" }",
"}")
.doTest();
}
@Test
public void immutableList_initUsingStaticFunc_replacesWithCopyOf() {
refactoringHelper
.addInputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = initMyList();",
" private static ImmutableList<String> initMyList() {",
" return ImmutableList.of();",
" }",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableSet<String> MY_LIST = ",
" ImmutableSet.copyOf(initMyList());",
" private static ImmutableList<String> initMyList() {",
" return ImmutableList.of();",
" }",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.doTest();
}
@Test
public void immutableList_rawType_replacesWithImmutableSet() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableSet MY_LIST = ImmutableSet.of(\"hello\");",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.doTest();
}
@Test
public void fieldAnnotatedWithBind_noMatch() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.inject.testing.fieldbinder.Bind;",
"import java.util.ArrayList;",
"class Test {",
" @Bind",
" private static final ImmutableList MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableVarPassedToAFunc_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" consumer(MY_LIST);",
" }",
" private void consumer(ImmutableList<String> arg) {",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_uniqueElements_iterating_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION;",
"import com.google.common.collect.ImmutableList;",
"import com.sun.source.tree.Tree.Kind;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> STR_LIST = ImmutableList.of(\"hello\");",
" private static final ImmutableList<Kind> ENUM_LIST =",
" ImmutableList.of(Kind.AND, METHOD_INVOCATION);",
" private void myFunc() {",
" STR_LIST.stream().forEach(System.out::println);",
" STR_LIST.forEach(System.out::println);",
" ENUM_LIST.stream().forEach(System.out::println);",
" ENUM_LIST.forEach(System.out::println);",
" for (String myStr : STR_LIST) { System.out.println(myStr); }",
" for (Kind myKind : ENUM_LIST) { System.out.println(myKind); }",
" for (Long lvar : ImmutableList.<Long>of(2L)) { System.out.println(lvar); }",
" ImmutableList<Long> longList = ImmutableList.of(1L);",
" for (Long lvar : longList) { System.out.println(lvar); }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_duplicateElements_iterating_doesNotReplace() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> STR_LIST_1 = ",
" ImmutableList.of(\"hello\", \"hello\");",
" private static final ImmutableList<String> STR_LIST_2 = ",
" ImmutableList.of(\"hello\", strGenFunc());",
" private void myFunc() {",
" STR_LIST_1.stream().forEach(System.out::println);",
" STR_LIST_2.stream().forEach(System.out::println);",
" }",
" private static String strGenFunc() { return \"\"; }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_distinctElementsInBuilder_iterating_doesNotReplace() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> STR_LIST = ",
" ImmutableList.<String>builder().add(\"hello\").build();",
" private void myFunc() {",
" STR_LIST.stream().forEach(System.out::println);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_passedToFunctionsAcceptingSet_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.Iterables;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" ImmutableSet<String> mySet = ImmutableSet.copyOf(MY_LIST);",
" String onlyElement = Iterables.getOnlyElement(MY_LIST);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_passedToGenericFunctionAcceptingList_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.Iterables;",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" private static final ImmutableList<String> MY_LIST_1 = ImmutableList.of(\"hello\");",
" private static final ImmutableList<String> MY_LIST_2 = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" ImmutableMap<String, List<String>> myMap = ",
" ImmutableMap.<String, List<String>>builder().put(\"a\", MY_LIST_1).build();",
" boolean myBool = ImmutableList.of().equals(MY_LIST_2);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_uniqueElements_inLoopExprAndStatement_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" for (String myStr : MY_LIST) {",
" System.out.println(MY_LIST.indexOf(myStr));",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableListInNestedClass_usedInParentClass_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" private static final class Nested {",
" private static final ImmutableList<String> MY_LIST_1 = ImmutableList.of(\"a\");",
" private static final ImmutableList<String> MY_LIST_2 = ImmutableList.of(\"b\");",
" }",
" private void myFunc() {",
" String one = Nested.MY_LIST_1.get(0);",
" String two = Nested.MY_LIST_2.iterator().next();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void twoImmutableListsUsedInSameMethodInvocation_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST_1 = ImmutableList.of(\"hello\");",
" private static final ImmutableList<String> MY_LIST_2 = ImmutableList.of(\"world\");",
" private void myFunc() {",
" MY_LIST_1.forEach(elem -> System.out.println(MY_LIST_2.get(0)));",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void listOfClassOrDistinctInstances_uniqueElements_iterating_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION;",
"import com.google.common.collect.ImmutableList;",
"import com.sun.source.tree.Tree.Kind;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<Class<?>> CLS_LIST = ",
" ImmutableList.of(Long.class, Double.class);",
" private static final ImmutableList<Object> OBJ_LIST =",
" ImmutableList.of(new String(\"\"), new Object());",
" private void myFunc() {",
" CLS_LIST.stream().forEach(System.out::println);",
" OBJ_LIST.forEach(System.out::println);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableListGetInVarArg_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = ImmutableList.of(\"hello\");",
" private String myFunc() {",
" return String.format(\"%s\", MY_LIST.get(0));",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void suppressionOnVariableTree_noFinding() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" @SuppressWarnings(\"ImmutableSetForContains\")",
" private static final ImmutableList<String> MY_LIST_1 =",
" ImmutableList.<String>builder().add(\"hello\").build();",
" private void myFunc() {",
" boolean myBool1 = MY_LIST_1.contains(\"he\");",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| 16,525
| 39.804938
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MissingFailTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers.FIRST;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for the missing fail matcher. */
@RunWith(JUnit4.class)
public class MissingFailTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(MissingFail.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(MissingFail.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("MissingFailPositiveCases.java").doTest();
}
@Test
public void positiveCases2() {
compilationHelper.addSourceFile("MissingFailPositiveCases2.java").doTest();
}
@Test
public void positiveCases3() {
compilationHelper.addSourceFile("MissingFailPositiveCases3.java").doTest();
}
@Test
public void negativeCases() {
compilationHelper.addSourceFile("MissingFailNegativeCases.java").doTest();
}
@Test
public void negativeCases2() {
compilationHelper.addSourceFile("MissingFailNegativeCases2.java").doTest();
}
@Test
public void failImport() {
BugCheckerRefactoringTestHelper.newInstance(MissingFail.class, getClass())
.addInputLines(
"test/A.java",
"package test;",
"import junit.framework.TestCase;",
"public class A extends TestCase {",
" public void testMethod() {",
" try {",
" new String();",
" } catch (IllegalArgumentException expected) {}",
" }",
"}")
.addOutputLines(
"test/A.java",
"package test;",
"import static org.junit.Assert.fail;",
"import junit.framework.TestCase;",
"public class A extends TestCase {",
" public void testMethod() {",
" try {",
" new String();",
" fail(\"Expected IllegalArgumentException\");",
" } catch (IllegalArgumentException expected) {}",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void failMessageMultiCatch() {
BugCheckerRefactoringTestHelper.newInstance(MissingFail.class, getClass())
.addInputLines(
"test/A.java",
"package test;",
"import junit.framework.TestCase;",
"public class A extends TestCase {",
" public void testMethod() {",
" try {",
" new String();",
" } catch (IllegalArgumentException | IllegalStateException expected) {}",
" }",
"}")
.addOutputLines(
"test/A.java",
"package test;",
"import static org.junit.Assert.fail;",
"import junit.framework.TestCase;",
"public class A extends TestCase {",
" public void testMethod() {",
" try {",
" new String();",
" fail(\"Expected Exception\");",
" } catch (IllegalArgumentException | IllegalStateException expected) {}",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
// verify that exceptions not named 'expected' are ignored
@Test
public void toleratedException() {
compilationHelper
.addSourceLines(
"test/A.java",
"package test;",
"import junit.framework.TestCase;",
"public class A extends TestCase {",
" public void testMethod() {",
" try {",
" new String();",
" } catch (IllegalArgumentException | IllegalStateException tolerated) {}",
" }",
"}")
.doTest();
}
// verify that exceptions not named 'expected' are ignored
@Test
public void toleratedExceptionWithAssert() {
compilationHelper
.addSourceLines(
"test/A.java",
"package test;",
"import junit.framework.TestCase;",
"public class A extends TestCase {",
" public void testMethod() {",
" try {",
" new String();",
" } catch (IllegalArgumentException | IllegalStateException tolerated) {",
" assertDummy();",
" }",
" }",
" static void assertDummy() {}",
"}")
.doTest();
}
@Test
public void assertThrowsCatchBlock() {
refactoringHelper
.addInputLines(
"in/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Test;",
"class ExceptionTest {",
" @Test",
" public void f() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" try {",
" Files.readAllBytes(p);",
" Files.readAllBytes(p);",
" } catch (IOException e) {",
" assertThat(e).hasMessageThat().contains(\"NOSUCH\");",
" }",
" }",
" @Test",
" public void g() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" try {",
" Files.readAllBytes(p);",
" } catch (IOException e) {",
" assertThat(e).hasMessageThat().contains(\"NOSUCH\");",
" }",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static com.google.common.truth.Truth.assertThat;",
"import static org.junit.Assert.assertThrows;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Test;",
"class ExceptionTest {",
" @Test",
" public void f() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" IOException e = assertThrows(IOException.class, () -> {",
" Files.readAllBytes(p);",
" Files.readAllBytes(p);",
" });",
" assertThat(e).hasMessageThat().contains(\"NOSUCH\");",
" }",
" @Test",
" public void g() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" IOException e = assertThrows(IOException.class, () -> Files.readAllBytes(p));",
" assertThat(e).hasMessageThat().contains(\"NOSUCH\");",
" }",
"}")
.setFixChooser(FIRST)
.doTest();
}
@Test
public void assertThrowsEmptyCatch() {
refactoringHelper
.addInputLines(
"in/ExceptionTest.java",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Test;",
"class ExceptionTest {",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" try {",
" Files.readAllBytes(p);",
" } catch (IOException expected) {",
" }",
" }",
"}")
.addOutputLines(
"out/ExceptionTest.java",
"import static org.junit.Assert.assertThrows;",
"import java.io.IOException;",
"import java.nio.file.*;",
"import org.junit.Test;",
"class ExceptionTest {",
" @Test",
" public void test() throws Exception {",
" Path p = Paths.get(\"NOSUCH\");",
" assertThrows(IOException.class, () -> Files.readAllBytes(p));",
" }",
"}")
.setFixChooser(FIRST)
.doTest();
}
@Test
public void emptyTry() {
refactoringHelper
.addInputLines(
"in/ExceptionTest.java",
"import java.io.IOException;",
"import org.junit.Test;",
"abstract class ExceptionTest {",
" abstract AutoCloseable c();",
" @Test",
" public void test() {",
" try (AutoCloseable c = c()) {",
" } catch (Exception expected) {",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void noEnclosingMethod() {
refactoringHelper
.addInputLines(
"in/ExceptionTest.java",
"import java.io.IOException;",
"import org.junit.Test;",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(JUnit4.class)",
"abstract class ExceptionTest {",
" abstract void c();",
" {",
" try {",
" c();",
" } catch (Exception expected) {",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| 10,097
| 32.885906
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AssertThrowsMultipleStatementsTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link AssertThrowsMultipleStatements}Test */
@RunWith(JUnit4.class)
public class AssertThrowsMultipleStatementsTest {
private final BugCheckerRefactoringTestHelper compilationHelper =
BugCheckerRefactoringTestHelper.newInstance(AssertThrowsMultipleStatements.class, getClass());
@Test
public void ignoreInThrowingRunnables() {
compilationHelper
.addInputLines(
"Test.java",
"import static org.junit.Assert.assertThrows;",
"class Test {",
" void f() {",
" assertThrows(IllegalStateException.class, () -> {",
" System.err.println();",
" });",
" IllegalStateException e = assertThrows(IllegalStateException.class, () -> {",
" System.err.println(1);",
" System.err.println(2);",
" });",
" assertThrows(IllegalStateException.class, () -> {",
" int x = 2;",
" int y = x;",
" });",
" }",
"}")
.addOutputLines(
"Test.java",
"import static org.junit.Assert.assertThrows;",
"class Test {",
" void f() {",
" assertThrows(IllegalStateException.class, () -> {",
" System.err.println();",
" });",
" System.err.println(1);",
" IllegalStateException e = assertThrows(IllegalStateException.class,",
" () -> System.err.println(2));",
" int x = 2;",
" assertThrows(IllegalStateException.class, () -> {",
" int y = x;",
" });",
" }",
"}")
.doTest();
}
}
| 2,548
| 34.402778
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ReachabilityFenceUsageTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ReachabilityFenceUsage}Test */
@RunWith(JUnit4.class)
public final class ReachabilityFenceUsageTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(ReachabilityFenceUsage.class, getClass());
@Test
public void positive() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.lang.ref.Reference;",
"class Test {",
" public void run() {",
" // BUG: Diagnostic contains:",
" Reference.reachabilityFence(this);",
" }",
"}")
.doTest();
}
@Test
public void positive_try() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.lang.ref.Reference;",
"class Test {",
" public void run() {",
" try {",
" // BUG: Diagnostic contains:",
" Reference.reachabilityFence(this);",
" } catch (Exception e) {}",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.lang.ref.Reference;",
"class Test {",
" public void run() {",
" try {",
" } finally {",
" Reference.reachabilityFence(this);",
" }",
" }",
"}")
.doTest();
}
}
| 2,319
| 28
| 82
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NullableOnContainingClassTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link NullableOnContainingClass}. */
@RunWith(JUnit4.class)
public final class NullableOnContainingClassTest {
public final CompilationTestHelper helper =
CompilationTestHelper.newInstance(NullableOnContainingClass.class, getClass());
@Test
public void annotationNotNamedNullable_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static java.lang.annotation.ElementType.TYPE_USE;",
"import java.lang.annotation.Target;",
"class A {",
" @Target(TYPE_USE)",
" @interface Anno {}",
" class B {}",
" void test(@Anno A.B x) {}",
" void test2(A.@Anno B x) {}",
"}")
.doTest();
}
@Test
public void annotationNotExclusivelyTypeUse_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static java.lang.annotation.ElementType.PARAMETER;",
"import static java.lang.annotation.ElementType.TYPE_USE;",
"import java.lang.annotation.Target;",
"class A {",
" @Target({PARAMETER, TYPE_USE})",
" @interface Nullable {}",
" static class B {}",
" void test(@Nullable A.B x) {}",
"}")
.doTest();
}
@Test
public void annotationParameterOnly_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static java.lang.annotation.ElementType.PARAMETER;",
"import java.lang.annotation.Target;",
"class A {",
" @Target(PARAMETER)",
" @interface Nullable {}",
" class B {}",
" void test(@Nullable A.B x) {}",
"}")
.doTest();
}
@Test
public void annotationNamedNullable_annotatingOuterClass() {
helper
.addSourceLines(
"Test.java",
"import static java.lang.annotation.ElementType.TYPE_USE;",
"import java.lang.annotation.Target;",
"import java.util.List;",
"class A {",
" @Target(TYPE_USE)",
" @interface Nullable {}",
" class B {}",
" // BUG: Diagnostic contains: A.@Nullable B",
" void test(@Nullable A.B x) {}",
" // BUG: Diagnostic contains: List< A.@Nullable B>",
" void test2(List<@Nullable A.B> x) {}",
"}")
.doTest();
}
@Test
public void annotationNamedNullable_annotatingOuterClass_canAnnotateTypeParameter() {
helper
.addSourceLines(
"Test.java",
"import static java.lang.annotation.ElementType.TYPE_PARAMETER;",
"import static java.lang.annotation.ElementType.TYPE_USE;",
"import java.lang.annotation.Target;",
"import java.util.List;",
"class A {",
" @Target({TYPE_USE, TYPE_PARAMETER})",
" @interface Nullable {}",
" class B {}",
" // BUG: Diagnostic contains: A.@Nullable B",
" void test(@Nullable A.B x) {}",
" // BUG: Diagnostic contains: List< A.@Nullable B>",
" void test2(List<@Nullable A.B> x) {}",
"}")
.doTest();
}
@Test
public void annotationNamedNullable_annotatingInImplements() {
helper
.addSourceLines(
"Test.java",
"import static java.lang.annotation.ElementType.TYPE_USE;",
"import java.lang.annotation.Target;",
"import java.util.List;",
"interface A {",
" @Target(TYPE_USE)",
" @interface Nullable {}",
" // BUG: Diagnostic contains: A.@Nullable B",
" abstract class B implements List<@Nullable A.B> {}",
"}")
.doTest();
}
@Test
public void annotationNamedNullable_annotatingInnerClass() {
helper
.addSourceLines(
"Test.java",
"import static java.lang.annotation.ElementType.TYPE_USE;",
"import java.lang.annotation.Target;",
"class A {",
" @Target(TYPE_USE)",
" @interface Nullable {}",
" class B {}",
" void test(A.@Nullable B x) {}",
"}")
.doTest();
}
}
| 5,117
| 32.233766
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RandomCastTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link RandomCast}Test */
@RunWith(JUnit4.class)
public class RandomCastTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(RandomCast.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Random;",
"class Test {",
" {",
" // BUG: Diagnostic contains:",
" int x = (int) new Random().nextFloat();",
" // BUG: Diagnostic contains:",
" x = (int) new Random().nextDouble();",
" // BUG: Diagnostic contains:",
" long y = (long) new Random().nextFloat();",
" // BUG: Diagnostic contains:",
" y = (long) new Random().nextDouble();",
" // BUG: Diagnostic contains:",
" y = (long) (new Random().nextDouble());",
" // BUG: Diagnostic contains:",
" int z = (int) Math.random();",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Random;",
"class Test {",
" {",
" float x = new Random().nextFloat();",
" x = (float) new Random().nextDouble();",
" double y = new Random().nextFloat();",
" y = new Random().nextDouble();",
" double z = Math.random();",
" int i = (int) new Random().nextInt();",
" i = (int) new Random().nextLong();",
" long l = (long) new Random().nextInt();",
" l = (long) new Random().nextLong();",
" }",
"}")
.doTest();
}
}
| 2,614
| 32.525641
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MockitoUsageTest.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link MockitoUsage}Test */
@RunWith(JUnit4.class)
public class MockitoUsageTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(MockitoUsage.class, getClass());
private static final String[] FOO_SOURCE = {
"class Foo {",
" Object get() { return null; }",
" Object execute () {",
" return null;",
" }",
"}",
};
@Test
public void negative_thenReturn() {
compilationHelper
.addSourceLines("Foo.java", FOO_SOURCE)
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.when;",
"class Test {",
" void test() {",
" Foo mock = mock(Foo.class);",
" when(mock.get()).thenReturn(null);",
" }",
"}")
.doTest();
}
@Test
public void negative_verify() {
compilationHelper
.addSourceLines("Foo.java", FOO_SOURCE)
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.verify;",
"class Test {",
" void test() {",
" Foo mock = mock(Foo.class);",
" verify(mock).execute();",
" }",
"}")
.doTest();
}
@Test
public void positive_verify_never_noMethod() {
compilationHelper
.addSourceLines("Foo.java", FOO_SOURCE)
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.verify;",
"import static org.mockito.Mockito.never;",
"class Test {",
" void test() {",
" Foo mock = mock(Foo.class);",
" // BUG: Diagnostic contains:",
" // Missing method call for verify(mock, never())",
" // verifyZeroInteractions(mock);",
" verify(mock, never());",
" }",
"}")
.doTest();
}
@Test
public void positive_verify_never_method() {
compilationHelper
.addSourceLines("Foo.java", FOO_SOURCE)
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.verify;",
"import static org.mockito.Mockito.never;",
"class Test {",
" void test() {",
" Foo mock = mock(Foo.class);",
" // BUG: Diagnostic contains:",
" // Missing method call for verify(mock.execute(), never())",
" // verify(mock, never()).execute();",
" verify(mock.execute(), never());",
" }",
"}")
.doTest();
}
@Test
public void positive_thenReturn() {
compilationHelper
.addSourceLines("Foo.java", FOO_SOURCE)
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.when;",
"class Test {",
" void test() {",
" Foo mock = mock(Foo.class);",
" // BUG: Diagnostic contains:",
" // Missing method call for when(mock.get()) here",
" // remove this line",
" when(mock.get());",
" }",
"}")
.doTest();
}
@Test
public void positive_verify_methodInside() {
compilationHelper
.addSourceLines("Foo.java", FOO_SOURCE)
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.verify;",
"class Test {",
" void test() {",
" Foo mock = mock(Foo.class);",
" // BUG: Diagnostic contains:",
" // Missing method call for verify(mock.execute()) here",
" // verify(mock).execute();",
" verify(mock.execute());",
" }",
"}")
.doTest();
}
@Test
public void positive_verify_noMethod() {
compilationHelper
.addSourceLines("Foo.java", FOO_SOURCE)
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.verify;",
"class Test {",
" void test() {",
" Foo mock = mock(Foo.class);",
" // BUG: Diagnostic contains:",
" // Missing method call for verify(mock) here",
" // remove this line",
" verify(mock);",
" }",
"}")
.doTest();
}
@Test
public void positive_verify_times() {
compilationHelper
.addSourceLines("Foo.java", FOO_SOURCE)
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.verify;",
"import static org.mockito.Mockito.times;",
"class Test {",
" void test() {",
" Foo mock = mock(Foo.class);",
" // BUG: Diagnostic contains:",
" // Missing method call for verify(mock.execute(), times(1))",
" // verify(mock, times(1)).execute();",
" verify(mock.execute(), times(1));",
" }",
"}")
.doTest();
}
}
| 6,310
| 31.19898
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AutoValueImmutableFieldsTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link AutoValueImmutableFields}. */
@RunWith(JUnit4.class)
public class AutoValueImmutableFieldsTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(AutoValueImmutableFields.class, getClass());
@Test
public void matchesNonPrimitiveArray() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableList",
" public abstract String[] countries();",
"}")
.doTest();
}
@Test
public void matchesIntArray() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableList",
" public abstract int[] countries();",
"}")
.doTest();
}
@Test
public void matchesCollection() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import java.util.Collection;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableCollection",
" public abstract Collection<String> countries();",
"}")
.doTest();
}
@Test
public void matchesList() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import java.util.List;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableList",
" public abstract List<String> countries();",
"}")
.doTest();
}
@Test
public void matchesMap() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import java.util.Map;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableMap",
" public abstract Map<String, String> countries();",
"}")
.doTest();
}
@Test
public void matchesMultimap() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.common.collect.Multimap;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableMultimap",
" public abstract Multimap<String, String> countries();",
"}")
.doTest();
}
@Test
public void matchesListMultimap() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.common.collect.ListMultimap;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableListMultimap",
" public abstract ListMultimap<String, String> countries();",
"}")
.doTest();
}
@Test
public void matchesSetMultimap() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.common.collect.SetMultimap;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableSetMultimap",
" public abstract SetMultimap<String, String> countries();",
"}")
.doTest();
}
@Test
public void matchesMultiset() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.common.collect.Multiset;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableMultiset",
" public abstract Multiset<String> countries();",
"}")
.doTest();
}
@Test
public void matchesSet() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import java.util.Set;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableSet",
" public abstract Set<String> countries();",
"}")
.doTest();
}
@Test
public void matchesTable() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.common.collect.Table;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableTable",
" public abstract Table<String, String, String> countries();",
"}")
.doTest();
}
@Test
public void matchesTwoProperties() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import java.util.Map;",
"import java.util.Set;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableSet",
" public abstract Set<String> countriesSet();",
" // BUG: Diagnostic contains: ImmutableMap",
" public abstract Map<String, String> countriesMap();",
"}")
.doTest();
}
@Test
public void noMatches() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.common.collect.ImmutableCollection;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.common.collect.ImmutableMultimap;",
"import com.google.common.collect.ImmutableListMultimap;",
"import com.google.common.collect.ImmutableSetMultimap;",
"import com.google.common.collect.ImmutableMultiset;",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableTable;",
"@AutoValue",
"abstract class Test {",
" public abstract ImmutableCollection<String> immutableCountriesCollection();",
" public abstract ImmutableList<String> immutableCountriesList();",
" public abstract ImmutableSet<String> immutableCountriesSet();",
" public abstract ImmutableMap<String, String> immutableCountriesMap();",
" public abstract ImmutableMultimap<String, String> immutableCountriesMultimap();",
" public abstract ImmutableListMultimap<String, String> countriesListMultimap();",
" public abstract ImmutableSetMultimap<String, String> countriesSetMultimap();",
" public abstract ImmutableMultiset<String> immutableCountriesMultiset();",
" public abstract ImmutableTable<String, String, String> immutableCountriesTable();",
"}")
.doTest();
}
@Test
public void suppressionOnMethod() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import java.util.Collection;",
"@AutoValue",
"abstract class Test {",
" @SuppressWarnings(\"AutoValueImmutableFields\")",
" public abstract Collection<String> countries();",
"}")
.doTest();
}
@Test
public void suppressionWithMutable() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"import java.util.Collection;",
"@AutoValue",
"abstract class Test {",
" @SuppressWarnings(\"mutable\")",
" public abstract Collection<String> countries();",
"}")
.doTest();
}
@Test
public void matchesNonPublic() {
compilationHelper
.addSourceLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"abstract class Test {",
" // BUG: Diagnostic contains: ImmutableList",
" abstract String[] countries();",
"}")
.doTest();
}
}
| 9,514
| 32.385965
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BoxedPrimitiveEqualityTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cushon@google.com (Liam Miller-Cushon)
*/
@RunWith(JUnit4.class)
public class BoxedPrimitiveEqualityTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(BoxedPrimitiveEquality.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean f(Boolean a, Boolean b) {",
" // BUG: Diagnostic contains:",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void negative_forNumber() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean f(Number a, Number b) {",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean f(boolean a, boolean b) {",
" return a == b;",
" }",
" boolean g(String a, String b) {",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void comparedToStaticField_noFinding() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" private static final Number SENTINEL = 1L;",
" boolean f(Number a) {",
" return a == SENTINEL;",
" }",
"}")
.doTest();
}
// regression test for #415
@Test
public void parenthesized() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" final Long constValue = Long.valueOf(1000L);",
" Long assignedValue;",
" // BUG: Diagnostic contains:"
+ " (!(assignedValue = Long.valueOf(1000L)).equals(constValue))",
" boolean retVal = ((assignedValue = Long.valueOf(1000L)) != constValue);",
" }",
"}")
.doTest();
}
@Test
public void atomic() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.atomic.AtomicInteger;",
"class Test {",
" boolean f(AtomicInteger a, AtomicInteger b) {",
" return a == b;",
" }",
"}")
.doTest();
}
}
| 3,354
| 26.5
| 90
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.