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/CatchAndPrintStackTraceTest.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;
/** {@link CatchAndPrintStackTrace}Test */
@RunWith(JUnit4.class)
public class CatchAndPrintStackTraceTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(CatchAndPrintStackTrace.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" try {",
" System.err.println();",
" } catch (Throwable t) {",
" // BUG: Diagnostic contains:",
" t.printStackTrace();",
" }",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" try {",
" System.err.println();",
" } catch (Throwable t) {}",
" try {",
" System.err.println();",
" } catch (Throwable t) {",
" t.printStackTrace();",
" t.printStackTrace();",
" }",
" try {",
" System.err.println();",
" } catch (Throwable t) {",
" t.printStackTrace(System.err);",
" }",
" }",
"}")
.doTest();
}
}
| 2,210
| 28.48
| 83
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/WildcardImportTest.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 static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.stream.Collectors.joining;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Streams;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link WildcardImport}Test */
@RunWith(JUnit4.class)
public class WildcardImportTest {
private BugCheckerRefactoringTestHelper testHelper;
@Before
public void setUp() {
testHelper = BugCheckerRefactoringTestHelper.newInstance(WildcardImport.class, getClass());
}
@Test
public void chainOffStatic() {
testHelper
.addInputLines(
"a/One.java",
"package a;",
"public class One {",
" public static Two THE_INSTANCE = null;",
"}")
.expectUnchanged()
.addInputLines(
"a/Two.java",
"package a;",
"public class Two {",
" public static String MESSAGE = \"Hello\";",
"}")
.expectUnchanged()
.addInputLines(
"in/test/Test.java",
"package test;",
"import static a.One.*;",
"public class Test {",
" String m = THE_INSTANCE.MESSAGE;",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"import static a.One.THE_INSTANCE;",
"public class Test {",
" String m = THE_INSTANCE.MESSAGE;",
"}")
.doTest();
}
@Test
public void classLiteral() {
testHelper
.addInputLines("a/A.java", "package a;", "public class A {", "}")
.expectUnchanged()
.addInputLines(
"in/test/Test.java",
"package test;",
"import a.*;",
"public class Test {",
" void m() {",
" System.err.println(A.class);",
" }",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"import a.A;",
"public class Test {",
" void m() {",
" System.err.println(A.class);",
" }",
"}")
.doTest();
}
@Test
public void staticMethod() {
testHelper
.addInputLines(
"a/A.java", //
"package a;",
"public class A {",
" public static void f() {}",
"}")
.expectUnchanged()
.addInputLines(
"in/test/Test.java",
"package test;",
"import static a.A.*;",
"public class Test {",
" void m() {",
" f();",
" }",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"import static a.A.f;",
"public class Test {",
" void m() {",
" f();",
" }",
"}")
.doTest();
}
@Test
public void enumTest() {
testHelper
.addInputLines(
"in/test/Test.java",
"package test;",
"import static java.nio.charset.StandardCharsets.*;",
"public class Test {",
" void m() {",
" System.err.println(UTF_8);",
" }",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"import static java.nio.charset.StandardCharsets.UTF_8;",
"public class Test {",
" void m() {",
" System.err.println(UTF_8);",
" }",
"}")
.doTest();
}
@Test
public void positive() {
testHelper
.addInputLines(
"in/test/Test.java",
"package test;",
"import java.util.*;",
"public class Test {",
" java.util.Map.Entry<String, String> e;",
" C c;",
" static class C {}",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"public class Test {",
" java.util.Map.Entry<String, String> e;",
" C c;",
" static class C {}",
"}")
.doTest();
}
@Test
public void doublePrefix() {
testHelper
.addInputLines(
"foo/Foo.java", //
"package foo;",
"public class Foo {}")
.expectUnchanged()
.addInputLines(
"foo/bar/Bar.java", //
"package foo.bar;",
"public class Bar {}")
.expectUnchanged()
.addInputLines(
"in/test/Test.java",
"package test;",
"import foo.*;",
"import foo.bar.*;",
"public class Test {",
" void f(Bar c) {}",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"import foo.bar.Bar;",
"public class Test {",
" void f(Bar c) {}",
"}")
.doTest();
}
@Test
public void positiveClassSelect() {
testHelper
.addInputLines(
"in/test/Test.java",
"package test;",
"import java.util.*;",
"public class Test {",
" Map.Entry<String, String> e;",
" C c;",
" static class C {}",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"import java.util.Map;",
"public class Test {",
" Map.Entry<String, String> e;",
" C c;",
" static class C {}",
"}")
.doTest();
}
@Test
public void positiveInnerClass() {
testHelper
.addInputLines(
"in/test/Test.java",
"package test;",
"import java.util.Map.*;",
"public class Test {",
" Entry<String, String> e;",
" C c;",
" static class C {}",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"import java.util.Map.Entry;",
"public class Test {",
" Entry<String, String> e;",
" C c;",
" static class C {}",
"}")
.doTest();
}
@Test
public void dontImportRuntime() {
testHelper
.addInputLines(
"in/test/Test.java", //
"package test;",
"public class Test {",
" String s;",
"}")
.addOutputLines(
"out/test/Test.java", //
"package test;",
"public class Test {",
" String s;",
"}")
.doTest();
}
@Test
public void dontImportSelf() {
testHelper
.addInputLines(
"in/test/Test.java",
"package test;",
"import java.util.*;",
"public class Test {",
" Test s;",
"}")
.addOutputLines(
"out/test/Test.java", //
"package test;",
"public class Test {",
" Test s;",
"}")
.doTest();
}
@Test
public void dontImportSelfPrivate() {
testHelper
.addInputLines(
"in/test/Test.java",
"package test;",
"import test.Test.Inner.*;",
"public class Test {",
" public static class Inner {",
" private static class InnerMost {",
" InnerMost i;",
" }",
" }",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"public class Test {",
" public static class Inner {",
" private static class InnerMost {",
" InnerMost i;",
" }",
" }",
"}")
.doTest();
}
@Test
public void dontImportSelfNested() {
testHelper
.addInputLines(
"in/test/Test.java",
"package test;",
"import java.util.*;",
"public class Test {",
" public static class Inner {",
" Inner t;",
" }",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"public class Test {",
" public static class Inner {",
" Inner t;",
" }",
"}")
.doTest();
}
@Test
public void importSamePackage() {
testHelper
.addInputLines(
"test/A.java",
"package test;",
"public class A {",
" public static class Inner {}",
"}")
.expectUnchanged()
.addInputLines(
"in/test/Test.java",
"package test;",
"import test.A.*;",
"public class Test {",
" Inner t;",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"import test.A.Inner;",
"public class Test {",
" Inner t;",
"}")
.doTest();
}
@Test
public void negativeNoWildcard() {
CompilationTestHelper.newInstance(WildcardImport.class, getClass())
.addSourceLines(
"test/Test.java",
"package test;",
"import java.util.Map;",
"public class Test {",
" Map.Entry<String, String> e;",
" C c;",
" static class C {}",
"}")
.doTest();
}
@Test
public void sameUnitWithSpuriousWildImport() {
testHelper
.addInputLines(
"in/test/Test.java",
"package test;",
"import java.util.Map;",
"public class Test {",
" Map.Entry<String, String> e;",
" C c;",
" private static class C {}",
"}")
.addOutputLines(
"test/Test.java",
"package test;",
"import java.util.Map;",
"public class Test {",
" Map.Entry<String, String> e;",
" C c;",
" private static class C {}",
"}")
.doTest();
}
@Test
public void nonCanonical() {
testHelper
.addInputLines(
"a/One.java", //
"package a;",
"public class One extends Two {",
"}")
.expectUnchanged()
.addInputLines(
"a/Two.java", //
"package a;",
"public class Two {",
" public static class Inner {}",
"}")
.expectUnchanged()
.addInputLines(
"in/test/Test.java",
"package test;",
"import static a.One.*;",
"public class Test {",
" Inner i;",
"}")
.addOutputLines(
"out/test/Test.java",
"package test;",
"import a.Two.Inner;",
"public class Test {",
" Inner i;",
"}")
.doTest();
}
@Test
public void memberImport() {
testHelper
.addInputLines(
"in/test/Test.java",
"package test;",
"import static java.util.Arrays.*;",
"import java.util.*;",
"public class Test {",
" List<Integer> xs = asList(1, 2, 3);",
"}")
.addOutputLines(
"test/Test.java",
"package test;",
"import static java.util.Arrays.asList;",
"import java.util.List;",
"public class Test {",
" List<Integer> xs = asList(1, 2, 3);",
"}")
.doTest();
}
private static final Predicate<String> QUALIFY_MEMBERS_FIX =
Predicates.and(
Predicates.containsPattern("Wildcard imports.*should not be used"),
Predicates.not(Predicates.contains(Pattern.compile("Did you mean"))));
@Test
public void qualifyMembersFix() {
String[] enumLines = {
"package e;",
"public enum E {",
" A, B, C, D, E, F, G, H, I, J,",
" K, L, M, N, O, P, Q, R, S, T,",
" U, V, W, X, Y, Z",
"}"
};
String[] testLines = {
"// BUG: Diagnostic matches: X",
"import static e.E.*;",
"public class Test {",
" Object[] ex = {",
" A, B, C, D, E, F, G, H, I, J,",
" K, L, M, N, O, P, Q, R, S, T,",
" U, V, W, X, Y, Z",
" };",
" boolean f(e.E e) {",
" switch (e) {",
" case A:",
" case E:",
" case I:",
" case O:",
" case U:",
" return true;",
" default:",
" return false;",
" }",
" }",
"}"
};
CompilationTestHelper.newInstance(WildcardImport.class, getClass())
.addSourceLines("e/E.java", enumLines)
.addSourceLines("e/Test.java", testLines)
.expectErrorMessage("X", QUALIFY_MEMBERS_FIX)
.doTest();
testHelper
.addInputLines("e/E.java", enumLines)
.expectUnchanged()
.addInputLines("in/Test.java", testLines)
.addOutputLines(
"out/Test.java",
"import e.E;",
"public class Test {",
" Object[] ex = {",
" E.A, E.B, E.C, E.D, E.E, E.F, E.G, E.H, E.I, E.J,",
" E.K, E.L, E.M, E.N, E.O, E.P, E.Q, E.R, E.S, E.T,",
" E.U, E.V, E.W, E.X, E.Y, E.Z",
" };",
" boolean f(e.E e) {",
" switch (e) {",
" case A:",
" case E:",
" case I:",
" case O:",
" case U:",
" return true;",
" default:",
" return false;",
" }",
" }",
"}")
.doTest();
}
@Test
public void manyTypesFix() {
ImmutableList<Character> alphabet =
Stream.iterate('A', x -> (char) (x + 1)).limit(26).collect(toImmutableList());
for (Character ch : alphabet) {
testHelper =
testHelper
.addInputLines(
String.format("e/%s.java", ch),
String.format("package e; public class %s {}", ch))
.expectUnchanged();
}
testHelper
.addInputLines(
"p/Test.java",
"package p;",
"import e.*;",
"public class Test {",
Streams.mapWithIndex(alphabet.stream(), (a, x) -> String.format("%s x%d;\n", a, x))
.collect(joining("\n")),
"}")
.addOutputLines(
"p/Test.java",
"package p;",
alphabet.stream().map(x -> String.format("import e.%s;", x)).collect(joining("\n")),
"public class Test {",
Streams.mapWithIndex(alphabet.stream(), (a, x) -> String.format("%s x%d;\n", a, x))
.collect(joining("\n")),
"}")
.doTest();
}
}
| 16,203
| 26.986183
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/PrivateConstructorForUtilityClassTest.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 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 PrivateConstructorForUtilityClass} Test */
@RunWith(JUnit4.class)
public final class PrivateConstructorForUtilityClassTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(
PrivateConstructorForUtilityClass.class, getClass());
@Test
public void emptyClassesGetLeftAlone() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {}")
.expectUnchanged()
.doTest();
}
@Test
public void privateClassesGetLeftAlone() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" private static class Blah {",
" static void blah() {}",
" }",
" private Test() {}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void subClassesGetLeftAlone() {
testHelper
.addInputLines(
"in/Foo.java", //
"public class Foo<E> {",
" private E entity;",
" public E getEntity() {",
" return entity;",
" }",
" public void setEntity(E anEntity) {",
" entity = anEntity;",
" }",
" public static class BooleanFoo extends Foo<Boolean> {",
" private static final long serialVersionUID = 123456789012L;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void implementingClassesGetLeftAlone() {
testHelper
.addInputLines(
"in/Foo.java", //
"import java.io.Serializable;",
"public class Foo {",
" private int entity;",
" public int getEntity() {",
" return entity;",
" }",
" public void setEntity(int anEntity) {",
" entity = anEntity;",
" }",
" public static class Bar implements Serializable {",
" private static final long serialVersionUID = 123456789012L;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void privateScopedClassesGetLeftAlone() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" private static class Blah {",
" static class Bleh {",
" static void bleh() {}",
" }",
" }",
" private Test() {}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void utilityClassesGetAPrivateConstructor_onlyFields() {
testHelper
.addInputLines(
"in/Test.java",
"",
"final class Test {",
" static final String SOME_CONSTANT = \"\";",
"}")
.addOutputLines(
"out/Test.java",
"",
"final class Test {",
" static final String SOME_CONSTANT = \"\";",
" private Test() {}",
"}")
.doTest();
}
@Test
public void utilityClassesGetAPrivateConstructor_onlyMethods() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" static void blah() {}",
"}")
.addOutputLines(
"out/Test.java",
"",
"final class Test {",
" static void blah() {}",
" private Test() {}",
"}")
.doTest();
}
@Test
public void utilityClassesGetAPrivateConstructor_onlyNestedClasses() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" static class Blah {}",
"}")
.addOutputLines(
"out/Test.java",
"",
"final class Test {",
" static class Blah {}",
" private Test() {}",
"}")
.doTest();
}
@Test
public void utilityClassesGetAPrivateConstructor_onlyStaticInitializer() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" static {}",
"}")
.addOutputLines(
"out/Test.java", //
"final class Test {",
" static {}",
" private Test() {}",
"}")
.doTest();
}
@Test
public void utilityClassesWithAConstructorGetLeftAlone() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" static void blah() {}",
" Test() {}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void otherClassesGetLeftAlone_field() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" private Object blah;",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void otherClassesGetLeftAlone_method() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" void blah() {}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void otherClassesGetLeftAlone_innerClass() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" class Blah {}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void otherClassesGetLeftAlone_initializer() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" {}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void otherClassesGetLeftAlone_constructor() {
testHelper
.addInputLines(
"in/Test.java", //
"final class Test {",
" Test() {}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void otherClassesGetLeftAlone_interface() {
testHelper
.addInputLines(
"in/Test.java", //
"interface Test {",
" void blah();",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void otherClassesGetLeftAlone_enum() {
testHelper
.addInputLines(
"in/Test.java", //
"enum Test {",
" INSTANCE;",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void b30170662() {
CompilationTestHelper.newInstance(PrivateConstructorForUtilityClass.class, getClass())
.addSourceLines(
"Foo.java",
"// BUG: Diagnostic contains:",
"public class Foo {",
" enum Enum {}",
" @interface Annotation {}",
" interface Interface {}",
"}")
.doTest();
}
@Test
public void ignoreTestClasses() {
testHelper
.addInputLines(
"in/Test.java",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(JUnit4.class)",
"final class Test {",
" @RunWith(JUnit4.class)",
" private static class Blah {",
" static void blah() {}",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void finalAdded() {
testHelper
.addInputLines(
"in/Test.java", //
"",
"class Test {",
" static final String SOME_CONSTANT = \"\";",
"}")
.addOutputLines(
"out/Test.java",
"",
"final class Test {",
" static final String SOME_CONSTANT = \"\";",
" private Test() {}",
"}")
.doTest();
}
@Test
public void abstractClass_noPrivateConstructor() {
testHelper
.addInputLines(
"in/Test.java", //
"",
"abstract class Test {",
" static final String SOME_CONSTANT = \"\";",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void record() {
assumeTrue(RuntimeVersion.isAtLeast16());
CompilationTestHelper.newInstance(PrivateConstructorForUtilityClass.class, getClass())
.addSourceLines(
"ExampleUtilityClass.java",
"package example;",
"// BUG: Diagnostic contains:",
"public final class ExampleUtilityClass {",
" public record SomeRecord(String value) {}",
"}")
.doTest();
}
@Test
public void ignoreAutoValue() {
CompilationTestHelper.newInstance(PrivateConstructorForUtilityClass.class, getClass())
.addSourceLines(
"Foo.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"public abstract class Foo {",
"}")
.doTest();
}
}
| 10,043
| 25.571429
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TypeNameShadowingTest.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 TypeNameShadowing} */
@RunWith(JUnit4.class)
public class TypeNameShadowingTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(TypeNameShadowing.class, getClass());
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(TypeNameShadowing.class, getClass());
@Test
public void positiveClass() {
compilationHelper
.addSourceLines(
"T.java",
"package foo.bar;", //
"class T {}")
.addSourceLines(
"Foo.java",
"package foo.bar;", //
"// BUG: Diagnostic contains: Type parameter T shadows visible type foo.bar.T",
"class Foo<T> {",
" void bar(T t) {}",
"}")
.doTest();
}
@Test
public void positiveNestedClass() {
compilationHelper
.addSourceLines(
"Foo.java",
"package foo.bar;", //
"class Foo {",
" class T {}",
" // BUG: Diagnostic contains: "
+ "Type parameter T shadows visible type foo.bar.Foo$T",
" class Bar<T> {",
" void bar(T t) {}",
" }",
"}")
.doTest();
}
@Test
public void positiveNestedStaticClass() {
compilationHelper
.addSourceLines(
"Foo.java",
"package foo.bar;", //
"class Foo {",
" public static class T {}",
" // BUG: Diagnostic contains: "
+ "Type parameter T shadows visible type foo.bar.Foo$T",
" class Bar<T> {",
" void bar(T t) {}",
" }",
"}")
.doTest();
}
@Test
public void positiveNestedGeneric() {
compilationHelper
.addSourceLines(
"T.java",
"package foo.bar;", //
"interface T {}")
.addSourceLines(
"Foo.java",
"package foo.bar;", //
"class Foo {",
" // BUG: Diagnostic contains: Type parameter T shadows visible type foo.bar.T",
" class FooInner<T> {",
" void bar(T t) {}",
" }",
"}")
.doTest();
}
@Test
public void positiveOtherNestedClass() {
compilationHelper
.addSourceLines(
"Foo.java",
"package foo.bar;", //
"class Foo {",
" class T {}",
"}")
.addSourceLines(
"Bar.java",
"package foo.bar;", //
"import foo.bar.Foo.T;",
"// BUG: Diagnostic contains: Type parameter T shadows visible type foo.bar.Foo$T",
"class Bar<T> {",
" void bar(T t) {}",
"}")
.doTest();
}
@Test
public void positiveMultipleParamsOneCollides() {
compilationHelper
.addSourceLines(
"T.java",
"package foo.bar;", //
"class T {}")
.addSourceLines(
"Foo.java",
"package foo.bar;", //
"// BUG: Diagnostic contains: Type parameter T shadows visible type foo.bar.T",
"class Foo<T,U,V> {",
" void bar(T t, U u, V v) {}",
"}")
.doTest();
}
@Test
public void positiveMultipleParamsBothCollide() {
compilationHelper
.addSourceLines(
"T.java",
"package foo.bar;", //
"class T {}")
.addSourceLines(
"U.java",
"package foo.bar;", //
"class U {}")
.addSourceLines(
"Foo.java",
"package foo.bar;", //
"// BUG: Diagnostic matches: combo",
"class Foo<T,U> {",
" void bar(T t, U u) {}",
"}")
.expectErrorMessage(
"combo",
s ->
s.contains("Type parameter T shadows visible type foo.bar.T")
&& s.contains("Type parameter U shadows visible type foo.bar.U"))
.doTest();
}
@Test
public void positiveJavaLangCollision() {
compilationHelper
.addSourceLines(
"Foo.java",
"// BUG: Diagnostic contains: Class shadows visible type java.lang.Class", //
"class Foo<Class> {",
" void bar(Class c) {}",
"}")
.doTest();
}
@Test
public void negativeClass() {
compilationHelper
.addSourceLines(
"T.java",
"package foo.bar;", //
"class T {}")
.addSourceLines(
"Foo.java",
"package foo.bar;", //
"class Foo<T1> {",
" void bar(T1 t) {}",
"}")
.doTest();
}
@Test
public void negativeNestedClass() {
compilationHelper
.addSourceLines(
"T.java",
"package foo.bar;", //
"class T {",
" class Foo<T1> {",
" void bar(T1 t) {}",
" }",
"}")
.doTest();
}
@Test
public void negativeOtherNestedClass() {
compilationHelper
.addSourceLines(
"Foo.java",
"package foo.bar;", //
"class Foo {",
" class T {}",
"}")
.addSourceLines(
"Bar.java",
"package foo.bar;", //
"class Bar<T> {",
" void bar(T t) {}",
"}")
.doTest();
}
@Test
public void negativeStarImport() {
compilationHelper
.addSourceLines(
"a/T.java",
"package a;", //
"class T {}")
.addSourceLines(
"b/Foo.java",
"package b;", //
"import a.*;",
"class Foo<T> {",
" void bar(T u) {}",
"}")
.doTest();
}
@Test
public void refactorSingle() {
refactoring
.addInputLines(
"Foo.java",
"class Foo {", //
" class T {}",
" <T> void f(T t){}",
"}")
.addOutputLines(
"Foo.java",
"class Foo {", //
" class T {}",
" <T2> void f(T2 t){}",
"}")
.doTest();
}
@Test
public void refactorMultiple() {
refactoring
.addInputLines(
"in/Foo.java",
"class Foo {", //
" class T {}",
" class U {}",
" <T,U> void f(T t, U u){}",
"}")
.addOutputLines(
"out/Foo.java",
"class Foo {", //
" class T {}",
" class U {}",
" <T2,U2> void f(T2 t, U2 u){}",
"}")
.doTest();
}
/**
* Tests that we only suggest a fix when the type variable name is style-guide-adherent;
* otherwise, it is likely the developer did not mean to use a generic and the fix is misleading
* Input program here is alpha-equivalent to the refactorMultiple test case; output only fixes T
*/
@Test
public void fixOnlyWellNamedVariables() {
refactoring
.addInputLines(
"in/Foo.java",
"class Foo {", //
" class T {}",
" class BadParameterName {}",
" <T,BadParameterName> void f(T t, BadParameterName u){}",
"}")
.addOutputLines(
"out/Foo.java",
"class Foo {", //
" class T {}",
" class BadParameterName {}",
" <T2,BadParameterName> void f(T2 t, BadParameterName u){}",
"}")
.doTest();
}
@Test
public void fieldClashOk() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" final Object T = new Object();",
" <T> void doIt(T t) {}",
"}")
.doTest();
}
}
| 8,783
| 26.53605
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ToStringReturnsNullTest.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;
/**
* Unit tests for {@link ToStringReturnsNull} bug pattern.
*
* @author eleanorh@google.com (Eleanor Harris)
* @author siyuanl@google.com (Siyuan Liu)
*/
@RunWith(JUnit4.class)
public final class ToStringReturnsNullTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ToStringReturnsNull.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: ToStringReturnsNull",
" public String toString() {",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void conditionalExpression() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" final boolean cond = false;",
" // BUG: Diagnostic contains: ToStringReturnsNull",
" public String toString() {",
" return cond ? null : \"foo\";",
" }",
"}")
.doTest();
}
@Test
public void returnsNonNullString() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public String toString() {",
" return \"foo\";",
" }",
"}")
.doTest();
}
@Test
public void nonToStringMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public String thisIsNotAToStringMethod() {",
" return \"bar\";",
" }",
"}")
.doTest();
}
@Test
public void nestedReturnNull() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public String toString() {",
" class InnerTest {",
" String getter() {",
" return null;",
" }",
" }",
" return \"bar\";",
" }",
"}")
.doTest();
}
@Test
public void lambdaReturnNull() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" interface MyGreeting {",
" String processName();",
" }",
" public String toString() {",
" MyGreeting lol = () -> {",
" String lolz = \"\";",
" return null;",
" };",
" return \"bar\";",
" }",
"}")
.doTest();
}
}
| 3,458
| 26.23622
| 79
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclarationTest.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 EmptyTopLevelDeclaration}Test */
@RunWith(JUnit4.class)
public class EmptyTopLevelDeclarationTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(EmptyTopLevelDeclaration.class, getClass());
@Test
public void negative() {
compilationHelper.addSourceLines("a/A.java", "package a;", "class One {}").doTest();
}
@Test
public void positive() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"// BUG: Diagnostic contains: Did you mean 'class One {}'?",
"class One {};")
.doTest();
}
}
| 1,439
| 29.638298
| 88
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ReferenceEqualityTest.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 ReferenceEquality}Test */
@RunWith(JUnit4.class)
public class ReferenceEqualityTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ReferenceEquality.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(ReferenceEquality.class, getClass());
@Test
public void protoGetter_nonnull() {
compilationHelper
.addSourceLines(
"in/Foo.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Foo {",
" void something(TestProtoMessage f1, TestProtoMessage f2) {",
" // BUG: Diagnostic contains: boolean b = Objects.equals(f1, f2);",
" boolean b = f1 == f2;",
" // BUG: Diagnostic contains: b = f1.getMessage().equals(f2.getMessage())",
" b = f1.getMessage() == f2.getMessage();",
" }",
"}")
.doTest();
}
@Test
public void negative_const() {
compilationHelper
.addSourceLines(
"Foo.java", //
"class Foo {",
"}")
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" public static final Foo CONST = new Foo();",
" boolean f(Foo a) {",
" return a == CONST;",
" }",
" boolean f(Object o, Foo a) {",
" return o == a;",
" }",
"}")
.doTest();
}
@Test
public void negative_extends_equalsObject() {
compilationHelper
.addSourceLines(
"Sup.java", //
"class Sup {",
" public boolean equals(Object o) {",
" return false; ",
" }",
"}")
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test extends Sup {",
" boolean f(Object a, Test b) {",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void positive_extendsAbstract_equals() {
compilationHelper
.addSourceLines(
"Sup.java", //
"abstract class Sup { ",
" public abstract boolean equals(Object o); ",
"}")
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"abstract class Test extends Sup {",
" boolean f(Test a, Test b) {",
" // BUG: Diagnostic contains: a.equals(b)",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void negative_implementsInterface_equals() {
compilationHelper
.addSourceLines(
"Sup.java", //
"interface Sup {",
" public boolean equals(Object o); ",
"}")
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test implements Sup {",
" boolean f(Test a, Test b) {",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void negative_noEquals() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Test a, Test b) {",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void positive_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 positive_equalWithOr() {
refactoringTestHelper
.addInputLines(
"in/Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Optional<Integer> a, Optional<Integer> b) {",
" return a == b || (a.equals(b));",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Optional<Integer> a, Optional<Integer> b) {",
" return a.equals(b);",
" }",
"}")
.doTest();
}
@Test
public void positive_equalWithOr_objectsEquals() {
refactoringTestHelper
.addInputLines(
"in/Test.java",
"import com.google.common.base.Optional;",
"import com.google.common.base.Objects;",
"class Test {",
" boolean f(Optional<Integer> a, Optional<Integer> b) {",
" boolean eq = a == b || Objects.equal(a, b);",
" return a == b || (java.util.Objects.equals(a, b));",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.base.Optional;",
"import com.google.common.base.Objects;",
"class Test {",
" boolean f(Optional<Integer> a, Optional<Integer> b) {",
" boolean eq = Objects.equal(a, b);",
" return java.util.Objects.equals(a, b);",
" }",
"}")
.doTest();
}
@Test
public void positive_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 negative_impl() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public boolean equals(Object o) {",
" return this == o;",
" }",
"}")
.doTest();
}
@Test
public void negative_enum() {
compilationHelper
.addSourceLines(
"Test.java",
"import javax.lang.model.element.ElementKind;",
"class Test {",
" boolean f(ElementKind a, ElementKind b) {",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void customEnum() {
compilationHelper
.addSourceLines(
"Kind.java",
"enum Kind {",
" FOO(42);",
" private final int x;",
" Kind(int x) { this.x = x; }",
"}")
.addSourceLines(
"Test.java",
"class Test {",
" boolean f(Kind a, Kind b) {",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void negative_null() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" boolean f(Optional<Integer> b) {",
" return b == null;",
" }",
"}")
.doTest();
}
@Test
public void negative_abstractEq() {
compilationHelper
.addSourceLines(
"Sup.java", //
"interface Sup {",
" public abstract boolean equals(Object o);",
"}")
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test implements Sup {",
" boolean f(Object a, Test b) {",
" return a == b;",
" }",
"}")
.doTest();
}
@Test
public void negativeCase_class() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean f(String s) {",
" return s.getClass() == String.class;",
" }",
"}")
.doTest();
}
@Test
public void transitiveEquals() {
compilationHelper
.addSourceLines(
"Super.java",
"public class Super {",
" public boolean equals(Object o) {",
" return false;",
" }",
"}")
.addSourceLines("Mid.java", "public class Mid extends Super {", "}")
.addSourceLines("Sub.java", "public class Sub extends Mid {", "}")
.addSourceLines(
"Test.java",
"abstract class Test {",
" boolean f(Sub a, Sub b) {",
" // BUG: Diagnostic contains: a.equals(b)",
" return a == b;",
" }",
"}")
.doTest();
}
public static class Missing {}
public static class MayImplementEquals {
public void f(Missing m) {}
public void g(Missing m) {}
}
@Test
public void erroneous() {
compilationHelper
.addSourceLines(
"Test.java",
"import " + MayImplementEquals.class.getCanonicalName() + ";",
"abstract class Test {",
" abstract MayImplementEquals getter();",
" boolean f(MayImplementEquals b) {",
" return getter() == b;",
" }",
"}")
.withClasspath(MayImplementEquals.class, ReferenceEqualityTest.class)
.doTest();
}
// regression test for #423
@Test
public void typaram() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test<T extends String, X> {",
" boolean f(T t) {",
" return t == null;",
" }",
" boolean g(T t1, T t2) {",
" // BUG: Diagnostic contains:",
" return t1 == t2;",
" }",
" boolean g(X x1, X x2) {",
" return x1 == x2;",
" }",
"}")
.doTest();
}
@Test
public void negative_compareTo() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test implements Comparable<Test> {",
" public int compareTo(Test o) {",
" return this == o ? 0 : -1;",
" }",
" public boolean equals(Object obj) {",
" return obj instanceof Test;",
" }",
" public int hashCode() {",
" return 1;",
" }",
"}")
.doTest();
}
@Test
public void likeCompareToButDifferentName() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test implements Comparable<Test> {",
" public int compareTo(Test o) {",
" return this == o ? 0 : -1;",
" }",
" public int notCompareTo(Test o) {",
" // BUG: Diagnostic contains:",
" return this == o ? 0 : -1;",
" }",
" public boolean equals(Object obj) {",
" return obj instanceof Test;",
" }",
" public int hashCode() {",
" return 1;",
" }",
"}")
.doTest();
}
@Test
public void positive_compareTo() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test implements Comparable<String> {",
" String f;",
" public int compareTo(String o) {",
" // BUG: Diagnostic contains:",
" return f == o ? 0 : -1;",
" }",
"}")
.doTest();
}
@Test
public void negative_implementsComparator() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Comparator;",
"class Test {",
" static class Comparator1 implements Comparator<String> {",
" @Override",
" public int compare(String o1, String o2) {",
" if (o1 == o2) {",
" return 0;",
" } else if (o1 == null) {",
" return -1;",
" } else if (o2 == null) {",
" return 1;",
" } else {",
" return -1;",
" }",
" }",
" }",
" static class Comparator2 implements Comparator<String> {",
" @Override",
" public int compare(String o1, String o2) {",
" return o1 == o2 ? 0 : -1;",
" }",
" }",
"}")
.expectNoDiagnostics()
.doTest();
}
@Test
public void negative_lambdaComparator() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Comparator;",
"class Test {",
" private static final Comparator<String> comparator1 = (o1, o2) -> {",
" if (o1 == o2) {",
" return 0;",
" } else if (o1 == null) {",
" return -1;",
" } else if (o2 == null) {",
" return 1;",
" } else {",
" return -1;",
" }",
" };",
" private static final Comparator<String> comparator2 = (o1, o2) -> {",
" return o1 == o2 ? 0 : -1;",
" };",
" private static final Comparator<String> comparator3 =",
" (o1, o2) -> o1 == o2 ? 0 : -1;",
"}")
.expectNoDiagnostics()
.doTest();
}
}
| 14,814
| 28.394841
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EqualsWrongThingTest.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 EqualsWrongThing} bugpattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class EqualsWrongThingTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(EqualsWrongThing.class, getClass());
@Test
public void negative() {
helper
.addSourceLines(
"Test.java",
"import com.google.common.base.Objects;",
"class Test {",
" private int a;",
" private int b;",
" @Override public boolean equals(Object o) {",
" Test that = (Test) o;",
" return a == that.a && Objects.equal(b, that.b);",
" }",
"}")
.doTest();
}
@Test
public void negativeUnordered() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int a;",
" private int b;",
" @Override public boolean equals(Object o) {",
" Test that = (Test) o;",
" return (a == that.a && b == that.b) || (a == that.b && b == that.a);",
" }",
"}")
.doTest();
}
@Test
public void negativeMixOfGettersAndFields() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int a;",
" private int b;",
" private Object c;",
" private int getA() { return a; }",
" private int getB() { return b; }",
" @Override public boolean equals(Object o) {",
" Test that = (Test) o;",
" return this.a == that.getA() && this.b == that.getB() && c.equals(that.c);",
" }",
"}")
.doTest();
}
@Test
public void positive() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int a;",
" private int b;",
" @Override public boolean equals(Object o) {",
" Test that = (Test) o;",
" // BUG: Diagnostic contains: comparison between `a` and `b`",
" return a == that.b && b == that.b;",
" }",
"}")
.doTest();
}
@Test
public void positiveGetters() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int a;",
" private int b;",
" private int getA() { return a; }",
" private int getB() { return b; }",
" @Override public boolean equals(Object o) {",
" Test that = (Test) o;",
" // BUG: Diagnostic contains: comparison between `getA()` and `getB()`",
" return getA() == that.getB() && getB() == that.getB();",
" }",
"}")
.doTest();
}
@Test
public void positiveObjects() {
helper
.addSourceLines(
"Test.java",
"import com.google.common.base.Objects;",
"class Test {",
" private int a;",
" private int b;",
" @Override public boolean equals(Object o) {",
" Test that = (Test) o;",
" // BUG: Diagnostic contains: comparison between `a` and `b`",
" return Objects.equal(a, that.b) && b == that.b;",
" }",
"}")
.doTest();
}
@Test
public void positiveEquals() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private Object a;",
" private Object b;",
" @Override public boolean equals(Object o) {",
" Test that = (Test) o;",
" // BUG: Diagnostic contains: comparison between `a` and `b`",
" return a.equals(that.b) && b == that.b;",
" }",
"}")
.doTest();
}
@Test
public void negativeArraysEquals() {
helper
.addSourceLines(
"Test.java",
"import java.util.Arrays;",
"class Test {",
" boolean test(int[] a, int[] b) {",
" return Arrays.equals(a, 0, 1, b, 2, 3);",
" }",
"}")
.doTest();
}
}
| 5,112
| 28.900585
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DistinctVarargsCheckerTest.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 java.util.stream.Collectors.joining;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import java.util.stream.IntStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link DistinctVarargsChecker}Test */
@RunWith(JUnit4.class)
public class DistinctVarargsCheckerTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(DistinctVarargsChecker.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(DistinctVarargsChecker.class, getClass());
@Test
public void distinctVarargsChecker_sameVariableInFuturesVaragsMethods_shouldFlag() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.util.concurrent.Futures;",
"import com.google.common.util.concurrent.ListenableFuture;",
"public class Test {",
" void testFunction() {",
" ListenableFuture firstFuture = null, secondFuture = null;",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Futures.whenAllSucceed(firstFuture, firstFuture);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Futures.whenAllSucceed(firstFuture, firstFuture, secondFuture);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Futures.whenAllComplete(firstFuture, firstFuture);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Futures.whenAllComplete(firstFuture, firstFuture, secondFuture);",
" }",
"}")
.doTest();
}
@Test
public void distinctVarargsCheckerdifferentVariableInFuturesVaragsMethods_shouldNotFlag() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.util.concurrent.Futures;",
"import com.google.common.util.concurrent.ListenableFuture;",
"public class Test {",
" void testFunction() {",
" ListenableFuture firstFuture = null, secondFuture = null;",
" Futures.whenAllComplete(firstFuture);",
" Futures.whenAllSucceed(firstFuture, secondFuture);",
" Futures.whenAllComplete(firstFuture);",
" Futures.whenAllComplete(firstFuture, secondFuture);",
" }",
"}")
.doTest();
}
@Test
public void distinctVarargsChecker_sameVariableInGuavaVarargMethods_shouldFlag() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Ordering;",
"import com.google.common.collect.ImmutableSortedMap;",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Ordering.explicit(first, first);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" Ordering.explicit(first, first, second);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSortedMap.of(first, second, first, second);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSet.of(first, first);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSet.of(first, first, second);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSortedSet.of(first, first);",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
" ImmutableSortedSet.of(first, first, second);",
" }",
"}")
.doTest();
}
@Test
public void distinctVarargsChecker_differentVariableInGuavaVarargMethods_shouldNotFlag() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Ordering;",
"import com.google.common.collect.ImmutableBiMap;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.common.collect.ImmutableSortedMap;",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2, third = 3, fourth = 4;",
" Ordering.explicit(first);",
" Ordering.explicit(first, second);",
" ImmutableMap.of(first, second);",
" ImmutableSortedMap.of(first, second);",
" ImmutableBiMap.of(first, second, third, fourth);",
" ImmutableSet.of(first);",
" ImmutableSet.of(first, second);",
" ImmutableSortedSet.of(first);",
" ImmutableSortedSet.of(first, second);",
" }",
"}")
.doTest();
}
@Test
public void distinctVarargsChecker_sameVariableInImmutableSetVarargsMethod_shouldRefactor() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" ImmutableSet.of(first, first);",
" ImmutableSet.of(first, first, second);",
" ImmutableSortedSet.of(first, first);",
" ImmutableSortedSet.of(first, first, second);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" ImmutableSet.of(first);",
" ImmutableSet.of(first, second);",
" ImmutableSortedSet.of(first);",
" ImmutableSortedSet.of(first, second);",
" }",
"}")
.doTest();
}
@Test
public void distinctVarargsChecker_differentVarsInImmutableSetVarargsMethod_shouldNotRefactor() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" ImmutableSet.of(first);",
" ImmutableSet.of(first, second);",
" ImmutableSortedSet.of(first);",
" ImmutableSortedSet.of(first, second);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.ImmutableSortedSet;",
"public class Test {",
" void testFunction() {",
" int first = 1, second = 2;",
" ImmutableSet.of(first);",
" ImmutableSet.of(first, second);",
" ImmutableSortedSet.of(first);",
" ImmutableSortedSet.of(first, second);",
" }",
"}")
.doTest();
}
@Test
public void negative_quadratic() {
String large =
IntStream.range(0, 7000)
.mapToObj(x -> String.format("\"%s\"", x))
.collect(joining(", ", "ImmutableSet.of(", ", \"0\");"));
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableSet;",
"public class Test {",
" void testFunction() {",
" // BUG: Diagnostic contains: DistinctVarargsChecker",
large,
" }",
"}")
.doTest();
}
}
| 9,040
| 39.542601
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AutoValueFinalMethodsTest.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 AutoValueFinalMethods} bug pattern.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@RunWith(JUnit4.class)
public class AutoValueFinalMethodsTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(AutoValueFinalMethods.class, getClass());
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(AutoValueFinalMethods.class, getClass());
@Test
public void finalAdditionToEqHcTs() {
testHelper
.addInputLines(
"in/Test.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"abstract class Test {",
" abstract String valueOne();",
" abstract String valueTwo();",
" static Test create(String valueOne, String valueTwo) {",
" return null;",
" }",
" @Override",
" public int hashCode() {",
" return 1;",
" }",
" @Override",
" public String toString() {",
" return \"Hakuna Matata\";",
" }",
" @Override",
" public boolean equals(Object obj) {",
" return true;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue",
"abstract class Test {",
" abstract String valueOne();",
" abstract String valueTwo();",
" static Test create(String valueOne, String valueTwo) {",
" return null;",
" }",
" @Override",
" public final int hashCode() {",
" return 1;",
" }",
" @Override",
" public final String toString() {",
" return \"Hakuna Matata\";",
" }",
" @Override",
" public final boolean equals(Object obj) {",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void negativeCases() {
compilationHelper
.addSourceLines(
"out/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.auto.value.extension.memoized.Memoized;",
"@AutoValue",
"abstract class Test {",
" abstract String valueOne();",
" abstract String valueTwo();",
" static Test create(String valueOne, String valueTwo) {",
" return null;",
" }",
" @Override",
" public abstract int hashCode(); ",
" @Override",
" @Memoized",
" public String toString() {",
" return \"Hakuna Matata\";",
" }",
" @Override",
" public final boolean equals(Object obj) {",
" return true;",
" }",
" private int privateNonEqTsHcMethod() {",
" return 2;",
" }",
" public final String publicFinalNonEqTsHcMethod() {",
" return \"Hakuna Matata\";",
" }",
" public boolean publicNonEqTsHcMethod(Object obj) {",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void abstractMemoizedNegativeCase() {
compilationHelper
.addSourceLines(
"out/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.auto.value.extension.memoized.Memoized;",
"@AutoValue",
"abstract class Test {",
" static Test create() {",
" return null;",
" }",
" @Override",
" @Memoized",
" public abstract int hashCode(); ",
"}")
.doTest();
}
@Test
public void diagnosticString() {
compilationHelper
.addSourceLines(
"out/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.auto.value.extension.memoized.Memoized;",
"@AutoValue",
"abstract class Test {",
" static Test create() {",
" return null;",
" }",
" @Override",
" // BUG: Diagnostic contains: Make equals final in AutoValue classes",
" public boolean equals(Object obj) {",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void diagnosticStringWithMultipleMethodMatches() {
compilationHelper
.addSourceLines(
"out/Test.java",
"import com.google.auto.value.AutoValue;",
"import com.google.auto.value.extension.memoized.Memoized;",
"@AutoValue",
"abstract class Test {",
" static Test create() {",
" return null;",
" }",
" @Override",
" // BUG: Diagnostic contains: Make equals, hashCode final in AutoValue classes",
" public boolean equals(Object obj) {",
" return true;",
" }",
" @Override",
" public int hashCode() {",
" return 1;",
" }",
"}")
.doTest();
}
}
| 6,324
| 31.942708
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NonOverridingEqualsTest.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;
/** Tests for {@link NonOverridingEquals}. */
// TODO(eaftan): Tests for correctness of suggested fix
@RunWith(JUnit4.class)
public class NonOverridingEqualsTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NonOverridingEquals.class, getClass());
// Positive cases
@Test
public void flagsSimpleCovariantEqualsMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains: Did you mean '@Override'",
" public boolean equals(Test other) {",
" return false;",
" }",
"}")
.doTest();
}
// The following two tests are really to help debug the construction of the suggested fixes.
@Test
public void flagsComplicatedCovariantEqualsMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" int i, j, k;",
" // BUG: Diagnostic contains: Did you mean '@Override'",
" public boolean equals(Test other) {",
" if (i == other.i && j == other.j && k == other.k) {",
" return true;",
" }",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void flagsAnotherComplicatedCovariantEqualsMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" boolean isInVersion;",
" String str;",
" // BUG: Diagnostic contains: Did you mean '@Override'",
" public boolean equals(Test that) {",
" return (this.isInVersion == that.isInVersion)",
" && this.str.equals(that.str);",
" }",
"}")
.doTest();
}
@Test
public void flagsAbstractCovariantEqualsMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"public abstract class Test {",
" // BUG: Diagnostic contains: Did you mean '@Override'",
" public abstract boolean equals(Test other);",
"}")
.doTest();
}
@Test
public void flagsNativeCovariantEqualsMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains: Did you mean '@Override'",
" public native boolean equals(Test other);",
"}")
.doTest();
}
@Test
public void flagsIfMethodTakesUnrelatedType() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains:",
" public boolean equals(Integer other) {",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void flagsBoxedBooleanReturnType() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains:",
" public Boolean equals(Test other) {",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void flagsCovariantEqualsMethodInEnum() {
compilationHelper
.addSourceLines(
"Planet.java",
"public enum Planet {",
" MERCURY,",
" VENUS,",
" EARTH,",
" MARS,",
" JUPITER,",
" SATURN,",
" URANUS,",
" NEPTUNE;", // Pluto: never forget
" // BUG: Diagnostic contains: enum instances can safely be compared by reference "
+ "equality",
" // Did you mean to remove this line?",
" public boolean equals(Planet other) {",
" return this == other;",
" }",
"}")
.doTest();
}
@Test
public void flagsPrivateEqualsMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains:",
" private boolean equals(Test other) {",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void flagsEvenIfAnotherMethodOverridesEquals() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains: either inline it into the callers or rename it",
" private boolean equals(Test other) {",
" return false;",
" }",
" @Override public boolean equals(Object other) {",
" return false;",
" }",
"}")
.doTest();
}
/**
* A static method can be invoked on an instance, so a static equals method with one argument
* could be confused with Object#equals. Though I can't imagine how anyone would define a
* single-argument static equals method...
*/
@Test
public void flagsStaticEqualsMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains:",
" public static boolean equals(Test other) {",
" return false;",
" }",
"}")
.doTest();
}
// Negative cases
@Test
public void dontFlagMethodThatOverridesEquals() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" @Override public boolean equals(Object other) {",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void dontFlagEqualsMethodWithMoreThanOneParameter() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean equals(Test other, String s) {",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void dontFlagIfWrongReturnType() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public int equals(Test other) {",
" return -1;",
" }",
"}")
.doTest();
}
}
| 7,277
| 27.996016
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MathRoundIntLongTest.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;
/** Tests for {@link MathRoundIntLong}. */
@RunWith(JUnit4.class)
public class MathRoundIntLongTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(MathRoundIntLong.class, getClass());
@Test
public void deleteRoundMethodInt() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" void f() {",
" int y = Math.round(3);",
" }",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
" void f() {",
" int y = 3;",
" }",
"}")
.doTest();
}
@Test
public void deleteRoundMethodIntClass() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" void f() {",
" Integer i = Integer.valueOf(3);",
" int y = Math.round(i);",
" }",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
" void f() {",
" Integer i = Integer.valueOf(3);",
" int y = i;",
" }",
"}")
.doTest();
}
@Test
public void replaceRoundMethodLong() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" void f() {",
" long l = 3L;",
" int y = Math.round(l);",
" }",
"}")
.addOutputLines(
"Test.java", //
"import com.google.common.primitives.Ints;",
"class Test {",
" void f() {",
" long l = 3L;",
" int y = Ints.saturatedCast(l);",
" }",
"}")
.doTest();
}
@Test
public void replaceRoundMethodLongClass() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" void f() {",
" Long l = Long.valueOf(\"3\");",
" int y = Math.round(l);",
" }",
"}")
.addOutputLines(
"Test.java", //
"import com.google.common.primitives.Ints;",
"class Test {",
" void f() {",
" Long l = Long.valueOf(\"3\");",
" int y = Ints.saturatedCast(l);",
" }",
"}")
.doTest();
}
@Test
public void roundingFloatNegative() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" void f() {",
" Float f = Float.valueOf(\"3\");",
" int y = Math.round(f);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void roundingDoubleNegative() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" void f() {",
" Double d = Double.valueOf(\"3\");",
" Long y = Math.round(d);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void replaceRoundMethodAddParenthesis() {
helper
.addInputLines(
"Test.java", //
"import com.google.common.primitives.Ints;",
"class Test {",
" void f() {",
" long l = 3L;",
" long x = 6L;",
" int y = Math.round(l/x);",
" }",
"}")
.addOutputLines(
"Test.java", //
"import com.google.common.primitives.Ints;",
"class Test {",
" void f() {",
" long l = 3L;",
" long x = 6L;",
" int y = Ints.saturatedCast(l/x);",
" }",
"}")
.doTest();
}
@Test
public void removeMathRoundLeaveParenthesisIfUnary() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" void f() {",
" int y = Math.round(1 + 3) * 3;",
" }",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
" void f() {",
" int y = (1 + 3) * 3;",
" }",
"}")
.doTest();
}
}
| 5,155
| 25.57732
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StaticAssignmentInConstructorTest.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 StaticAssignmentInConstructor}. */
@RunWith(JUnit4.class)
public final class StaticAssignmentInConstructorTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(StaticAssignmentInConstructor.class, getClass());
@Test
public void positive() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" static int foo;",
" public Test(int foo) {",
" // BUG: Diagnostic contains:",
" this.foo = foo;",
" }",
"}")
.doTest();
}
@Test
public void dubiousStorageOfLatestInstance_exempted() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" static Test latest;",
" public Test() {",
" latest = this;",
" }",
"}")
.doTest();
}
@Test
public void instanceField_noMatch() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" int foo;",
" public Test(int foo) {",
" this.foo = foo;",
" }",
"}")
.doTest();
}
@Test
public void assignedWithinLambda_noMatch() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" static int foo;",
" public Test(int a) {",
" java.util.Arrays.asList().stream().map(x -> { foo = 1; return a; }).count();",
" }",
"}")
.doTest();
}
}
| 2,396
| 26.551724
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CompareToZeroTest.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 CompareToZero} bugpattern. */
@RunWith(JUnit4.class)
public final class CompareToZeroTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(CompareToZero.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(CompareToZero.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean test(Integer i) {",
" // BUG: Diagnostic contains: compared",
" return i.compareTo(2) == -1;",
" }",
"}")
.doTest();
}
@Test
public void positiveSuggestionForConsistency() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean test(Integer i) {",
" // BUG: Diagnostic contains: consistency",
" return i.compareTo(2) <= -1;",
" }",
"}")
.doTest();
}
@Test
public void positive_gte1_has_1_finding() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean test(Integer i) {",
" // BUG: Diagnostic matches: KEY",
" return i.compareTo(2) >= 1;",
" }",
"}")
.expectErrorMessage(
"KEY", msg -> msg.contains("consistency") && !msg.contains("implementation"))
.doTest();
}
@Test
public void positiveAddition() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" int test(Integer i) {",
" // BUG: Diagnostic contains:",
" return i.compareTo(2) + i.compareTo(3);",
" }",
"}")
.doTest();
}
@Test
public void stringConcat_ignored() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" String test(Integer i) {",
" return \"\" + i.compareTo(3);",
" }",
"}")
.doTest();
}
@Test
public void refactoring() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" void test(Integer i) {",
" boolean b1 = i.compareTo(2) == -1;",
" boolean b2 = i.compareTo(2) > -1;",
" boolean b3 = -1 < i.compareTo(2);",
" boolean b4 = i.compareTo(2) < 1;",
" boolean b5 = i.compareTo(2) != -1;",
" boolean b6 = i.compareTo(2) != 1;",
" boolean b7 = i.compareTo(2) <= -1;",
" boolean b8 = ((i.compareTo(2))) >= 1;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" void test(Integer i) {",
" boolean b1 = i.compareTo(2) < 0;",
" boolean b2 = i.compareTo(2) >= 0;",
" boolean b3 = i.compareTo(2) >= 0;",
" boolean b4 = i.compareTo(2) <= 0;",
" boolean b5 = i.compareTo(2) >= 0;",
" boolean b6 = i.compareTo(2) <= 0;",
" boolean b7 = i.compareTo(2) < 0;",
" boolean b8 = ((i.compareTo(2))) > 0;",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test(Integer i) {",
" boolean b1 = i.compareTo(2) < 0;",
" boolean b2 = i.compareTo(2) > 0;",
" boolean b3 = i.compareTo(2) == 0;",
" }",
"}")
.doTest();
}
}
| 4,728
| 29.908497
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ByteBufferBackingArrayTest.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;
/** Test for ByteBufferBackingArray bug checker */
@RunWith(JUnit4.class)
public class ByteBufferBackingArrayTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ByteBufferBackingArray.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("ByteBufferBackingArrayPositiveCases.java").doTest();
}
@Test
public void negativeCases() {
compilationHelper.addSourceFile("ByteBufferBackingArrayNegativeCases.java").doTest();
}
@Test
public void i1004() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.nio.ByteBuffer;",
"public class Test {",
" public void ByteBufferBackingArrayTest() {",
" byte[] byteArray = ((ByteBuffer) new Object()).array();",
" }",
"}")
.doTest();
}
}
| 1,702
| 29.963636
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JavaLangClashTest.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.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link JavaLangClash}Test */
@RunWith(JUnit4.class)
public class JavaLangClashTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(JavaLangClash.class, getClass());
// TODO(b/67718586): javac 9 doesn't want to compile sources in java.lang
private static final ImmutableList<String> JAVA8_JAVACOPTS =
ImmutableList.of("-source", "8", "-target", "8");
@Test
public void positive() {
testHelper
.addSourceLines(
"foo/String.java", //
"package foo;",
"// BUG: Diagnostic contains:",
"public class String {}")
.doTest();
}
@Test
public void positiveTypeParameter() {
testHelper
.addSourceLines(
"java/lang/Foo.java", //
"package java.lang;",
"// BUG: Diagnostic contains:",
"public class Foo<String> {}")
.setArgs(JAVA8_JAVACOPTS)
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"java/lang/String.java", //
"package java.lang;",
"public class String {}")
.setArgs(JAVA8_JAVACOPTS)
.doTest();
}
@Test
public void negativeNonPublic() {
testHelper
.addSourceLines(
"test/AssertionStatusDirectives.java", //
"package Test;",
"public class AssertionStatusDirectives {}")
.doTest();
}
@Test
public void negative_compiler() {
testHelper
.addSourceLines(
"Compiler.java", //
"package p;",
"public class Compiler {}")
.doTest();
}
@Test
public void negative_module() {
testHelper
.addSourceLines(
"Module.java", //
"package p;",
"public class Module {}")
.doTest();
}
}
| 2,702
| 26.03
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LongFloatConversionTest.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;
/** {@link LongFloatConversion}Test */
@RunWith(JUnit4.class)
public class LongFloatConversionTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(LongFloatConversion.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" void f(Long l) {}",
" void f(float l) {}",
" {",
" // BUG: Diagnostic contains:",
" f(0L);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" void f(float l) {}",
" {",
" f((float) 0L);",
" }",
"}")
.doTest();
}
@Test
public void methodHandle() {
testHelper
.addSourceLines(
"Test.java",
"import java.lang.invoke.MethodHandle;",
"import java.nio.ByteBuffer;",
"class Test {",
" private static final long L = 42;",
" private static final MethodHandle MH = null;",
" long f(ByteBuffer buf) {",
" try {",
" return (long) MH.invoke(buf, L);",
" } catch (Throwable throwable) {",
" return 0;",
" }",
" }",
"}")
.doTest();
}
}
| 2,290
| 26.939024
| 79
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ModifiedButNotUsedTest.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.BugCheckerRefactoringTestHelper.FixChoosers;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link ModifiedButNotUsed} bugpattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class ModifiedButNotUsedTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ModifiedButNotUsed.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(ModifiedButNotUsed.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" void test() {",
" // BUG: Diagnostic contains:",
" List<Integer> foo = new ArrayList<>();",
" foo.add(1);",
" List<Integer> bar;",
" // BUG: Diagnostic contains:",
" bar = new ArrayList<>();",
" bar.add(1);",
" }",
"}")
.doTest();
}
@Test
public void sideEffectFreeRefactoring() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" void test() {",
" List<Integer> foo = new ArrayList<>();",
" foo.add(1);",
" List<Integer> bar = new ArrayList<>();",
" bar.add(sideEffects());",
" List<Integer> baz;",
" baz = new ArrayList<>();",
" baz.add(sideEffects());",
" }",
" int sideEffects() { return 1; }",
"}")
.addOutputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" void test() {",
" }",
" int sideEffects() { return 1; }",
"}")
.doTest();
}
@Test
public void sideEffectPreservingRefactoring() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" void test() {",
" List<Integer> bar = new ArrayList<>();",
" bar.add(sideEffects());",
" List<Integer> baz;",
" baz = new ArrayList<>();",
" baz.add(sideEffects());",
" }",
" int sideEffects() { return 1; }",
"}")
.addOutputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" void test() {",
" sideEffects();",
" sideEffects();",
" }",
" int sideEffects() { return 1; }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void negatives() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"abstract class Test {",
" void test() {",
" List<Integer> foo = new ArrayList<>();",
" foo.add(1);",
" if (false) { foo = new ArrayList<>(); }",
" int a = foo.get(0);",
" }",
" void test2() {",
" List<Integer> foo = new ArrayList<>();",
" foo.add(1);",
" incoming(foo);",
" }",
" abstract void incoming(List<Integer> l);",
"}")
.doTest();
}
@Test
public void usedByAssignment() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" private List<Integer> bar;",
" void test() {",
" List<Integer> foo = new ArrayList<>();",
" foo.add(1);",
" bar = foo;",
" }",
"}")
.doTest();
}
@Test
public void usedDuringAssignment() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"abstract class Test {",
" private List<Integer> bar;",
" void test() {",
" List<Integer> foo = new ArrayList<>();",
" foo.add(1);",
" foo = frobnicate(foo);",
" }",
" abstract List<Integer> frobnicate(List<Integer> a);",
"}")
.doTest();
}
@Test
public void negativeAfterReassignment() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" void test() {",
" List<Integer> foo = new ArrayList<>();",
" foo.add(1);",
" foo.get(0);",
" foo = new ArrayList<>();",
" foo.add(1);",
" foo.get(0);",
" }",
"}")
.doTest();
}
@Test
public void proto() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" static void foo() {",
" // BUG: Diagnostic contains:",
" TestProtoMessage.Builder proto = TestProtoMessage.newBuilder();",
" proto.setMessage(TestFieldProtoMessage.newBuilder());",
" TestProtoMessage.Builder proto2 =",
" // BUG: Diagnostic contains:",
" TestProtoMessage.newBuilder().setMessage(TestFieldProtoMessage.newBuilder());",
" TestProtoMessage.Builder proto3 =",
" // BUG: Diagnostic contains:",
" TestProtoMessage.getDefaultInstance().toBuilder().clearMessage();",
" TestProtoMessage.Builder proto4 =",
" // BUG: Diagnostic contains:",
" TestProtoMessage.getDefaultInstance().toBuilder().clear();",
" }",
"}")
.doTest();
}
@Test
public void protoSideEffects() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void foo() {",
" TestProtoMessage.Builder proto = TestProtoMessage.newBuilder();",
" TestFieldProtoMessage.Builder builder = TestFieldProtoMessage.newBuilder();",
" proto.setMessage(builder).setMessage(sideEffects());",
" }",
" TestFieldProtoMessage sideEffects() { throw new UnsupportedOperationException(); }",
"}")
.addOutputLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void foo() {",
" TestFieldProtoMessage.Builder builder = TestFieldProtoMessage.newBuilder();",
" sideEffects();",
" }",
" TestFieldProtoMessage sideEffects() { throw new UnsupportedOperationException(); }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void protoNegative() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" static TestProtoMessage foo() {",
" TestProtoMessage.Builder proto = TestProtoMessage.newBuilder();",
" return proto.setMessage(TestFieldProtoMessage.newBuilder()).build();",
" }",
"}")
.doTest();
}
@Test
public void immutableCollection() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" static void foo() {",
" // BUG: Diagnostic contains:",
" ImmutableList.Builder<Integer> a = ImmutableList.builder();",
" a.add(1);",
" // BUG: Diagnostic contains:",
" ImmutableList.Builder<Integer> b = ImmutableList.<Integer>builder().add(1);",
" b.add(1);",
" }",
"}")
.doTest();
}
@Test
public void protoUnusedExpression() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void foo(TestProtoMessage proto) {",
" // BUG: Diagnostic contains:",
" proto.toBuilder().setMessage(TestFieldProtoMessage.newBuilder()).build();",
" // BUG: Diagnostic contains:",
" proto.toBuilder().setMessage(TestFieldProtoMessage.newBuilder());",
" }",
"}")
.doTest();
}
@Test
public void protoBuilderMergeFrom() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void foo(TestProtoMessage proto) throws Exception {",
" // BUG: Diagnostic contains:",
" TestProtoMessage.newBuilder().mergeFrom(new byte[0]).build();",
" }",
"}")
.doTest();
}
@Test
public void protoUnusedExpressionViaBuilderGetter() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"class Test {",
" void foo(TestProtoMessage proto) {",
" // BUG: Diagnostic contains:",
" proto.toBuilder().getMessageBuilder().clearField().build();",
" }",
"}")
.doTest();
}
@Test
public void collectionUnusedExpression() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" void foo() {",
" // BUG: Diagnostic contains:",
" ImmutableList.<Integer>builder().add(1).build();",
" // BUG: Diagnostic contains:",
" ImmutableList.<Integer>builder().add(1);",
" }",
"}")
.doTest();
}
}
| 12,532
| 33.717452
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FuzzyEqualsShouldNotBeUsedInEqualsMethodTest.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 FuzzyEqualsShouldNotBeUsedInEqualsMethodTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FuzzyEqualsShouldNotBeUsedInEqualsMethod.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceFile("FuzzyEqualsShouldNotBeUsedInEqualsMethodPositiveCases.java")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceFile("FuzzyEqualsShouldNotBeUsedInEqualsMethodNegativeCases.java")
.doTest();
}
}
| 1,431
| 30.130435
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ParameterCommentTest.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;
/** {@link ParameterComment}Test */
@RunWith(JUnit4.class)
public class ParameterCommentTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(ParameterComment.class, getClass());
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(ParameterComment.class, getClass());
@Test
public void positive() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f(int x, int y) {}",
" {",
" f(0/*x*/, 1/*y=*/);",
" f(0/*x*/, 1); // y",
" f(/* x */ 0, /* y */ 1);",
" f(0 /* x */, /* y */ 1);",
" f(/* x */ 0, 1 /* y */);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f(int x, int y) {}",
" {",
" f(/* x= */ 0, /* y= */ 1);",
" f(/* x= */ 0, /* y= */ 1);",
" f(/* x= */ 0, /* y= */ 1);",
" f(/* x= */ 0, /* y= */ 1);",
" f(/* x= */ 0, /* y= */ 1);",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void negative() {
compilationTestHelper
.addSourceLines(
"in/Test.java",
"class Test {",
" void f(int x, int y) {}",
" {",
" f(/* x= */0, /* y = */1);",
" f(0 /*y=*/, 1 /*x=*/); ",
" }",
"}")
.doTest();
}
@Test
public void varargs() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" void f(int y, int... xs) {}",
" {",
" f(0/*y*/);",
" f(0/*y*/, 1/*xs*/);",
" f(0, new int[]{0}/*xs*/);",
" f(0, 1, 2/*xs*/, 3/*xs*/);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f(int y, int... xs) {}",
" {",
" f(/* y= */ 0);",
" f(/* y= */ 0, /* xs= */ 1);",
" f(0, /* xs= */ new int[]{0});",
" f(0, 1, /* xs= */ 2, /* xs= */ 3);",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void noParams() {
testHelper
.addInputLines(
"in/Test.java", //
"class Test {",
" void f() {}",
" {",
" f();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void positiveConstructor() {
testHelper
.addInputLines(
"in/Test.java",
"class Test {",
" Test (int x, int y) {}",
" {",
" new Test(0/*x*/, 1/*y=*/);",
" new Test(0/*x*/, 1); // y",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" Test (int x, int y) {}",
" {",
" new Test(/* x= */ 0, /* y= */ 1);",
" new Test(/* x= */ 0, /* y= */ 1); ",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void parameterComment_doesNotChange_whenNestedComment() {
testHelper
.addInputLines(
"in/Test.java",
"abstract class Test {",
" abstract void target(Object first, Object second);",
" abstract Object target2(Object second);",
" void test(Object first, Object second) {",
" target(first, target2(/* second= */ second));",
" }",
"}")
.addOutputLines(
"out/Test.java",
"abstract class Test {",
" abstract void target(Object first, Object second);",
" abstract Object target2(Object second);",
" void test(Object first, Object second) {",
" target(first, target2(/* second= */ second));",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void parameterComment_nestedComment() {
testHelper
.addInputLines(
"in/Test.java",
"abstract class Test {",
" abstract void target(Object first, Object second);",
" abstract Object target2(Object second);",
" void test(Object first, Object second) {",
" target(first, target2(second /* second */));",
" }",
"}")
.addOutputLines(
"out/Test.java",
"abstract class Test {",
" abstract void target(Object first, Object second);",
" abstract Object target2(Object second);",
" void test(Object first, Object second) {",
" target(first, target2(/* second= */ second));",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void negative_multiLineTernary() {
compilationTestHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public static int foo(int x) {",
" int y = true ? ",
" foo(/* x= */ x) : foo(/* x= */ x);",
" int z = true ? ",
" foo(/* x= */ x) :",
" foo(/* x= */ x);",
" return 0;",
" }",
"}")
.expectNoDiagnostics()
.doTest();
}
@Test
public void negative_nestedLambda() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.function.Consumer;",
"public class Test {",
" private void testcase(String s, Consumer<Boolean> c) {",
" outer(",
" p -> {",
" System.out.println(s);",
" inner(",
" /* myFunc= */ c,",
" /* i1= */ 200,",
" /* i2= */ 300);",
" },",
" /* b1= */ true,",
" /* b2= */ false);",
" }",
" private void outer(Consumer<Boolean> myFunc, boolean b1, boolean b2) {}",
" private void inner(Consumer<Boolean> myFunc, int i1, int i2) {}",
"}")
.expectNoDiagnostics()
.doTest();
}
@Test
public void matchingCommentsAfterwards() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"class Test {",
" public Test a(int a) { return this; }",
" public int b(int b) { return 1; }",
" public void test(Test x) {",
" assertThat(x.a(/* a= */ 1).b(/* b= */ 0)).isEqualTo(1);",
" assertThat(x.a(/* a= */ 2).b(/* b= */ 0)).isEqualTo(1);",
" }",
"}")
.doTest();
}
}
| 8,079
| 30.317829
| 88
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InjectOnBugCheckersTest.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.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class InjectOnBugCheckersTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(InjectOnBugCheckers.class, getClass());
@Test
public void positive() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.ErrorProneFlags;",
"import com.google.errorprone.bugpatterns.BugChecker;",
"@BugPattern(summary = \"\", severity = BugPattern.SeverityLevel.WARNING)",
"public class Test extends BugChecker {",
" // BUG: Diagnostic contains: @Inject",
" public Test(ErrorProneFlags f) {}",
"}")
.doTest();
}
@Test
public void notTheActualBugPattern_noFinding() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.ErrorProneFlags;",
"import com.google.errorprone.bugpatterns.BugChecker;",
"public class Test extends BugChecker {",
" public Test(ErrorProneFlags f) {}",
"}")
.doTest();
}
@Test
public void zeroArgConstructor_noFinding() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.bugpatterns.BugChecker;",
"@BugPattern(summary = \"\", severity = BugPattern.SeverityLevel.WARNING)",
"public class Test extends BugChecker {",
" public Test() {}",
"}")
.doTest();
}
@Test
public void alreadyAnnotated_noFinding() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.ErrorProneFlags;",
"import com.google.errorprone.bugpatterns.BugChecker;",
"import javax.inject.Inject;",
"@BugPattern(summary = \"\", severity = BugPattern.SeverityLevel.WARNING)",
"public class Test extends BugChecker {",
" @Inject",
" public Test(ErrorProneFlags f) {}",
"}")
.doTest();
}
}
| 3,089
| 33.719101
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IsInstanceIncompatibleTypeTest.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 IsInstanceIncompatibleType}Test */
@RunWith(JUnit4.class)
public class IsInstanceIncompatibleTypeTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(IsInstanceIncompatibleType.class, getClass());
@Test
public void positiveInstanceOf() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" Optional<String> f(Optional<String> s) {",
" // BUG: Diagnostic contains: String cannot be cast to Integer",
" return s.filter(Integer.class::isInstance);",
" }",
"}")
.doTest();
}
@Test
public void positiveInstanceOf_methodCall() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" Optional<String> f(Optional<String> s) {",
" // BUG: Diagnostic contains: String cannot be cast to Integer",
" return s.filter(x -> Integer.class.isInstance(x));",
" }",
"}")
.doTest();
}
@Test
public void positiveInstanceOf2() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"import java.util.HashMap;",
"class Test {",
" Optional<HashMap<String,Integer>> f(Optional<HashMap<String,Integer>> m) {",
" // BUG: Diagnostic contains: HashMap cannot be cast to Integer",
" return m.filter(Integer.class::isInstance);",
" }",
"}")
.doTest();
}
@Test
public void positiveInstanceOfWithGenerics() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"import java.lang.Number;",
"class Test {",
" <T extends Number> Optional<T> f(Optional<T> t) {",
" // BUG: Diagnostic contains: Number cannot be cast to String",
" return t.filter(String.class::isInstance);",
" }",
"}")
.doTest();
}
@Test
public void negativeInstanceOf() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"import java.util.HashMap;",
"import java.util.LinkedHashMap;",
"class Test {",
" Optional<HashMap> f(Optional<HashMap> m) {",
" return m.filter(LinkedHashMap.class::isInstance);",
" }",
"}")
.doTest();
}
@Test
public void negativeInstanceOf_methodCall() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"import java.util.HashMap;",
"import java.util.LinkedHashMap;",
"class Test {",
" Optional<HashMap> f(Optional<HashMap> m) {",
" return m.filter(x -> LinkedHashMap.class.isInstance(x));",
" }",
"}")
.doTest();
}
@Test
public void negativeInstanceOf2() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"import java.util.HashMap;",
"import java.util.LinkedHashMap;",
"class Test {",
" Optional<HashMap<String, Integer>> f(Optional<HashMap<String,Integer>> m) {",
" return m.filter(LinkedHashMap.class::isInstance);",
" }",
"}")
.doTest();
}
@Test
public void negativeInstanceOfWithGenerics() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" <T> Optional<T> f(Optional<T> t) {",
" return t.filter(Object.class::isInstance);",
" }",
"}")
.doTest();
}
@Test
public void rawTypes() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" boolean f(Object o, Class c) {",
" return c.isInstance(o);",
" }",
" <T> Optional<T> f(Optional<T> t, Class c) {",
" return t.filter(c::isInstance);",
" }",
"}")
.doTest();
}
}
| 5,214
| 29.319767
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DirectInvocationOnMockTest.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.assumeTrue;
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 DirectInvocationOnMock}. */
@RunWith(JUnit4.class)
public final class DirectInvocationOnMockTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(DirectInvocationOnMock.class, getClass());
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(DirectInvocationOnMock.class, getClass());
@Test
public void directInvocationOnMock() {
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"class Test {",
" public void test() {",
" Test test = mock(Test.class);",
" // BUG: Diagnostic contains: test",
" test.test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMockAssignment() {
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"class Test {",
" public void test() {",
" Test test;",
" test = mock(Test.class);",
" // BUG: Diagnostic contains:",
" test.test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_suggestsVerify() {
refactoring
.addInputLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.verify;",
"class Test {",
" public void test() {",
" Test test = mock(Test.class);",
" test.test();",
" }",
"}")
.addOutputLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.verify;",
"class Test {",
" public void test() {",
" Test test = mock(Test.class);",
" verify(test).test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_mockHasExtraOptions_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import org.mockito.Answers;",
"class Test {",
" public void test() {",
" Test test = mock(Test.class, Answers.RETURNS_DEEP_STUBS);",
" test.test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMockAnnotatedField() {
helper
.addSourceLines(
"Test.java",
"import org.mockito.Mock;",
"class Test {",
" @Mock public Test test;",
" public void test() {",
" // BUG: Diagnostic contains:",
" test.test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMockAnnotatedField_mockHasExtraOptions_noFinding() {
helper
.addSourceLines(
"Test.java",
"import org.mockito.Answers;",
"import org.mockito.Mock;",
"class Test {",
" @Mock(answer = Answers.RETURNS_DEEP_STUBS) public Test test;",
" public void test() {",
" test.test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_withinWhen_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.when;",
"class Test {",
" public Object test() {",
" Test test = mock(Test.class);",
" when(test.test()).thenReturn(null);",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_withinGiven_noFinding() {
assumeTrue(isBddMockitoAvailable());
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.BDDMockito.given;",
"class Test {",
" public Object test() {",
" Test test = mock(Test.class);",
" given(test.test()).willReturn(null);",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_setUpToCallRealMethod_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.when;",
"class Test {",
" public Object test() {",
" Test test = mock(Test.class);",
" when(test.test()).thenCallRealMethod();",
" return test.test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_setUpToCallRealMethodUsingGiven_noFinding() {
assumeTrue(isBddMockitoAvailable());
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.BDDMockito.given;",
"class Test {",
" public Object test() {",
" Test test = mock(Test.class);",
" given(test.test()).willCallRealMethod();",
" return test.test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_setUpWithDoCallRealMethod_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.doCallRealMethod;",
"class Test {",
" public Object test() {",
" Test test = mock(Test.class);",
" doCallRealMethod().when(test).test();",
" return test.test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_setUpWithDoCallRealMethodUsingGiven_noFinding() {
assumeTrue(isBddMockitoAvailable());
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.BDDMockito.willCallRealMethod;",
"class Test {",
" public Object test() {",
" Test test = mock(Test.class);",
" willCallRealMethod().given(test).test();",
" return test.test();",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_withinCustomWhen_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import org.mockito.stubbing.OngoingStubbing;",
"class Test {",
" public <T> OngoingStubbing<T> when(T t) {",
" return org.mockito.Mockito.when(t);",
" }",
" public Object test() {",
" Test test = mock(Test.class);",
" when(test.test()).thenReturn(null);",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_withinCustomGiven_noFinding() {
assumeTrue(isBddMockitoAvailable());
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import org.mockito.BDDMockito.BDDMyOngoingStubbing;",
"class Test {",
" public <T> BDDMyOngoingStubbing<T> given(T t) {",
" return org.mockito.BDDMockito.given(t);",
" }",
" public Object test() {",
" Test test = mock(Test.class);",
" given(test.test()).willReturn(null);",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_withinWhenWithCast_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.when;",
"class Test {",
" public Object test() {",
" Test test = mock(Test.class);",
" when((Object) test.test()).thenReturn(null);",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void directInvocationOnMock_withinGivenWithCast_noFinding() {
assumeTrue(isBddMockitoAvailable());
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.BDDMockito.given;",
"class Test {",
" public Object test() {",
" Test test = mock(Test.class);",
" given((Object) test.test()).willReturn(null);",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void finalMethodInvoked_noFinding() {
helper
.addSourceLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"class Test {",
" public Object test() {",
" Test test = mock(Test.class);",
" return test.getClass();",
" }",
"}")
.doTest();
}
private static boolean isBddMockitoAvailable() {
try {
Class.forName("org.mockito.BDDMockito");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
| 10,694
| 29.732759
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ReturnValueIgnoredTest.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;
/** Tests for {@link ReturnValueIgnored}. */
@RunWith(JUnit4.class)
public class ReturnValueIgnoredTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ReturnValueIgnored.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(ReturnValueIgnored.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("ReturnValueIgnoredPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("ReturnValueIgnoredNegativeCases.java").doTest();
}
@Test
public void function() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" void f(Function<Integer, Integer> f) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" f.apply(0);",
" }",
"}")
.doTest();
}
@Test
public void consumer() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.function.Consumer;",
"class Test {",
" void f(Consumer<Integer> f) {",
" f.accept(0);",
" }",
"}")
.doTest();
}
@Test
public void functionVoid() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" void f(Function<Integer, Void> f) {",
" f.apply(0);",
" }",
"}")
.doTest();
}
@Test
public void ignoreInTests() {
compilationHelper
.addSourceLines(
"Test.java",
"import static org.junit.Assert.fail;",
"import java.util.function.Function;",
"class Test {",
" void f(Function<Integer, Integer> f) {",
" try {",
" f.apply(0);",
" fail();",
" } catch (Exception expected) {}",
" }",
"}")
.doTest();
}
@Test
public void stream() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" \"\".codePoints().count();",
" \"\".codePoints().forEach(i -> {});",
" }",
"}")
.doTest();
}
@Test
public void javaTime() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.Duration;",
"import java.time.LocalDate;",
"import java.time.ZoneId;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Duration.ZERO.plusDays(2);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Duration.ZERO.toDays();",
// We ignore parse() methods on java.time types
" Duration.parse(\"PT20.345S\");",
" LocalDate.parse(\"2007-12-03\");",
// We ignore of() methods on java.time types
" LocalDate.of(1985, 5, 31);",
// We ignore ZoneId.of() -- it's effectively a parse() method
" ZoneId.of(\"America/New_York\");",
" }",
"}")
.doTest();
}
@Test
public void optionalStaticMethods() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void optional() {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Optional.empty();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Optional.of(42);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Optional.ofNullable(null);",
" }",
"}")
.doTest();
}
@Test
public void optionalInstanceMethods() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void optional() {",
" Optional<Integer> optional = Optional.of(42);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.filter(v -> v > 40);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.flatMap(v -> Optional.of(v + 1));",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.get();",
" optional.ifPresent(v -> {});",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.isPresent();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.map(v -> v + 1);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.orElse(40);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.orElseGet(() -> 40);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.orElseThrow(() -> new RuntimeException());",
" }",
"}")
.doTest();
}
@Test
public void optionalInstanceMethods_jdk9() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void optional() {",
" Optional<Integer> optional = Optional.of(42);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.or(() -> Optional.empty());",
" }",
"}")
.doTest();
}
@Test
public void optionalInstanceMethods_jdk10() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void optional() {",
" Optional<Integer> optional = Optional.of(42);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.orElseThrow();",
" }",
"}")
.doTest();
}
@Test
public void optionalInstanceMethods_jdk11() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void optional() {",
" Optional<Integer> optional = Optional.of(42);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" optional.isEmpty();",
" }",
"}")
.doTest();
}
@Test
public void timeUnitApis() {
compilationHelper
.addSourceLines(
"Test.java",
"import static java.util.concurrent.TimeUnit.MILLISECONDS;",
"class Test {",
" void timeUnit() {",
" long ms = 4200;",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" MILLISECONDS.toNanos(ms);",
" }",
"}")
.doTest();
}
@Test
public void issue1565_enumDeclaration() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"enum Test {",
" A;",
" void f(Function<Integer, Integer> f) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" f.apply(0);",
" }",
"}")
.doTest();
}
@Test
public void issue1363_dateTimeFormatterBuilder() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.format.DateTimeFormatterBuilder;",
"class Test {",
" void f() {",
" DateTimeFormatterBuilder formatter = new DateTimeFormatterBuilder();",
" formatter.appendZoneId();",
" formatter.optionalEnd();",
" formatter.padNext(5);",
" formatter.parseCaseSensitive();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" formatter.toFormatter();",
" }",
"}")
.doTest();
}
@Test
public void issue876() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.nio.file.Path;",
"abstract class Test {",
" void test(Path p) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" E e = p::toRealPath;",
" }",
" abstract <T> void a(T t);",
" public interface E {",
" void run() throws Exception;",
" }",
"}")
.doTest();
}
@Test
public void collectionContains() {
compilationHelper
.addSourceLines(
"Test.java",
"abstract class Test {",
" void test(java.util.List p) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" p.contains(null);",
" }",
"}")
.doTest();
}
@Test
public void mapMethods() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Map;",
"public final class Test {",
" void doTest(Map<Integer, Integer> map) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" map.isEmpty();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" map.size();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" map.entrySet();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" map.keySet();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" map.values();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" map.containsKey(42);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" map.containsValue(42);",
" }",
" void doTest(Map.Entry<Integer, Integer> entry) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" entry.getKey();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" entry.getValue();",
" entry.setValue(42);",
" }",
"}")
.doTest();
}
@Test
public void mapMethods_java11() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Map;",
"class Test {",
" void doTest() {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Map.of(42, 42);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Map.entry(42, 42);",
" }",
" void doTest(Map<Integer, Integer> map) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Map.copyOf(map);",
" }",
" void doTest(Map.Entry<Integer, Integer>... entries) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Map.ofEntries(entries);",
" }",
"}")
.doTest();
}
@Test
public void methodReferenceToObject() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.function.Function;",
"abstract class Test {",
" void test(Function<Integer, Long> fn) {",
" foo(fn::apply);",
" }",
" void foo(Function<Integer, Object> fn) {",
" }",
"}")
.doTest();
}
@Test
public void integers() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() throws Exception {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Integer.reverse(2);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" new Integer(2).doubleValue();",
// We ignore the following "parsing" style methods:
" Integer.decode(\"1985\");",
" Integer.parseInt(\"1985\");",
" Integer.parseInt(\"1985\", 10);",
" Integer.parseUnsignedInt(\"1985\");",
" Integer.parseUnsignedInt(\"1985\", 10);",
" Integer.valueOf(\"1985\");",
" Integer.valueOf(\"1985\", 10);",
" }",
"}")
.doTest();
}
@Test
public void constructors() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() throws Exception {",
// TODO: we haven't yet enabled constructor checking for basic types yet,
// just making sure it doesn't crash
" new String(\"Hello\");",
" }",
"}")
.doTest();
}
@Test
public void protoMessageNewBuilder() {
compilationHelper
.addSourceLines(
"test.java",
"import com.google.protobuf.Duration;",
"class Test {",
" public void proto_newBuilder() {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Duration.newBuilder();",
" Duration.Builder builder = Duration.newBuilder();",
" Duration duration = Duration.newBuilder().setSeconds(4).build();",
" }",
"}")
.doTest();
}
@Test
public void protoMessageBuildBuildPartial() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.protobuf.Duration;",
"final class Test {",
" public void proto_build() {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Duration.newBuilder().setSeconds(4).build();",
" Duration duration = Duration.newBuilder().setSeconds(4).build();",
" }",
" public void proto_buildPartial() {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Duration.newBuilder().setSeconds(4).buildPartial();",
" Duration duration = Duration.newBuilder().setSeconds(4).buildPartial();",
" }",
"}")
.doTest();
}
@Test
public void refactoringDeletesConstantExpressionCall() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"import java.util.stream.Stream;",
"final class Test {",
" public void f() {",
" Optional.of(42);",
" Optional.of(42).orElseThrow(AssertionError::new);",
" Stream.of(Optional.of(42)).forEach(o -> o.orElseThrow(AssertionError::new));",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"import java.util.stream.Stream;",
"final class Test {",
" public void f() {",
" var unused = Optional.of(42).orElseThrow(AssertionError::new);",
" Stream.of(Optional.of(42)).forEach(o -> o.orElseThrow(AssertionError::new));",
" }",
"}")
.doTest();
}
@Test
public void refactoringAssignsToOriginal() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f(Optional<Integer> o) {",
" o.map(i -> i + 1);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" void f(Optional<Integer> o) {",
" o = o.map(i -> i + 1);",
" }",
"}")
.doTest();
}
@Test
public void refactoringDoesNotAssignToOriginalForTypeArgumentMismatch() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"final class Test {",
" public void f() {",
" Optional<Integer> o = Optional.of(42);",
" o.map(i -> \"value is \" + i);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"final class Test {",
" public void f() {",
" Optional<Integer> o = Optional.of(42);",
" var unused = o.map(i -> \"value is \" + i);",
" }",
"}")
.doTest();
}
@Test
public void iterableHasNext() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Iterator;",
"final class Test {",
" private static class CustomIterator implements Iterator<String> {",
" @Override public boolean hasNext() { return true; }",
" public boolean hasNext(boolean unused) { return true; }",
" @Override public String next() { return \"hi\"; }",
" public boolean nonInterfaceMethod() { return true; }",
" }",
" public void iteratorHasNext() {",
" CustomIterator iterator = new CustomIterator();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" iterator.hasNext();",
" iterator.next();", // this is OK (some folks next their way through an Iterator)
" iterator.hasNext(true);", // this is OK (it's an overload but not on the interface)
" iterator.nonInterfaceMethod();", // this is OK (it's not an interface method)
" }",
"}")
.doTest();
}
@Test
public void collectionToArray() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"final class Test {",
" private static final ImmutableList<Long> LIST = ImmutableList.of(42L);",
" public void collectionToArray() {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" LIST.toArray();",
// Collection.toArray(T[]) is fine, since it _can_ dump the collection contents into the
// passed-in array *if* the array is large enough (in which case, you don't have to
// check the return value of the method call).
" LIST.toArray(new Long[0]);",
" }",
"}")
.doTest();
}
@Test
public void collectionToArray_java8() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"final class Test {",
" private static final ImmutableList<Long> LIST = ImmutableList.of(42L);",
" public void collectionToArray() {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" LIST.toArray(Long[]::new);",
" }",
"}")
.doTest();
}
@Test
public void objectMethods() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test(Test t, Object o) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" t.equals(o);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" o.equals(t);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" t.hashCode();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" t.getClass();",
" }",
"}")
.doTest();
}
@Test
public void charSequenceMethods() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test(CharSequence cs) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" cs.charAt(0);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" cs.chars();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" cs.codePoints();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" cs.length();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" cs.subSequence(1, 2);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" cs.toString();",
" }",
" void test(StringBuilder sb) {",
" sb.append(\"hi\");",
" }",
"}")
.doTest();
}
@Test
public void enumMethods() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.TimeUnit;",
"class Test {",
" void test(Enum e) {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" e.getDeclaringClass();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" e.name();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" e.ordinal();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" TimeUnit.valueOf(\"MILLISECONDS\");",
" }",
"}")
.doTest();
}
@Test
public void enumMethodsOnSubtype() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.lang.invoke.VarHandle;",
"class Test {",
" void test(VarHandle.AccessMode accessMode) {",
" accessMode.methodName();",
" }",
"}")
.doTest();
}
@Test
public void throwableMethods() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test(Throwable t) {",
// These 2 APIs are OK to ignore (they just return this)
" t.fillInStackTrace();",
" t.initCause(new Throwable());",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" t.getCause();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" t.getLocalizedMessage();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" t.getMessage();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" t.getStackTrace();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" t.getSuppressed();",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" t.toString();",
" }",
"}")
.doTest();
}
@Test
public void objectsMethods() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Objects;",
"class Test {",
" void test(Object o) {",
// These APIs are OK to ignore
" Objects.checkFromIndexSize(0, 1, 2);",
" Objects.checkFromToIndex(0, 1, 2);",
" Objects.checkIndex(0, 1);",
" Objects.requireNonNull(o);",
" Objects.requireNonNull(o, \"message\");",
" Objects.requireNonNull(o, () -> \"messageSupplier\");",
" Objects.requireNonNullElse(o, new Object());",
" Objects.requireNonNullElseGet(o, () -> new Object());",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Objects.compare(\"B\", \"a\", String.CASE_INSENSITIVE_ORDER);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Objects.deepEquals(new Object(), new Object());",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Objects.equals(new Object(), new Object());",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Objects.hash(new Object(), new Object());",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Objects.hashCode(o);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Objects.isNull(o);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Objects.nonNull(o);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Objects.toString(o);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Objects.toString(o, \"defaultValue\");",
" }",
"}")
.doTest();
}
@Test
public void classMethods() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test(Class<?> c) throws Exception {",
" Class.forName(\"java.sql.Date\");",
" c.getMethod(\"toString\");",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" c.desiredAssertionStatus();",
" }",
"}")
.doTest();
}
@Test
public void constructorOfAbstractModule() {
compilationHelper
.addSourceLines(
"TestModule.java",
"import com.google.inject.AbstractModule;",
"class TestModule extends AbstractModule {",
" public TestModule() {}",
" public static void foo() {",
" // BUG: Diagnostic contains: Ignored return value of 'TestModule'",
" new TestModule();",
" }",
"}")
.doTest();
}
@Test
public void constructorOfModule() {
compilationHelper
.addSourceLines(
"TestModule.java",
"import com.google.inject.Binder;",
"import com.google.inject.Module;",
"class TestModule implements Module {",
" public TestModule() {}",
" @Override public void configure(Binder binder) {}",
" public static void foo() {",
" // BUG: Diagnostic contains: Ignored return value of 'TestModule'",
" new TestModule();",
" }",
"}")
.doTest();
}
}
| 27,625
| 32.896933
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NarrowingCompoundAssignmentTest.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 cushon@google.com (Liam Miller-Cushon)
*/
@RunWith(JUnit4.class)
public class NarrowingCompoundAssignmentTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NarrowingCompoundAssignment.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" short s = 0;",
" char t = 0;",
" byte u = 0;",
" float v = 0;",
" // BUG: Diagnostic contains: s = (short) (s * 1)",
" s *= 1;",
" // BUG: Diagnostic contains: t = (char) (t * 1)",
" t *= 1;",
" // BUG: Diagnostic contains: u = (byte) (u * 1)",
" u *= 1;",
" // BUG: Diagnostic contains: u = (byte) (u * 1L)",
" u *= 1L;",
" // BUG: Diagnostic contains: v = (float) (v * 1.0)",
" v *= 1.0;",
" // BUG: Diagnostic contains: v = (float) (v * 1.0d)",
" v *= 1.0d;",
" }",
"}")
.doTest();
}
@Test
public void allOps() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" short s = 0;",
" // BUG: Diagnostic contains: s = (short) (s * 1)",
" s *= 1;",
" // BUG: Diagnostic contains: s = (short) (s / 1)",
" s /= 1;",
" // BUG: Diagnostic contains: s = (short) (s % 1)",
" s %= 1;",
" // BUG: Diagnostic contains: s = (short) (s + 1)",
" s += 1;",
" // BUG: Diagnostic contains: s = (short) (s - 1)",
" s -= 1;",
" // BUG: Diagnostic contains: s = (short) (s << 1)",
" s <<= 1;",
" // Signed right shifts are OK",
" s >>= 1;",
" // BUG: Diagnostic contains: s = (short) (s >>> 1)",
" s >>>= 1;",
" }",
"}")
.doTest();
}
@Test
public void deficientRightShift() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" // BUG: Diagnostic contains: i = (short) (i >>> 1)",
" for (short i = -1; i != 0; i >>>= 1);",
" }",
"}")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" int s = 0;",
" long t = 0;",
" double u = 0;",
" s *= 1;",
" t *= 1;",
" u *= 1;",
" }",
"}")
.doTest();
}
@Test
public void floatFloat() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" float a = 0;",
" float b = 0;",
" Float c = Float.valueOf(0);",
" a += b;",
" a += c;",
" }",
"}")
.doTest();
}
// bit twiddling deficient types with masks of the same width is fine
@Test
public void bitTwiddle() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" short smask = 0b1;",
" byte bmask = 0b1;",
"",
" short s = 0;",
" byte b = 0;",
"",
" s &= smask;",
" s |= smask;",
" s ^= smask;",
"",
" s &= bmask;",
" s |= bmask;",
" s ^= bmask;",
"",
" b &= bmask;",
" b |= bmask;",
" b ^= bmask;",
" }",
"}")
.doTest();
}
// bit twiddling deficient types with constant masks of the same width is fine
@Test
public void bitTwiddleConstant() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" short s = 0;",
" byte b = 0;",
"",
" s &= ~1;",
" s |= 1;",
" s ^= 1;",
"",
" b &= ~1;",
" b |= 1;",
" b ^= 1;",
"",
" b |= 128;",
" b &= 128;",
" b ^= 128;",
" b |= 1L;",
" b &= 1L;",
" b ^= 1L;",
"",
" // BUG: Diagnostic contains: b = (byte) (b | 256)",
" b |= 256;",
" // BUG: Diagnostic contains: b = (byte) (b & ~256)",
" b &= ~256;",
" // BUG: Diagnostic contains: b = (byte) (b ^ 256)",
" b ^= 256;",
" }",
"}")
.doTest();
}
@Test
public void allowsBinopsOfDeficientTypes() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" short smask = 0b1;",
" byte bmask = 0b1;",
"",
" short s = 0;",
" byte b = 0;",
"",
" s += smask;",
" s -= smask;",
" s *= smask;",
"",
" s += bmask;",
" s -= bmask;",
" s *= bmask;",
"",
" b -= bmask;",
" b += bmask;",
" b /= bmask;",
" }",
"}")
.doTest();
}
@Test
public void preservePrecedence() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" float f = 0;",
" // BUG: Diagnostic contains: f = (float) (f - (3.0 - 2.0))",
" f -= 3.0 - 2.0;",
" }",
"}")
.doTest();
}
@Test
public void preservePrecedence2() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" float f = 0;",
" // BUG: Diagnostic contains: f = (float) (f - 3.0 * 2.0)",
" f -= 3.0 * 2.0;",
" }",
"}")
.doTest();
}
@Test
public void preservePrecedence3() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" float f = 0;",
" // BUG: Diagnostic contains: f = (float) (f - (3.0 > 0 ? 1.0 : 2.0))",
" f -= 3.0 > 0 ? 1.0 : 2.0;",
" }",
"}")
.doTest();
}
@Test
public void preservePrecedenceExhaustive_multMult() throws Exception {
testPrecedence("*", "*", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_multPlus() throws Exception {
testPrecedence("*", "+", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_multLShift() throws Exception {
testPrecedence("*", "<<", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_multAnd() throws Exception {
testPrecedence("*", "&", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_multOr() throws Exception {
testPrecedence("*", "|", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_plusMult() throws Exception {
testPrecedence("+", "*", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_plusPlus() throws Exception {
testPrecedence("+", "+", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_plusLShift() throws Exception {
testPrecedence("+", "<<", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_plusAnd() throws Exception {
testPrecedence("+", "&", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_plusOr() throws Exception {
testPrecedence("+", "|", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_lShiftMult() throws Exception {
testPrecedence("<<", "*", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_lShiftPlus() throws Exception {
testPrecedence("<<", "+", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_lShiftLShift() throws Exception {
testPrecedence("<<", "<<", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_lShiftAnd() throws Exception {
testPrecedence("<<", "&", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_lShiftOr() throws Exception {
testPrecedence("<<", "|", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_andMult() throws Exception {
testPrecedence("&", "*", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_andPlus() throws Exception {
testPrecedence("&", "+", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_andLShift() throws Exception {
testPrecedence("&", "<<", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_andAnd() throws Exception {
testPrecedence("&", "&", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_andOr() throws Exception {
testPrecedence("&", "|", /* parens= */ true);
}
@Test
public void preservePrecedenceExhaustive_orMult() throws Exception {
testPrecedence("|", "*", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_orPlus() throws Exception {
testPrecedence("|", "+", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_orLShift() throws Exception {
testPrecedence("|", "<<", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_orAnd() throws Exception {
testPrecedence("|", "&", /* parens= */ false);
}
@Test
public void preservePrecedenceExhaustive_orOr() throws Exception {
testPrecedence("|", "|", /* parens= */ true);
}
private void testPrecedence(String opA, String opB, boolean parens) {
String rhs = String.format("100_000 %s 200_000", opB);
if (parens) {
rhs = "(" + rhs + ")";
}
String expect = String.format("s = (short) (s %s %s", opA, rhs);
String compoundAssignment = String.format(" s %s= 100_000 %s 200_000;", opA, opB);
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" short s = 0;",
" // BUG: Diagnostic contains: " + expect,
compoundAssignment,
" }",
"}")
.doTest();
}
@Test
public void doubleLong() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" long a = 1;",
" double b = 2;",
" // BUG: Diagnostic contains: Compound assignments from double to long",
" a *= b;",
" }",
"}")
.doTest();
}
@Test
public void doubleInt() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" int a = 1;",
" double b = 2;",
" // BUG: Diagnostic contains: Compound assignments from double to int",
" a *= b;",
" }",
"}")
.doTest();
}
@Test
public void floatLong() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" long a = 1;",
" float b = 2;",
" // BUG: Diagnostic contains: Compound assignments from float to long",
" a *= b;",
" }",
"}")
.doTest();
}
@Test
public void floatInt() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" int a = 1;",
" float b = 2;",
" // BUG: Diagnostic contains:" + " Compound assignments from float to int",
" a *= b;",
" }",
"}")
.doTest();
}
@Test
public void exhaustiveTypes() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f(short s, byte b, char c, int i, long l, float f, double d) {",
" s += s;",
" s += b;",
" // BUG: Diagnostic contains:",
" s += c;",
" // BUG: Diagnostic contains:",
" s += i;",
" // BUG: Diagnostic contains:",
" s += l;",
" // BUG: Diagnostic contains:",
" s += f;",
" // BUG: Diagnostic contains:",
" s += d;",
" // BUG: Diagnostic contains:",
" b += s;",
" b += b;",
" // BUG: Diagnostic contains:",
" b += c;",
" // BUG: Diagnostic contains:",
" b += i;",
" // BUG: Diagnostic contains:",
" b += l;",
" // BUG: Diagnostic contains:",
" b += f;",
" // BUG: Diagnostic contains:",
" b += d;",
" // BUG: Diagnostic contains:",
" c += s;",
" // BUG: Diagnostic contains:",
" c += b;",
" c += c;",
" // BUG: Diagnostic contains:",
" c += i;",
" // BUG: Diagnostic contains:",
" c += l;",
" // BUG: Diagnostic contains:",
" c += f;",
" // BUG: Diagnostic contains:",
" c += d;",
" i += s;",
" i += b;",
" i += c;",
" i += i;",
" // BUG: Diagnostic contains:",
" i += l;",
" // BUG: Diagnostic contains:",
" i += f;",
" // BUG: Diagnostic contains:",
" i += d;",
" l += s;",
" l += b;",
" l += c;",
" l += i;",
" l += l;",
" // BUG: Diagnostic contains:",
" l += f;",
" // BUG: Diagnostic contains:",
" l += d;",
" f += s;",
" f += b;",
" f += c;",
" f += i;",
" f += l;",
" f += f;",
" // BUG: Diagnostic contains:",
" f += d;",
" d += s;",
" d += b;",
" d += c;",
" d += i;",
" d += l;",
" d += f;",
" d += d;",
" }",
"}")
.doTest();
}
@Test
public void boxing() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" int a = 1;",
" // BUG: Diagnostic contains: from Long to int",
" a += (Long) 0L;",
" }",
"}")
.doTest();
}
@Test
public void stringConcat() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" String a = \"\";",
" a += (char) 0;",
" }",
"}")
.doTest();
}
}
| 16,926
| 27.024834
| 91
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DoubleBraceInitializationTest.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;
/** {@link DoubleBraceInitialization}Test */
@RunWith(JUnit4.class)
public class DoubleBraceInitializationTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(DoubleBraceInitialization.class, getClass());
@Test
public void negative() {
CompilationTestHelper.newInstance(DoubleBraceInitialization.class, getClass())
.addSourceLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" static final List<Integer> a = new ArrayList<Integer>();",
" static final Object o = new Object() {{",
" System.err.println(hashCode());",
" }};",
" static final List<Integer> b = new ArrayList<Integer>() {",
" {",
" add(1);",
" }",
" @Override public boolean add(Integer i) {",
" return true;",
" }",
" };",
" static final List<Integer> c = new ArrayList<Integer>() {",
" @Override public boolean add(Integer i) {",
" return true;",
" }",
" };",
"}")
.doTest();
}
@Test
public void positiveNoFix() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.ArrayList;",
"import java.util.List;",
"// BUG: Diagnostic contains:",
"class Test {",
" static final List<Integer> b = new ArrayList<Integer>() {{",
" addAll(this);",
" }};",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void list() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"class Test {",
" static final List<Integer> a = new ArrayList<Integer>() {{ add(1); add(2); }};",
" static final List<Integer> b = Collections.unmodifiableList(",
" new ArrayList<Integer>() {{ add(1); add(2); }});",
" List<Integer> c = new ArrayList<Integer>() {{ add(1); add(2); }};",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"class Test {",
" static final ImmutableList<Integer> a = ImmutableList.of(1, 2);",
" static final ImmutableList<Integer> b = ImmutableList.of(1, 2);",
" List<Integer> c = new ArrayList<Integer>(ImmutableList.of(1, 2));",
"}")
.doTest();
}
@Test
public void set() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.Collections;",
"import java.util.HashSet;",
"import java.util.Set;",
"class Test {",
" static final Set<Integer> a = new HashSet<Integer>() {{ add(1); add(2); }};",
" static final Set<Integer> b = Collections.unmodifiableSet(",
" new HashSet<Integer>() {{ add(1); add(2); }});",
" Set<Integer> c = new HashSet<Integer>() {{ add(1); add(2); }};",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.collect.ImmutableSet;",
"import java.util.Collections;",
"import java.util.HashSet;",
"import java.util.Set;",
"class Test {",
" static final ImmutableSet<Integer> a = ImmutableSet.of(1, 2);",
" static final ImmutableSet<Integer> b = ImmutableSet.of(1, 2);",
" Set<Integer> c = new HashSet<Integer>(ImmutableSet.of(1, 2));",
"}")
.doTest();
}
@Test
public void collection() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.ArrayDeque;",
"import java.util.Collection;",
"import java.util.Collections;",
"import java.util.Deque;",
"class Test {",
" static final Collection<Integer> a =",
" new ArrayDeque<Integer>() {{ add(1); add(2); }};",
" static final Collection<Integer> b = Collections.unmodifiableCollection(",
" new ArrayDeque<Integer>() {{ add(1); add(2); }});",
" Deque<Integer> c = new ArrayDeque<Integer>() {{ add(1); add(2); }};",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.collect.ImmutableCollection;",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayDeque;",
"import java.util.Collection;",
"import java.util.Collections;",
"import java.util.Deque;",
"class Test {",
" static final ImmutableCollection<Integer> a = ImmutableList.of(1, 2);",
" static final ImmutableCollection<Integer> b = ImmutableList.of(1, 2);",
" Deque<Integer> c = new ArrayDeque<Integer>(ImmutableList.of(1, 2));",
"}")
.doTest();
}
@Test
public void map() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.Collections;",
"import java.util.HashMap;",
"import java.util.Map;",
"class Test {",
" static final Map<Integer, String> a = new HashMap<Integer, String>() {{",
" put(1, \"a\"); put(2, \"b\"); ",
" }};",
" static final Map<Integer, String> b =",
" Collections.unmodifiableMap(new HashMap<Integer, String>() {{",
" put(1, \"a\"); put(2, \"b\"); ",
" }});",
" Map<Integer, String> c = new HashMap<Integer, String>() {{",
" put(1, \"a\"); put(2, \"b\"); ",
" }};",
" static final Map<Integer, String> d = new HashMap<Integer, String>() {{",
" put(1, \"a\");",
" put(2, \"b\"); ",
" put(3, \"c\"); ",
" put(4, \"d\"); ",
" put(5, \"e\"); ",
" put(6, \"f\"); ",
" }};",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.collect.ImmutableMap;",
"import java.util.Collections;",
"import java.util.HashMap;",
"import java.util.Map;",
"class Test {",
" static final ImmutableMap<Integer, String> a =",
" ImmutableMap.of(1, \"a\", 2, \"b\");",
" static final ImmutableMap<Integer, String> b =",
" ImmutableMap.of(1, \"a\", 2, \"b\");",
" Map<Integer, String> c =",
" new HashMap<Integer, String>(ImmutableMap.of(1, \"a\", 2, \"b\"));",
" static final ImmutableMap<Integer, String> d =",
" ImmutableMap.<Integer, String>builder()",
" .put(1, \"a\")",
" .put(2, \"b\")",
" .put(3, \"c\")",
" .put(4, \"d\")",
" .put(5, \"e\")",
" .put(6, \"f\")",
" .buildOrThrow();",
"}")
.doTest();
}
@Test
public void nulls() {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.*;",
"// BUG: Diagnostic contains:",
"class Test {",
" static final List<Integer> a = new ArrayList<Integer>() {{ add(null); }};",
" static final Set<Integer> b = new HashSet<Integer>() {{ add(null); }};",
" static final Map<String, Integer> c =",
" new HashMap<String, Integer>() {{ put(null, null); }};",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void returned() {
testHelper
.addInputLines(
"Test.java",
"import java.util.Collections;",
"import java.util.HashMap;",
"import java.util.Map;",
"class Test {",
" private Map<String, Object> test() {",
" return Collections.unmodifiableMap(new HashMap<String, Object>() {",
" {}",
" });",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableMap;",
"import java.util.Collections;",
"import java.util.HashMap;",
"import java.util.Map;",
"class Test {",
" private ImmutableMap<String, Object> test() {",
" return ImmutableMap.of();",
" }",
"}")
.doTest();
}
@Test
public void lambda() {
testHelper
.addInputLines(
"Test.java",
"import java.util.Collections;",
"import java.util.HashMap;",
"import java.util.Map;",
"import java.util.function.Supplier;",
"class Test {",
" private Supplier<Map<String, Object>> test() {",
" return () -> Collections.unmodifiableMap(new HashMap<String, Object>() {",
" {}",
" });",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableMap;",
"import java.util.Collections;",
"import java.util.HashMap;",
"import java.util.Map;",
"import java.util.function.Supplier;",
"class Test {",
" private Supplier<Map<String, Object>> test() {",
" return () -> ImmutableMap.of();",
" }",
"}")
.doTest();
}
@Test
public void statement() {
testHelper
.addInputLines(
"Test.java",
"import java.util.Collections;",
"import java.util.HashMap;",
"import java.util.Map;",
"class Test {",
" private void test() {",
" Collections.unmodifiableMap(new HashMap<String, Object>() {",
" {}",
" });",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableMap;",
"import java.util.Collections;",
"import java.util.HashMap;",
"import java.util.Map;",
"class Test {",
" private void test() {",
" ImmutableMap.of();",
" }",
"}")
.doTest();
}
}
| 11,809
| 35.338462
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SwitchDefaultTest.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 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 SwitchDefault}Test */
@RunWith(JUnit4.class)
public class SwitchDefaultTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(SwitchDefault.class, getClass());
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(SwitchDefault.class, getClass());
@Test
public void refactoring_groupAndCase() {
testHelper
.addInputLines(
"in/Test.java", //
"class Test {",
" void f(int i) {",
" switch (i) {",
" default:",
" case 0:",
" return;",
" case 1:",
" return;",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"class Test {",
" void f(int i) {",
" switch (i) {",
" case 1:",
" return;",
" case 0:",
" default:",
" return;",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactoring_case() {
testHelper
.addInputLines(
"in/Test.java", //
"class Test {",
" void f(int i) {",
" switch (i) {",
" case 2:",
" return;",
" case 1:",
" case 0:",
" default:",
" return;",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"class Test {",
" void f(int i) {",
" switch (i) {",
" case 2:",
" return;",
" case 1:",
" case 0:",
" default:",
" return;",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactoring_group() {
testHelper
.addInputLines(
"in/Test.java", //
"class Test {",
" void f(int i) {",
" switch (i) {",
" case 0:",
" default:",
" return;",
" case 1:",
" return;",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"class Test {",
" void f(int i) {",
" switch (i) {",
" case 1:",
" return;",
" case 0:",
" default:",
" return;",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactoring_fallthrough() {
testHelper
.addInputLines(
"in/Test.java", //
"class Test {",
" boolean f(int i) {",
" switch (i) {",
" default:",
" return false;",
" case 0:",
" case 1:",
" System.err.println();",
" }",
" return true;",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"class Test {",
" boolean f(int i) {",
" switch (i) {",
" case 0:",
" case 1:",
" System.err.println();",
" break;",
" default:",
" return false;",
" }",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void refactoring_fallthroughEmpty() {
testHelper
.addInputLines(
"in/Test.java", //
"class Test {",
" boolean f(int i) {",
" switch (i) {",
" default:",
" return false;",
" case 0:",
" case 1:",
" }",
" return true;",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"class Test {",
" boolean f(int i) {",
" switch (i) {",
" case 0:",
" case 1:",
" break;",
" default:",
" return false;",
" }",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void refactoring_outOfOrder() {
testHelper
.addInputLines(
"in/Test.java", //
"class Test {",
" boolean f(int i) {",
" switch (i) {",
" case 0:",
" return true;",
" default: // fall through",
" case 1: // fall through",
" }",
" return false;",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"class Test {",
" boolean f(int i) {",
" switch (i) {",
" case 0:",
" return true;",
" case 1: // fall through",
" default: // fall through",
" }",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void newNotation_validDefault() {
assumeTrue(RuntimeVersion.isAtLeast14());
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public static void nothing1() { }",
" public static void nothing2() { }",
" public static void nothing3() { }",
" public static void switchDefaultCrash(int i)",
" {",
" switch(i) {",
" case 0 -> nothing1();",
" case 1 -> nothing2();",
" default -> nothing3();",
" }",
" }",
"}")
.doTest();
}
@Test
public void newNotation_changeOrder() {
assumeTrue(RuntimeVersion.isAtLeast14());
testHelper
.addInputLines(
"Test.java",
"class Test {",
" public static void nothing1() { }",
" public static void nothing2() { }",
" public static void nothing3() { }",
" public static void switchDefaultCrash(int i)",
" {",
" switch(i) {",
" default -> nothing3();",
" case 0 -> nothing1();",
" case 1 -> nothing2();",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" public static void nothing1() { }",
" public static void nothing2() { }",
" public static void nothing3() { }",
" public static void switchDefaultCrash(int i)",
" {",
" switch(i) {",
" case 0 -> nothing1();",
" case 1 -> nothing2();",
" default -> nothing3();",
" }",
" }",
"}")
.doTest();
}
}
| 8,396
| 27.464407
| 83
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LenientFormatStringValidationTest.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 LenientFormatStringValidationTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(LenientFormatStringValidation.class, getClass());
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(LenientFormatStringValidation.class, getClass());
@Test
public void tooFewArguments() {
helper
.addSourceLines(
"Test.java",
"import com.google.common.base.Preconditions;",
"class Test {",
" void test() {",
" // BUG: Diagnostic contains:",
" Preconditions.checkState(false, \"%s\");",
" }",
"}")
.doTest();
}
@Test
public void tooManyArguments() {
helper
.addSourceLines(
"Test.java",
"import com.google.common.base.Preconditions;",
"class Test {",
" void test() {",
" // BUG: Diagnostic contains:",
" Preconditions.checkState(false, \"%s\", 1, 1);",
" }",
"}")
.doTest();
}
@Test
public void tooManyArguments_fix() {
refactoring
.addInputLines(
"Test.java",
"import com.google.common.base.Preconditions;",
"class Test {",
" void test() {",
" Preconditions.checkState(false, \"%s\", 1, 1);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Preconditions;",
"class Test {",
" void test() {",
" Preconditions.checkState(false, \"%s (%s)\", 1, 1);",
" }",
"}")
.doTest();
}
@Test
public void tooManyArguments_fixWithNonLiteral() {
refactoring
.addInputLines(
"Test.java",
"import com.google.common.base.Preconditions;",
"class Test {",
" private static final String FOO = \"%s\";",
" void test() {",
" Preconditions.checkState(false, FOO, 1, 1);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Preconditions;",
"class Test {",
" private static final String FOO = \"%s\";",
" void test() {",
" Preconditions.checkState(false, FOO + \" (%s)\", 1, 1);",
" }",
"}")
.doTest();
}
@Test
public void correctArguments() {
helper
.addSourceLines(
"Test.java",
"import com.google.common.base.Preconditions;",
"class Test {",
" void test() {",
" Preconditions.checkState(false, \"%s\", 1);",
" }",
"}")
.doTest();
}
}
| 3,769
| 29.650407
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryFinalTest.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 org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link UnnecessaryFinal}. */
@RunWith(JUnit4.class)
public final class UnnecessaryFinalTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryFinal.class, getClass());
@Test
public final void removesOnParameters() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" void test(final Object o) {}",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
" void test(Object o) {}",
"}")
.doTest();
}
@Test
public final void removesOnLocals() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" void test() {",
" final Object o;",
" }",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
" void test() {",
" Object o;",
" }",
"}")
.doTest();
}
@Test
public final void doesNotRemoveOnFields() {
helper
.addInputLines(
"Test.java", //
"class Test {",
" final Object o = null;",
"}")
.expectUnchanged()
.doTest();
}
}
| 2,122
| 26.217949
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ExtendsAutoValueTest.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.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 ExtendsAutoValue}. */
@RunWith(JUnit4.class)
public class ExtendsAutoValueTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(ExtendsAutoValue.class, getClass())
.setArgs(ImmutableList.of("-processor", AutoValueProcessor.class.getName()));
@Test
public void extendsAutoValue_goodNoSuperclass() {
helper
.addSourceLines(
"TestClass.java", //
"public class TestClass {}")
.doTest();
}
@Test
public void extendsAutoValue_goodSuperclass() {
helper
.addSourceLines(
"TestClass.java", //
"class SuperClass {}",
"public class TestClass extends SuperClass {}")
.doTest();
}
@Test
public void extendsAutoValue_goodAutoValueExtendsSuperclass() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.auto.value.AutoValue;",
"public class TestClass {}",
"@AutoValue class AutoClass extends TestClass {}")
.doTest();
}
@Test
public void extendsAutoValue_goodGeneratedIgnored() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.auto.value.AutoValue;",
"import javax.annotation.processing.Generated;",
"@AutoValue class AutoClass {}",
"@Generated(value=\"hi\") public class TestClass extends AutoClass {}")
.doTest();
}
@Test
public void extendsAutoValue_bad() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue class AutoClass {}",
"// BUG: Diagnostic contains: ExtendsAutoValue",
"public class TestClass extends AutoClass {}")
.doTest();
}
@Test
public void extendsAutoOneOf_bad() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.auto.value.AutoOneOf;",
"@AutoOneOf(AutoClass.Kind.class) class AutoClass {",
" enum Kind {}",
"}",
"// BUG: Diagnostic contains: ExtendsAutoValue",
"public class TestClass extends AutoClass {",
"}")
.doTest();
}
@Test
public void extendsAutoValue_badNoImport() {
helper
.addSourceLines(
"TestClass.java",
"@com.google.auto.value.AutoValue class AutoClass {}",
"// BUG: Diagnostic contains: ExtendsAutoValue",
"public class TestClass extends AutoClass {}")
.doTest();
}
@Test
public void extendsAutoValue_badInnerClass() {
helper
.addSourceLines(
"OuterClass.java",
"import com.google.auto.value.AutoValue;",
"public class OuterClass { ",
" @AutoValue abstract static class AutoClass {}",
" // BUG: Diagnostic contains: ExtendsAutoValue",
" class TestClass extends AutoClass {}",
"}")
.doTest();
}
@Test
public void extendsAutoValue_badInnerStaticClass() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.auto.value.AutoValue;",
"class OuterClass { ",
" @AutoValue static class AutoClass {}",
"}",
"// BUG: Diagnostic contains: ExtendsAutoValue",
"public class TestClass extends OuterClass.AutoClass {}")
.doTest();
}
@Test
public void extendsAutoValue_badButSuppressed() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue class AutoClass {}",
"@SuppressWarnings(\"ExtendsAutoValue\")",
"public class TestClass extends AutoClass {}")
.doTest();
}
@Test
public void extendsAutoValue_innerClassExtends() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.auto.value.AutoValue;",
"@AutoValue class AutoClass {}",
"",
"public class TestClass {",
" // BUG: Diagnostic contains: ExtendsAutoValue",
" public class Extends extends AutoClass {}",
"}")
.doTest();
}
@Test
public void extendsAutoValue_innerClassExtends_generated() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.auto.value.AutoValue;",
"import javax.annotation.processing.Generated;",
"@AutoValue class AutoClass {}",
"",
"@Generated(\"generator\")",
"public class TestClass {",
" public class Extends extends AutoClass {}",
"}")
.doTest();
}
}
| 5,702
| 29.827027
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnitAmbiguousTestClassTest.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 JUnitAmbiguousTestClassTest}Test */
@RunWith(JUnit4.class)
public class JUnitAmbiguousTestClassTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JUnitAmbiguousTestClass.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Positive.java",
"import org.junit.Test;",
"import junit.framework.TestCase;",
"// BUG: Diagnostic contains:",
"public class Positive extends TestCase {",
" @Test",
" public void testCase() {}",
"}")
.doTest();
}
@Test
public void negativeNoExtends() {
compilationHelper
.addSourceLines(
"Positive.java",
"import org.junit.Test;",
"public class Positive {",
" @Test",
" public void testCase() {}",
"}")
.doTest();
}
@Test
public void negativeNoAnnotations() {
compilationHelper
.addSourceLines(
"Positive.java",
"import junit.framework.TestCase;",
"public class Positive extends TestCase {",
" public void testCase() {}",
"}")
.doTest();
}
}
| 2,073
| 28.211268
| 83
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/VariableNameSameAsTypeTest.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 kayco@google.com (Kayla Walker) & seibelsabrina@google.com (Sabrina Seibel)
*/
@RunWith(JUnit4.class)
public class VariableNameSameAsTypeTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(VariableNameSameAsType.class, getClass());
@Test
public void positiveInsideMethod() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: VariableNameSameAsType",
" String String; ",
" }",
"}")
.doTest();
}
@Test
public void positiveLambda() {
helper
.addSourceLines(
"Test.java",
"import java.util.function.Predicate;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: Variable named String has the type String",
" Predicate<String> p = (String) -> String.isEmpty(); ",
" }",
"}")
.doTest();
}
@Test
public void positiveInitialized() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: VariableNameSameAsType",
" String String = \"Kayla\"; ",
" }",
"}")
.doTest();
}
@Test
public void positiveInitializedSeparate() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: VariableNameSameAsType",
" String String; ",
" String = \"Kayla\"; ",
" }",
"}")
.doTest();
}
@Test
public void positiveField() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: VariableNameSameAsType",
" String String;",
" void f() {",
" }",
"}")
.doTest();
}
@Test
public void negativeLowerCase() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" void f() {",
" String string;",
" }",
"}")
.doTest();
}
@Test
public void negativeInitializedLowerCase() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" void f() {",
" String string = \"Kayla\"; ",
" }",
"}")
.doTest();
}
@Test
public void negativeInitializedSeparate() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" String string; ",
" string = \"Kayla\"; ",
" }",
"}")
.doTest();
}
@Test
public void negativeOther() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" void f() {",
" String t; ",
" }",
"}")
.doTest();
}
}
| 3,982
| 24.208861
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DateFormatConstantTest.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 DateFormatConstant}Test */
@RunWith(JUnit4.class)
public class DateFormatConstantTest {
@Test
public void positive() {
CompilationTestHelper.newInstance(DateFormatConstant.class, getClass())
.addSourceLines(
"Test.java",
"import java.text.DateFormat;",
"import java.text.SimpleDateFormat;",
"class Test {",
" // BUG: Diagnostic contains:",
" private static final DateFormat DATE_FORMAT1 =",
" new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
" // BUG: Diagnostic contains:",
" private static final SimpleDateFormat DATE_FORMAT2 =",
" new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
"}")
.doTest();
}
@Test
public void negative() {
CompilationTestHelper.newInstance(DateFormatConstant.class, getClass())
.addSourceLines(
"Test.java",
"import java.text.SimpleDateFormat;",
"class Test {",
" private static final SimpleDateFormat NO_INITIALIZER;",
" static {",
" NO_INITIALIZER = new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
" }",
" private final SimpleDateFormat NON_STATIC =",
" new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
" private static SimpleDateFormat NON_FINAL =",
" new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
" private static final SimpleDateFormat lowerCamelCase =",
" new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
" static void f() {",
" final SimpleDateFormat NOT_A_FIELD =",
" new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
" }",
" private static final String NOT_A_SIMPLE_DATE_FORMAT = \"\";",
"}")
.doTest();
}
@Test
public void threadLocalFix() {
BugCheckerRefactoringTestHelper.newInstance(DateFormatConstant.class, getClass())
.addInputLines(
"in/Test.java",
"import java.text.SimpleDateFormat;",
"import java.text.DateFormat;",
"import java.util.Date;",
"class Test {",
" private static final DateFormat DATE_FORMAT =",
" new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
" static String f(Date d) {",
" return DATE_FORMAT.format(d);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.text.SimpleDateFormat;",
"import java.text.DateFormat;",
"import java.util.Date;",
"class Test {",
" private static final ThreadLocal<DateFormat> dateFormat = ",
" ThreadLocal.withInitial(() -> new SimpleDateFormat(\"yyyy-MM-dd HH:mm\"));",
" static String f(Date d) {",
" return dateFormat.get().format(d);",
" }",
"}")
.doTest();
}
@Test
public void lowerCamelCaseFix() {
BugCheckerRefactoringTestHelper.newInstance(DateFormatConstant.class, getClass())
.addInputLines(
"in/Test.java",
"import java.text.SimpleDateFormat;",
"import java.text.DateFormat;",
"import java.util.Date;",
"class Test {",
" private static final DateFormat DATE_FORMAT =",
" new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
" static String f(Date d) {",
" return DATE_FORMAT.format(d);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.text.SimpleDateFormat;",
"import java.text.DateFormat;",
"import java.util.Date;",
"class Test {",
" private static final DateFormat dateFormat =",
" new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");",
" static String f(Date d) {",
" return dateFormat.format(d);",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
}
| 5,082
| 36.932836
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LiteEnumValueOfTest.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;
/**
* Tests for {@link LiteEnumValueOf}.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@RunWith(JUnit4.class)
public final class LiteEnumValueOfTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(LiteEnumValueOf.class, getClass())
.addSourceFile("android/testdata/stubs/android/os/Parcel.java")
.addSourceFile("android/testdata/stubs/android/os/Parcelable.java")
.addSourceLines(
"FakeLiteEnum.java",
"enum FakeLiteEnum implements com.google.protobuf.Internal.EnumLite {",
" FOO;",
" @Override public int getNumber() {",
" return 0;",
" }",
"}");
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void test() {",
" // BUG: Diagnostic contains:",
" FakeLiteEnum.valueOf(\"FOO\");",
" // BUG: Diagnostic contains:",
" FakeLiteEnum.FOO.valueOf(\"FOO\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"Usage.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestEnum;",
"class Usage {",
" private TestEnum testMethod() {",
" return TestEnum.valueOf(\"FOO\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseJDK9OrAbove() {
compilationHelper
.addSourceLines(
"ProtoLiteEnum.java",
"enum ProtoLiteEnum {",
" FOO(1),",
" BAR(2);",
" private final int number;",
" private ProtoLiteEnum(int number) {",
" this.number = number;",
" }",
" public int getNumber() {",
" return number;",
" }",
"}")
.addSourceLines("TestData.java", "class TestData {}")
.addSourceLines(
"$AutoValue_TestData.java",
"import javax.annotation.processing.Generated;",
"@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")",
"class $AutoValue_TestData extends TestData {}")
.addSourceLines(
"AutoValue_TestData.java",
"import android.os.Parcel;",
"import android.os.Parcelable;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestEnum;",
"import javax.annotation.processing.Generated;",
"@Generated(\"com.ryanharter.auto.value.parcel.AutoValueParcelExtension\")",
"class AutoValue_TestData extends $AutoValue_TestData {",
" AutoValue_TestData(ProtoLiteEnum protoLiteEnum) {}",
" public static final Parcelable.Creator<AutoValue_TestData> CREATOR =",
" new Parcelable.Creator<AutoValue_TestData>() {",
" @Override",
" public AutoValue_TestData createFromParcel(Parcel in) {",
" return new AutoValue_TestData(ProtoLiteEnum.valueOf(\"FOO\"));",
" }",
" @Override",
" public AutoValue_TestData[] newArray(int size) {",
" return null;",
" }",
" };",
"}")
.doTest();
}
}
| 4,329
| 34.785124
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ObjectToStringTest.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 com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.source.tree.ClassTree;
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 ObjectToStringTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ObjectToString.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("ObjectToStringPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("ObjectToStringNegativeCases.java").doTest();
}
/** A class that will be missing at compile-time for {@link #testIncompleteClasspath}. */
public static class One {}
/** A test class for {@link #testIncompleteClasspath}. */
public abstract static class TestLib {
/** Another test class for {@link #testIncompleteClasspath}. */
public static final class Two extends One {
@Override
public String toString() {
return "";
}
}
public abstract Two f();
}
// A bugchecker that eagerly completes the missing symbol for testIncompleteClasspath below,
// to avoid the CompletionFailure being reported later.
/** A checker for {@link #testIncompleteClasspath}. */
@BugPattern(summary = "", severity = ERROR)
public static class CompletionChecker extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
state.getSymbolFromString(One.class.getName());
return Description.NO_MATCH;
}
}
// don't complain if we can't load the type hierarchy of a class that is toString()'d
@Test
public void incompleteClasspath() {
CompilationTestHelper.newInstance(
ScannerSupplier.fromBugCheckerClasses(ObjectToString.class, CompletionChecker.class),
getClass())
.addSourceLines(
"Test.java",
"import " + TestLib.class.getCanonicalName() + ";",
"class Test {",
" String f(TestLib lib) {",
" return \"\" + lib.f();",
" }",
"}")
.withClasspath(ObjectToStringTest.class, TestLib.class, TestLib.Two.class)
.doTest();
}
@Test
public void qualifiedName() {
compilationHelper
.addSourceLines(
"A.java", //
"class A {",
" static final class B {}",
"}")
.addSourceLines(
"C.java",
"class C {",
" String test() {",
" // BUG: Diagnostic contains: A.B",
" return new A.B().toString();",
" }",
"}")
.doTest();
}
}
| 3,773
| 31.25641
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ImplementAssertionWithChainingTest.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 ImplementAssertionWithChainingTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ImplementAssertionWithChaining.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("ImplementAssertionWithChainingPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("ImplementAssertionWithChainingNegativeCases.java").doTest();
}
}
| 1,356
| 31.309524
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BadAnnotationImplementationTest.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 {@link BadAnnotationImplementation}. */
@RunWith(JUnit4.class)
public class BadAnnotationImplementationTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(BadAnnotationImplementation.class, getClass());
@Test
public void declaredClassImplementsAnnotation() {
compilationHelper
.addSourceLines(
"TestAnnotation.java",
"import java.lang.annotation.Annotation;",
"// BUG: Diagnostic contains:",
"public class TestAnnotation implements Annotation {",
" @Override public Class<? extends Annotation> annotationType() {",
" return TestAnnotation.class;",
" }",
"}")
.doTest();
}
@Test
public void anonymousClassImplementsAnnotation() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.lang.annotation.Annotation;",
"public class Test {",
" public Annotation getAnnotation() {",
" // BUG: Diagnostic contains:",
" return new Annotation() {",
" @Override public Class<? extends Annotation> annotationType() {",
" return Annotation.class;",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void anonymousClassImplementsUserDefinedAnnotation() {
compilationHelper
.addSourceLines("MyAnnotation.java", "public @interface MyAnnotation {}")
.addSourceLines(
"AnonymousClass.java",
"import java.lang.annotation.Annotation;",
"public class AnonymousClass {",
" public Annotation getAnnotation() {",
" // BUG: Diagnostic contains:",
" return new MyAnnotation() {",
" @Override public Class<? extends Annotation> annotationType() {",
" return Annotation.class;",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void overridesEqualsButNotHashCode() {
compilationHelper
.addSourceLines(
"TestAnnotation.java",
"import java.lang.annotation.Annotation;",
"// BUG: Diagnostic contains:",
"public class TestAnnotation implements Annotation {",
" @Override public Class<? extends Annotation> annotationType() {",
" return TestAnnotation.class;",
" }",
" @Override public boolean equals(Object other) {",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void overridesHashCodeButNotEquals() {
compilationHelper
.addSourceLines(
"TestAnnotation.java",
"import java.lang.annotation.Annotation;",
"// BUG: Diagnostic contains:",
"public class TestAnnotation implements Annotation {",
" @Override public Class<? extends Annotation> annotationType() {",
" return TestAnnotation.class;",
" }",
" @Override public int hashCode() {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void wrongEquals() {
compilationHelper
.addSourceLines(
"TestAnnotation.java",
"import java.lang.annotation.Annotation;",
"// BUG: Diagnostic contains:",
"public class TestAnnotation implements Annotation {",
" @Override public Class<? extends Annotation> annotationType() {",
" return TestAnnotation.class;",
" }",
" public boolean equals(TestAnnotation other) {",
" return false;",
" }",
" @Override public int hashCode() {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void wrongHashCode() {
compilationHelper
.addSourceLines(
"TestAnnotation.java",
"import java.lang.annotation.Annotation;",
"// BUG: Diagnostic contains:",
"public class TestAnnotation implements Annotation {",
" @Override public Class<? extends Annotation> annotationType() {",
" return TestAnnotation.class;",
" }",
" @Override public boolean equals(Object other) {",
" return false;",
" }",
" public int hashCode(Object obj) {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void overridesEqualsAndHashCode() {
compilationHelper
.addSourceLines(
"TestAnnotation.java",
"import java.lang.annotation.Annotation;",
"public class TestAnnotation implements Annotation {",
" @Override public Class<? extends Annotation> annotationType() {",
" return TestAnnotation.class;",
" }",
" @Override public boolean equals(Object other) {",
" return false;",
" }",
" @Override public int hashCode() {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void declareInterfaceThatExtendsAnnotation() {
compilationHelper
.addSourceLines(
"TestAnnotation.java",
"import java.lang.annotation.Annotation;",
"public interface TestAnnotation extends Annotation {}")
.doTest();
}
@Test
public void declareEnumThatImplementsAnnotation() {
compilationHelper
.addSourceLines(
"TestEnum.java",
"import java.lang.annotation.Annotation;",
"// BUG: Diagnostic contains: Enums cannot correctly implement Annotation",
"public enum TestEnum implements Annotation {",
" VALUE_1,",
" VALUE_2;",
" @Override public Class<? extends Annotation> annotationType() {",
" return TestEnum.class;",
" }",
"}")
.doTest();
}
@Test
public void extendsClassThatImplementsEqualsAndHashCode() {
compilationHelper
.addSourceLines(
"BaseAnnotation.java",
"import java.lang.annotation.Annotation;",
"public class BaseAnnotation implements Annotation {",
" @Override public Class<? extends Annotation> annotationType() {",
" return Annotation.class;",
" }",
" @Override public boolean equals(Object other) {",
" return false;",
" }",
" @Override public int hashCode() {",
" return 0;",
" }",
"}")
.addSourceLines(
"MyAnnotation.java",
"import java.lang.annotation.Annotation;",
"public class MyAnnotation extends BaseAnnotation {}")
.doTest();
}
}
| 7,865
| 32.615385
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InfiniteRecursionTest.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 InfiniteRecursion}Test */
@RunWith(JUnit4.class)
public class InfiniteRecursionTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(InfiniteRecursion.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f(int x) {}",
" void f() {",
" // BUG: Diagnostic contains:",
" f();",
" }",
" int g() {",
" return 0;",
" }",
" int g(int x) {",
" // BUG: Diagnostic contains:",
" return g(x);",
" }",
"}")
.doTest();
}
@Test
public void positiveExplicitThis() {
compilationHelper
.addSourceLines(
"p/Test.java",
"package p;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains:",
" this.f();",
" }",
" void g() {",
" // BUG: Diagnostic contains:",
" (this).g();",
" }",
" void h() {",
" // BUG: Diagnostic contains:",
" Test.this.h();",
" }",
" void i() {",
" // BUG: Diagnostic contains:",
" (p.Test.this).i();",
" }",
"}")
.doTest();
}
@Test
public void positiveMultipleStatementsFirst() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" Test f() {",
" // BUG: Diagnostic contains:",
" f();",
" return this;",
" }",
"}")
.doTest();
}
@Test
public void positiveStatic() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" static void f(int x) {}",
" static void f() {",
" // BUG: Diagnostic contains:",
" Test.f();",
" }",
" static void instanceF() {",
" // BUG: Diagnostic contains:",
" new Test().instanceF();",
" }",
" static void subclassF() {",
" // BUG: Diagnostic contains:",
" Subclass.subclassF();",
" }",
" static int g() {",
" return 0;",
" }",
" static int g(int x) {",
" // BUG: Diagnostic contains:",
" return Test.g(x);",
" }",
"",
" class Subclass extends Test {}",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f(int x) {}",
" void f() {",
" f(42);",
" }",
" int g() {",
" return 0;",
" }",
" int g(int x) {",
" return x == 0 ? g() : g(x - 1);",
" }",
"}")
.doTest();
}
@Test
public void positiveMultipleStatementsNotFirst() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" Test f() {",
" new Test();",
" // BUG: Diagnostic contains:",
" f();",
" return this;",
" }",
"}")
.doTest();
}
@Test
public void negativeDelegate() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" Test test;",
" void f() {",
" test.f();",
" }",
"}")
.doTest();
}
@Test
public void positiveDelegateCannotBeOverridden() {
compilationHelper
.addSourceLines(
"Test.java",
"final class Test {",
" Test test;",
" void f() {",
" // BUG: Diagnostic contains:",
" test.f();",
" }",
"}")
.doTest();
}
@Test
public void negativeAfterReturn() {
compilationHelper
.addSourceLines(
"Test.java",
"final class Test {",
" void f(boolean callAgain) {",
" if (!callAgain) {",
" return;",
" }",
" f(false);",
" }",
"}")
.doTest();
}
@Test
public void positiveBeforeReturn() {
compilationHelper
.addSourceLines(
"Test.java",
"final class Test {",
" void f(boolean callAgain) {",
" // BUG: Diagnostic contains:",
" f(false);",
" if (!callAgain) {",
" return;",
" }",
" }",
"}")
.doTest();
}
@Test
public void negativeConditional() {
compilationHelper
.addSourceLines(
"Test.java",
"final class Test {",
" void f(boolean callAgain) {",
" if (callAgain) {",
" f(false);",
" }",
" }",
"}")
.doTest();
}
@Test
public void negativeNestedClass() {
compilationHelper
.addSourceLines(
"Test.java",
"final class Test {",
" void f() {",
" new Object() {",
" void g() {",
" f();",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void positiveAfterNestedClass() {
compilationHelper
.addSourceLines(
"Test.java",
"final class Test {",
" void f() {",
" new Object() {",
" void g() {",
" f();",
" return;",
" }",
" };",
" // BUG: Diagnostic contains:",
" f();",
" }",
"}")
.doTest();
}
@Test
public void negativeLambda() {
compilationHelper
.addSourceLines(
"Test.java",
"final class Test {",
" Runnable f() {",
" return () -> f();",
" }",
"}")
.doTest();
}
@Test
public void positiveGeneric() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test<X> {",
" <T> void f(T x) {",
" // BUG: Diagnostic contains:",
" this.<String>f(\"\");",
" }",
" void g(X x) {",
" // BUG: Diagnostic contains:",
" g(null);",
" }",
"}")
.doTest();
}
@Test
public void positiveCast() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test<X> {",
" String overrideOfSomeMethodThatReturnsObject() {",
" // BUG: Diagnostic contains:",
" return (String) overrideOfSomeMethodThatReturnsObject();",
" }",
"}")
.doTest();
}
@Test
public void positiveCastWithParens() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test<X> {",
" String overrideOfSomeMethodThatReturnsObject() {",
" // BUG: Diagnostic contains:",
" return (String) (overrideOfSomeMethodThatReturnsObject());",
" }",
"}")
.doTest();
}
@Test
public void overload() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public void f(String s) {",
" f((Object) s);",
" }",
" public void f(Object o) {",
" // BUG: Diagnostic contains:",
" f(o);",
" }",
"}")
.doTest();
}
@Test
public void abstractMethod() {
compilationHelper
.addSourceLines(
"Test.java", //
"abstract class Test {",
" abstract void f();",
"}")
.doTest();
}
@Test
public void positiveBinaryLeftHandSide() {
compilationHelper
.addSourceLines(
"Test.java",
"final class Test {",
" Test next;",
" boolean nextIsCool;",
" boolean isCool(boolean thisIsCool) {",
" // BUG: Diagnostic contains:",
" return next.isCool(nextIsCool) || thisIsCool;",
" }",
"}")
.doTest();
}
@Test
public void negativeBinaryRightHandSide() {
compilationHelper
.addSourceLines(
"Test.java",
"final class Test {",
" Test next;",
" boolean nextIsCool;",
" boolean isCool(boolean thisIsCool) {",
" return thisIsCool || next.isCool(thisIsCool);",
" }",
"}")
.doTest();
}
@Test
public void positiveBinaryRightHandSideNotConditional() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" String asString() {",
" // BUG: Diagnostic contains:",
" return '{' + asString() + '}';",
" }",
"}")
.doTest();
}
}
| 10,471
| 24.603912
| 77
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JavaUtilDateCheckerTest.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;
/** {@link JavaUtilDateChecker}Test */
@RunWith(JUnit4.class)
public class JavaUtilDateCheckerTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(JavaUtilDateChecker.class, getClass());
@Test
public void javaUtilDate_constructors() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Date;",
"class Test {",
" // BUG: Diagnostic contains: Date has a bad API",
" private static final Date date1 = new Date();",
" // BUG: Diagnostic contains: Date has a bad API",
" private static final Date date2 = new Date(123456789L);",
"}")
.doTest();
}
@Test
public void javaUtilDate_staticMethods() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Date;",
"class Test {",
" // BUG: Diagnostic contains: Date has a bad API",
" private static final long date = Date.parse(\"Sat, 12 Aug 1995 13:30:00 GMT\");",
"}")
.doTest();
}
@Test
public void javaUtilDate_instanceMethods() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.Date;",
"class Test {",
" public void doSomething(Date date) {",
" // BUG: Diagnostic contains: Date has a bad API",
" long time = date.getTime();",
" }",
"}")
.doTest();
}
@Test
public void javaUtilDate_allowedApis() {
testHelper
.addSourceLines(
"Test.java",
"import java.time.Instant;",
"import java.util.Date;",
"class Test {",
" public void doSomething(Date date) {",
" Instant instant = date.toInstant();",
" Date date2 = Date.from(instant);",
" }",
"}")
.doTest();
}
}
| 2,765
| 29.733333
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ModifySourceCollectionInStreamTest.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;
/**
* Tests for {@link ModifySourceCollectionInStream} bugpattern.
*
* @author deltazulu@google.com (Donald Duo Zhao)
*/
@RunWith(JUnit4.class)
public class ModifySourceCollectionInStreamTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ModifySourceCollectionInStream.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("ModifySourceCollectionInStreamPositiveCases.java").doTest();
}
@Test
public void negativeCasse() {
compilationHelper.addSourceFile("ModifySourceCollectionInStreamNegativeCases.java").doTest();
}
}
| 1,421
| 32.069767
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MissingCasesInEnumSwitchTest.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 static org.junit.Assume.assumeTrue;
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 MissingCasesInEnumSwitch}Test */
@RunWith(JUnit4.class)
public class MissingCasesInEnumSwitchTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(MissingCasesInEnumSwitch.class, getClass());
@Test
public void exhaustive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" enum Case { ONE, TWO, THREE }",
" void m(Case c) {",
" switch (c) {",
" case ONE:",
" case TWO:",
" case THREE:",
" System.err.println(\"found it!\");",
" break;",
" }",
" }",
"}")
.doTest();
}
@Test
public void exhaustive_multipleCaseExpressions() {
assumeTrue(RuntimeVersion.isAtLeast14());
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" enum Case { ONE, TWO }",
" void m(Case c) {",
" switch (c) {",
" case ONE, TWO -> {}",
" }",
" }",
"}")
.doTest();
}
@Test
public void nonExhaustive_withDefault() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" enum Case { ONE, TWO, THREE }",
" void m(Case c) {",
" switch (c) {",
" case ONE:",
" case TWO:",
" System.err.println(\"found it!\");",
" break;",
" default:",
" break;",
" }",
" }",
"}")
.doTest();
}
@Test
public void nonExhaustive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" enum Case { ONE, TWO, THREE }",
" void m(Case c) {",
" // BUG: Diagnostic contains: THREE",
" switch (c) {",
" case ONE:",
" case TWO:",
" System.err.println(\"found it!\");",
" break;",
" }",
" }",
"}")
.doTest();
}
@Test
public void nonExhaustive_manyCases() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" enum Case { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT }",
" void m(Case c) {",
" // BUG: Diagnostic contains: TWO, THREE, FOUR, and 4 others",
" switch (c) {",
" case ONE:",
" System.err.println(\"found it!\");",
" break;",
" }",
" }",
"}")
.doTest();
}
@Test
public void nonExhaustive_nonEnum() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m(int i) {",
" switch (i) {",
" case 1:",
" case 2:",
" System.err.println(\"found it!\");",
" break;",
" }",
" }",
"}")
.doTest();
}
@Test
public void empty() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" enum Case { ONE, TWO }",
" void m(Case e) {",
" // BUG: Diagnostic contains: ONE, TWO",
" switch (e) {",
" }",
" }",
"}")
.doTest();
}
}
| 4,577
| 26.914634
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CompileTimeConstantCheckerTest.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 com.google.errorprone.annotations.CompileTimeConstant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link CompileTimeConstantChecker}Test */
@RunWith(JUnit4.class)
public class CompileTimeConstantCheckerTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(CompileTimeConstantChecker.class, getClass());
@Test
public void matches_fieldAccessFailsWithNonConstant() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public void m(String p, @CompileTimeConstant String q) { }",
" // BUG: Diagnostic contains: Non-compile-time constant expression passed",
" public void r(String s) { this.m(\"boo\", s); }",
"}")
.doTest();
}
@Test
public void matches_fieldAccessFailsWithNonConstantExpression() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public void m(String p, @CompileTimeConstant String q) { }",
" // BUG: Diagnostic contains: Non-compile-time constant expression passed",
" public void r(String s) { this.m(\"boo\", s +\"boo\"); }",
"}")
.doTest();
}
@Test
public void matches_fieldAccessSucceedsWithLiteral() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public void m(String s, @CompileTimeConstant String p) { }",
" public void r(String x) { this.m(x, \"boo\"); }",
"}")
.doTest();
}
@Test
public void matches_fieldAccessSucceedsWithStaticFinal() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public static final String S = \"Hello\";",
" public void m(String s, @CompileTimeConstant String p) { }",
" public void r(String x) { this.m(x, S); }",
"}")
.doTest();
}
@Test
public void matches_fieldAccessSucceedsWithConstantConcatenation() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public static final String S = \"Hello\";",
" public void m(String s, @CompileTimeConstant String p) { }",
" public void r(String x) { this.m(x, S + \" World!\"); }",
"}")
.doTest();
}
@Test
public void matches_identCallFailsWithNonConstant() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public void m(@CompileTimeConstant String p, int i) { }",
" // BUG: Diagnostic contains: Non-compile-time constant expression passed",
" public void r(String s) { m(s, 19); }",
"}")
.doTest();
}
@Test
public void matches_identCallSucceedsWithLiteral() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public void m(String s, @CompileTimeConstant String p) { }",
" public void r(@CompileTimeConstant final String x) { m(x, x); }",
" public void s() { r(\"boo\"); }",
"}")
.doTest();
}
@Test
public void matches_staticCallFailsWithNonConstant() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public static void m(@CompileTimeConstant String p, int i) { }",
" // BUG: Diagnostic contains: Non-compile-time constant expression passed",
" public static void r(String s) { m(s, 19); }",
"}")
.doTest();
}
@Test
public void matches_staticCallSucceedsWithLiteral() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public static void m(String s, @CompileTimeConstant String p) { }",
" public static void r(String x) { m(x, \"boo\"); }",
"}")
.doTest();
}
@Test
public void matches_qualifiedStaticCallFailsWithNonConstant() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public static class Inner {",
" public static void m(@CompileTimeConstant String p, int i) { }",
" }",
" // BUG: Diagnostic contains: Non-compile-time constant expression passed",
" public static void r(String s) { Inner.m(s, 19); }",
"}")
.doTest();
}
@Test
public void matches_qualifiedStaticCallSucceedsWithLiteral() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public static class Inner {",
" public static void m(String s, @CompileTimeConstant String p) { }",
" }",
" public static void r(String x) { Inner.m(x, \"boo\"); }",
"}")
.doTest();
}
@Test
public void matches_ctorSucceedsWithLiteral() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public CompileTimeConstantTestCase(",
" String s, @CompileTimeConstant String p) { }",
" public static CompileTimeConstantTestCase makeNew(String x) {",
" return new CompileTimeConstantTestCase(x, \"boo\");",
" }",
"}")
.doTest();
}
@Test
public void matches_ctorFailsWithNonConstant() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public CompileTimeConstantTestCase(",
" String s, @CompileTimeConstant String p) { }",
" public static CompileTimeConstantTestCase makeNew(String x) {",
" // BUG: Diagnostic contains: Non-compile-time constant expression passed",
" return new CompileTimeConstantTestCase(\"boo\", x);",
" }",
"}")
.doTest();
}
@Test
public void matches_identCallSucceedsWithinCtorWithLiteral() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public CompileTimeConstantTestCase(",
" String s, @CompileTimeConstant final String p) { m(p); }",
" public void m(@CompileTimeConstant String r) {}",
" public static CompileTimeConstantTestCase makeNew(String x) {",
" return new CompileTimeConstantTestCase(x, \"boo\");",
" }",
"}")
.doTest();
}
/** Holder for a method we wish to reference from a test. */
public static class Holder {
public static void m(String s, @CompileTimeConstant String... p) {}
private Holder() {}
}
@Test
public void matches_varargsInDifferentCompilationUnit() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import " + Holder.class.getCanonicalName() + ";",
"public class CompileTimeConstantTestCase {",
" public static void r(String s) {",
" // BUG: Diagnostic contains: Non-compile-time constant expression passed",
" Holder.m(s, \"foo\", s);",
" }",
"}")
.doTest();
}
@Test
public void matches_varargsSuccess() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public static void m(String s, @CompileTimeConstant String... p) { }",
" public static void r(String s) { ",
" m(s); ",
" m(s, \"foo\"); ",
" m(s, \"foo\", \"bar\"); ",
" m(s, \"foo\", \"bar\", \"baz\"); ",
" }",
"}")
.doTest();
}
@Test
public void matches_effectivelyFinalCompileTimeConstantParam() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public static void m(@CompileTimeConstant String y) { }",
" public static void r(@CompileTimeConstant String x) { ",
" m(x); ",
" }",
"}")
.doTest();
}
@Test
public void matches_nonFinalCompileTimeConstantParam() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" public static void m(@CompileTimeConstant String y) { }",
" public static void r(@CompileTimeConstant String x) { ",
" x = x + \"!\";",
" // BUG: Diagnostic contains: . Did you mean to make 'x' final?",
" m(x); ",
" }",
"}")
.doTest();
}
@Test
public void matches_override() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"abstract class CompileTimeConstantTestCase {",
" abstract void m(String y);",
" static class C extends CompileTimeConstantTestCase {",
" // BUG: Diagnostic contains: Method with @CompileTimeConstant parameter",
" @Override void m(@CompileTimeConstant String s) {}",
" }",
"}")
.doTest();
}
@Test
public void matches_methodReference() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.function.Consumer;",
"public class CompileTimeConstantTestCase {",
" public static void m(@CompileTimeConstant String s) { }",
" public static Consumer<String> r(String x) {",
" // BUG: Diagnostic contains: Method with @CompileTimeConstant parameter",
" return CompileTimeConstantTestCase::m;",
" }",
"}")
.doTest();
}
@Test
public void matches_constructorReference() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.function.Function;",
"public class CompileTimeConstantTestCase {",
" CompileTimeConstantTestCase(@CompileTimeConstant String s) { }",
" public static Function<String, CompileTimeConstantTestCase> r(String x) {",
" // BUG: Diagnostic contains: Method with @CompileTimeConstant parameter",
" return CompileTimeConstantTestCase::new;",
" }",
"}")
.doTest();
}
@Test
public void matches_methodReferenceCorrectOverrideMethod() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.function.Consumer;",
"public class CompileTimeConstantTestCase {",
" interface ConstantFn {",
" void apply(@CompileTimeConstant String s);",
" }",
" public static void m(@CompileTimeConstant String s) { }",
" public static ConstantFn r(String x) {",
" return CompileTimeConstantTestCase::m;",
" }",
"}")
.doTest();
}
@Test
public void matches_methodReferenceCorrectOverrideConstructor() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.function.Consumer;",
"public class CompileTimeConstantTestCase {",
" interface ConstantFn {",
" CompileTimeConstantTestCase apply(@CompileTimeConstant String s);",
" }",
" CompileTimeConstantTestCase(@CompileTimeConstant String s) {}",
" public static ConstantFn r(String x) {",
" return CompileTimeConstantTestCase::new;",
" }",
"}")
.doTest();
}
@Test
public void matches_lambdaExpression() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.function.Consumer;",
"public class CompileTimeConstantTestCase {",
" // BUG: Diagnostic contains: Method with @CompileTimeConstant parameter",
" Consumer<String> c = (@CompileTimeConstant String s) -> {};",
"}")
.doTest();
}
@Test
public void doesNotMatch_lambdaExpression_correctOverride() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.function.Consumer;",
"public class CompileTimeConstantTestCase {",
" interface ConstantFn {",
" void apply(@CompileTimeConstant String s);",
" }",
" ConstantFn c = (@CompileTimeConstant String s) -> {doFoo(s);};",
" void doFoo(final @CompileTimeConstant String foo) {}",
"}")
.doTest();
}
@Test
public void matches_lambdaExpressionWithoutAnnotatedParameters() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"import java.util.function.Consumer;",
"public class CompileTimeConstantTestCase {",
" interface ConstantFn {",
" void apply(@CompileTimeConstant String s);",
" }",
" // BUG: Diagnostic contains: Non-compile-time constant expression",
" ConstantFn c = s -> {doFoo(s);};",
" void doFoo(final @CompileTimeConstant String foo) {}",
"}")
.doTest();
}
@Test
public void matches_lambdaExpressionWithoutExplicitFormalParameters() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" @FunctionalInterface",
" interface I {",
" void f(@CompileTimeConstant String x);",
" }",
" void f(String s) {",
" I i = x -> {};",
" // BUG: Diagnostic contains: Non-compile-time constant expression passed",
" i.f(s);",
" }",
"}")
.doTest();
}
@Test
public void reportsDiagnostic_whenConstantFieldDeclaredWithoutFinal() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" // BUG: Diagnostic contains: . Did you mean to make 's' final?",
" @CompileTimeConstant String s = \"s\";",
"}")
.doTest();
}
@Test
public void noDiagnostic_whenConstantFieldDeclaredFinal() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" @CompileTimeConstant final String s = \"s\";",
"}")
.doTest();
}
@Test
public void reportsDiagnostic_whenInitialisingFinalFieldWithNonConstant() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" @CompileTimeConstant final String s;",
" CompileTimeConstantTestCase(String s) {",
" // BUG: Diagnostic contains: Non-compile-time constant expression",
" this.s = s;",
" }",
"}")
.doTest();
}
@Test
public void noDiagnostic_whenInitialisingFinalFieldWithConstant() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" @CompileTimeConstant final String s;",
" CompileTimeConstantTestCase(@CompileTimeConstant String s) {",
" this.s = s;",
" }",
"}")
.doTest();
}
@Test
public void noDiagnostic_whenInvokingMethodWithFinalField() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class CompileTimeConstantTestCase {",
" @CompileTimeConstant final String s;",
" CompileTimeConstantTestCase(@CompileTimeConstant String s) {",
" this.s = s;",
" }",
" void invokeCTCMethod() {",
" ctcMethod(s);",
" }",
" void ctcMethod(@CompileTimeConstant String s) {}",
"}")
.doTest();
}
@Test
public void reportsDiagnostic_whenConstantEnumFieldDeclaredWithoutFinal() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public enum Test {",
" A(\"A\");",
" // BUG: Diagnostic contains: . Did you mean to make 's' final?",
" @CompileTimeConstant String s;",
" Test(@CompileTimeConstant String s) {",
" this.s = s;",
" }",
"}")
.doTest();
}
@Test
public void noDiagnostic_whenConstantEnumFieldDeclaredFinal() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public enum Test {",
" A(\"A\");",
" @CompileTimeConstant final String s;",
" Test(@CompileTimeConstant String s) {",
" this.s = s;",
" }",
"}")
.doTest();
}
@Test
public void reportsDiagnostic_whenInitialisingFinalEnumFieldWithNonConstant() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public enum Test {",
" A(\"A\");",
" @CompileTimeConstant final String s;",
" Test(String s) {",
" // BUG: Diagnostic contains: Non-compile-time constant expression",
" this.s = s;",
" }",
"}")
.doTest();
}
@Test
public void noDiagnostic_whenInvokingMethodWithFinalEnumField() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public enum Test {",
" A(\"A\");",
" @CompileTimeConstant final String s;",
" Test(@CompileTimeConstant String s) {",
" this.s = s;",
" }",
" void invokeCTCMethod() {",
" ctcMethod(s);",
" }",
" void ctcMethod(@CompileTimeConstant String s) {}",
"}")
.doTest();
}
@Test
public void nonConstantField_positive() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public abstract class CompileTimeConstantTestCase {",
" abstract String something();",
" // BUG: Diagnostic contains: Non-compile-time constant expression",
" @CompileTimeConstant final String x = something();",
"}")
.doTest();
}
@Test
public void constantField_immutableList() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"package test;",
"import com.google.common.collect.ImmutableList;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public abstract class CompileTimeConstantTestCase {",
" @CompileTimeConstant final ImmutableList<String> x = ImmutableList.of(\"a\");",
"}")
.doTest();
}
}
| 25,122
| 36.385417
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SymbolToStringTest.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 SymbolToString}. */
@RunWith(JUnit4.class)
public class SymbolToStringTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(SymbolToString.class, getClass());
@Test
public void noMatch() {
testHelper
.addSourceLines(
"ExampleChecker.java",
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.BugPattern.SeverityLevel;",
"import com.google.errorprone.VisitorState;",
"import com.google.errorprone.bugpatterns.BugChecker;",
"import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;",
"import com.google.errorprone.matchers.Description;",
"import com.sun.source.tree.ClassTree;",
"import com.sun.tools.javac.code.Types;",
"@BugPattern(name = \"Example\", summary = \"\", severity = SeverityLevel.ERROR)",
"public class ExampleChecker extends BugChecker implements ClassTreeMatcher {",
" @Override public Description matchClass(ClassTree t, VisitorState s) {",
" return Description.NO_MATCH;",
" }",
"}")
.addModules("jdk.compiler/com.sun.tools.javac.code")
.doTest();
}
@Test
public void matchInABugChecker() {
testHelper
.addSourceLines(
"ExampleChecker.java",
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.BugPattern.SeverityLevel;",
"import com.google.errorprone.VisitorState;",
"import com.google.errorprone.bugpatterns.BugChecker;",
"import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;",
"import com.google.errorprone.fixes.SuggestedFix;",
"import com.google.errorprone.matchers.Description;",
"import com.google.errorprone.matchers.Matcher;",
"import com.sun.source.tree.ClassTree;",
"import com.sun.tools.javac.code.Symbol;",
"import com.sun.tools.javac.code.Symbol.ClassSymbol;",
"import com.sun.tools.javac.tree.TreeMaker;",
"import com.sun.tools.javac.code.Type;",
"import com.sun.tools.javac.code.Types;",
"import com.sun.tools.javac.tree.JCTree.JCClassDecl;",
"@BugPattern(name = \"Example\", summary = \"\", severity = SeverityLevel.ERROR)",
"public class ExampleChecker extends BugChecker implements ClassTreeMatcher {",
" @Override",
" public Description matchClass(ClassTree tree, VisitorState state) {",
" Symbol classSymbol = ((JCClassDecl) tree).sym;",
" if (classSymbol.toString().contains(\"matcha\")) {",
" return describeMatch(tree);",
" }",
" // BUG: Diagnostic contains: SymbolToString",
" if (classSymbol.toString().equals(\"match\")) {",
" return describeMatch(tree);",
" }",
" if (new InnerClass().matchaMatcher(classSymbol)) {",
" return describeMatch(tree);",
" }",
" return Description.NO_MATCH;",
" }",
"",
" class InnerClass {",
" boolean matchaMatcher(Symbol sym) {",
" // BUG: Diagnostic contains: SymbolToString",
" return sym.toString().equals(\"match\");",
" }",
" }",
"}")
.addModules(
"jdk.compiler/com.sun.tools.javac.code",
"jdk.compiler/com.sun.tools.javac.tree",
"jdk.compiler/com.sun.tools.javac.util")
.doTest();
}
}
| 4,552
| 42.361905
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TypeParameterNamingTest.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.common.truth.Truth.assertWithMessage;
import static com.google.errorprone.bugpatterns.TypeParameterNaming.TypeParameterNamingClassification.CLASS_NAME_WITH_T;
import static com.google.errorprone.bugpatterns.TypeParameterNaming.TypeParameterNamingClassification.LETTER_WITH_MAYBE_NUMERAL;
import static com.google.errorprone.bugpatterns.TypeParameterNaming.TypeParameterNamingClassification.NON_CLASS_NAME_WITH_T_SUFFIX;
import static com.google.errorprone.bugpatterns.TypeParameterNaming.TypeParameterNamingClassification.UNCLASSIFIED;
import com.google.common.truth.Subject;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.bugpatterns.TypeParameterNaming.TypeParameterNamingClassification;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link TypeParameterNaming} */
@RunWith(JUnit4.class)
public class TypeParameterNamingTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(TypeParameterNaming.class, getClass());
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(TypeParameterNaming.class, getClass());
@Test
public void positiveCases() {
compilationHelper
.addSourceLines(
"Test.java",
"// BUG: Diagnostic contains: TypeParameterNaming",
"class Test<BadName> {",
" // BUG: Diagnostic contains: TypeParameterNaming",
" public <T, Foo> void method(Exception e) {}",
"}")
.doTest();
}
@Test
public void refactoring_trailing() {
refactoring
.addInputLines(
"in/Test.java",
"/** @param <BadName> bad name */",
"class Test<BadName> {",
" public <T, Foo> void method(Foo f) {",
" BadName bad = null;",
" Foo d = f;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"/** @param <BadNameT> bad name */",
"class Test<BadNameT> {",
" public <T, FooT> void method(FooT f) {",
" BadNameT bad = null;",
" FooT d = f;",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void refactoring_single() {
refactoring
.addInputLines(
"in/Test.java",
"class Test<BadName> {",
" /** @param <Foo> foo */",
" public <T, Foo> void method(Foo f) {",
" BadName bad = null;",
" Foo d = f;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test<B> {",
" /** @param <F> foo */",
" public <T, F> void method(F f) {",
" B bad = null;",
" F d = f;",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void refactoring_single_number() {
refactoring
.addInputLines(
"in/Test.java",
"class Test<Bar> {",
" public <T, Baz> void method(Baz f) {",
" Bar bad = null;",
" Baz d = f;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test<B> {",
" public <T, B2> void method(B2 f) {",
" B bad = null;",
" B2 d = f;",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void refactoring_single_number_enclosing() {
refactoring
.addInputLines(
"in/Test.java",
"class Test<Bar> {",
" public <T, Baz, Boo> void method(Baz f) {",
" Bar bad = null;",
" Baz d = f;",
" Boo wow = null;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test<B> {",
" public <T, B2, B3> void method(B2 f) {",
" B bad = null;",
" B2 d = f;",
" B3 wow = null;",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void refactoring_single_number_within_scope() {
refactoring
.addInputLines(
"in/Test.java",
"class Test {",
" public <T, Baz, Boo> void method(Baz f) {",
" Baz d = f;",
" Boo wow = null;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" public <T, B, B2> void method(B f) {",
" B d = f;",
" B2 wow = null;",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void refactoring_single_number_many_ok() {
refactoring
.addInputLines(
"in/Test.java",
"class Test {",
" public <B, B2, B3, B4, Bad> void method(Bad f) {",
" Bad d = f;",
" B2 wow = null;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" public <B, B2, B3, B4, B5> void method(B5 f) {",
" B5 d = f;",
" B2 wow = null;",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void refactoring_single_number_ok_after() {
refactoring
.addInputLines(
"in/Test.java",
"class Test {",
" public <B, Bad, B2> void method(Bad f) {",
" Bad d = f;",
" B2 wow = null;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" public <B, B3, B2> void method(B3 f) {",
" B3 d = f;",
" B2 wow = null;",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void refactoring_newNames() {
refactoring
.addInputLines(
"in/Test.java",
"class Test<RESP> {",
" public <TBaz, Foo> void method(Foo f) {",
" TBaz bad = null;",
" Foo d = f;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test<RespT> {",
" public <BazT, FooT> void method(FooT f) {",
" BazT bad = null;",
" FooT d = f;",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void refactoring_tSuffixes() {
refactoring
.addInputLines(
"in/Test.java",
"class Test<RESP> {",
" public <FOOT, BART> void method(FOOT f) {",
" BART bad = null;",
" FOOT d = f;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test<RespT> {",
" public <F, B> void method(F f) {",
" B bad = null;",
" F d = f;",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void negativeCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.ArrayList;",
"class Test<MyClassVarT> {",
" public <T, T3, SomeOtherT> void method(Exception e) {",
" ArrayList<String> dontCheckTypeArguments = new ArrayList<String>();",
" }",
"}")
.doTest();
}
@Test
public void negativeCases_manyNumberedTypes() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.ArrayList;",
"class Test<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> {",
" public <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> void method(Exception e) {",
" T10 t = null;",
" }",
"}")
.doTest();
}
@Test
public void refactoring_underscore() {
refactoring
.addInputLines(
"in/Test.java", //
"class Test {",
" public <_T> void method(_T t) {",
" }",
"}")
.addOutputLines(
"in/Test.java", //
"class Test {",
" public <T> void method(T t) {",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void classifyTypeName_singleLetter() {
assertKindOfName("T").isEqualTo(LETTER_WITH_MAYBE_NUMERAL);
assertKindOfName("D").isEqualTo(LETTER_WITH_MAYBE_NUMERAL);
assertKindOfName("T9").isEqualTo(LETTER_WITH_MAYBE_NUMERAL);
assertKindOfName("X").isEqualTo(LETTER_WITH_MAYBE_NUMERAL);
}
@Test
public void classifyTypeName_classT() {
assertKindOfName("FooT").isEqualTo(CLASS_NAME_WITH_T);
assertKindOfName("FooBarT").isEqualTo(CLASS_NAME_WITH_T);
assertKindOfName("FoobarT").isEqualTo(CLASS_NAME_WITH_T);
}
@Test
public void classifyTypeName_invalidTypeParameters() {
assertKindOfName("FooD").isEqualTo(UNCLASSIFIED);
assertKindOfName("somethingT").isEqualTo(NON_CLASS_NAME_WITH_T_SUFFIX);
assertKindOfName("Some_TokenT").isEqualTo(NON_CLASS_NAME_WITH_T_SUFFIX);
// Here, we don't tokenize LOUDT as L_O_U_D_T, but as one token
assertKindOfName("LOUDT").isEqualTo(NON_CLASS_NAME_WITH_T_SUFFIX);
// Per Google style guide, acronyms should be lowercase
assertKindOfName("HTTPHeaderT").isEqualTo(NON_CLASS_NAME_WITH_T_SUFFIX);
// This is unfortunate, the first 'word' is a single character, but falls into the same bin
// as above.
assertKindOfName("ACanalPanamaT").isEqualTo(NON_CLASS_NAME_WITH_T_SUFFIX);
}
private static Subject assertKindOfName(String s) {
return assertWithMessage(s).that(TypeParameterNamingClassification.classify(s));
}
}
| 11,131
| 30.7151
| 131
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MixedDescriptorsTest.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 MixedDescriptors} bugpattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class MixedDescriptorsTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(MixedDescriptors.class, getClass());
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"import com.google.protobuf.Descriptors.Descriptor;",
"final class Test {",
" void test(Descriptor d) {",
" TestFieldProtoMessage.getDescriptor().findFieldByNumber(",
" TestFieldProtoMessage.FIELD_FIELD_NUMBER);",
" TestFieldProtoMessage.getDescriptor().findFieldByNumber(1);",
" d.findFieldByNumber(TestFieldProtoMessage.FIELD_FIELD_NUMBER);",
" }",
"}")
.doTest();
}
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"final class Test {",
" void test() {",
" // BUG: Diagnostic contains:",
" TestFieldProtoMessage.getDescriptor().findFieldByNumber(",
" TestProtoMessage.MULTI_FIELD_FIELD_NUMBER);",
" }",
"}")
.doTest();
}
}
| 2,506
| 34.814286
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SelfComparisonTest.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.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link SelfComparison} bug pattern.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@RunWith(JUnit4.class)
public class SelfComparisonTest {
CompilationTestHelper compilationHelper;
@Before
public void setUp() {
compilationHelper = CompilationTestHelper.newInstance(SelfComparison.class, getClass());
}
@Test
public void positiveCase() {
compilationHelper.addSourceFile("SelfComparisonPositiveCase.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("SelfComparisonNegativeCases.java").doTest();
}
}
| 1,418
| 27.959184
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MultipleParallelOrSequentialCallsTest.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.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link MultipleParallelOrSequentialCalls}.
*
* @author mariasam@google.com (Maria Sam) on 7/6/17.
*/
@RunWith(JUnit4.class)
public class MultipleParallelOrSequentialCallsTest {
CompilationTestHelper compilationTestHelper;
@Before
public void setup() {
compilationTestHelper =
CompilationTestHelper.newInstance(MultipleParallelOrSequentialCalls.class, getClass());
}
@Test
public void positiveCases() {
compilationTestHelper
.addSourceFile("MultipleParallelOrSequentialCallsPositiveCases.java")
.doTest();
}
@Test
public void negativeCases() {
compilationTestHelper
.addSourceFile("MultipleParallelOrSequentialCallsNegativeCases.java")
.doTest();
}
@Test
public void fixes() {
BugCheckerRefactoringTestHelper.newInstance(MultipleParallelOrSequentialCalls.class, getClass())
.addInput("MultipleParallelOrSequentialCallsPositiveCases.java")
.addOutput("MultipleParallelOrSequentialCallsPositiveCases_expected.java")
.doTest(TestMode.AST_MATCH);
}
}
| 2,034
| 30.796875
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryLambdaTest.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;
/** {@link UnnecessaryLambda}Test */
@RunWith(JUnit4.class)
public class UnnecessaryLambdaTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryLambda.class, getClass());
@Test
public void method() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private Function<String, String> f() {",
" return x -> {",
" return \"hello \" + x;",
" };",
" }",
" void g() {",
" Function<String, String> f = f();",
" System.err.println(f().apply(\"world\"));",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private String f(String x) {",
" return \"hello \" + x;",
" }",
" void g() {",
" Function<String, String> f = this::f;",
" System.err.println(f(\"world\"));",
" }",
"}")
.doTest();
}
@Test
public void method_effectivelyPrivate() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private class Inner {",
" Function<String, String> f() {",
" return x -> {",
" return \"hello \" + x;",
" };",
" }",
" void g() {",
" Function<String, String> f = f();",
" System.err.println(f().apply(\"world\"));",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private class Inner {",
" String f(String x) {",
" return \"hello \" + x;",
" }",
" void g() {",
" Function<String, String> f = this::f;",
" System.err.println(f(\"world\"));",
" }",
" }",
"}")
.doTest();
}
@Test
public void method_static() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private static Function<String, String> f() {",
" return x -> \"hello \" + x;",
" }",
" void g() {",
" Function<String, String> f = f();",
" System.err.println(f().apply(\"world\"));",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private static String f(String x) {",
" return \"hello \" + x;",
" }",
" void g() {",
" Function<String, String> f = Test::f;",
" System.err.println(f(\"world\"));",
" }",
"}")
.doTest();
}
@Test
public void method_void() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Consumer;",
"class Test {",
" private Consumer<String> f() {",
" return x -> System.err.println(x);",
" }",
" void g() {",
" Consumer<String> f = f();",
" f().accept(\"world\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.Consumer;",
"class Test {",
" private void f(String x) {",
" System.err.println(x);",
" }",
" void g() {",
" Consumer<String> f = this::f;",
" f(\"world\");",
" }",
"}")
.doTest();
}
@Test
public void variable_instance() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private final Function<String, String> camelCase = x -> \"hello \" + x;",
" void g() {",
" Function<String, String> f = camelCase;",
" System.err.println(camelCase.apply(\"world\"));",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private String camelCase(String x) {",
" return \"hello \" + x;",
" }",
" void g() {",
" Function<String, String> f = this::camelCase;",
" System.err.println(camelCase(\"world\"));",
" }",
"}")
.doTest();
}
@Test
public void variable_static() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private static final Function<String, String> F = x -> \"hello \" + x;",
" void g() {",
" Function<String, String> l = Test.F;",
" System.err.println(F.apply(\"world\"));",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private static String f(String x) {",
" return \"hello \" + x;",
" }",
" void g() {",
" Function<String, String> l = Test::f;",
" System.err.println(f(\"world\"));",
" }",
"}")
.doTest();
}
@Test
public void method_shapes() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.BiFunction;",
"import java.util.function.Supplier;",
"class Test {",
" private Supplier<String> f() {",
" return () -> \"hello \";",
" }",
" private BiFunction<String, String, String> g() {",
" return (a, b) -> a + \"hello \" + b;",
" }",
" private Runnable h() {",
" return () -> System.err.println();",
" }",
" void main() {",
" System.err.println(f().get());",
" System.err.println(g().apply(\"a\", \"b\"));",
" h().run();",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.BiFunction;",
"import java.util.function.Supplier;",
"class Test {",
" private String f() {",
" return \"hello \";",
" }",
" private String g(String a, String b) {",
" return a + \"hello \" + b;",
" }",
" private void h() {",
" System.err.println();",
" }",
" void main() {",
" System.err.println(f());",
" System.err.println(g(\"a\", \"b\"));",
" h();",
" }",
"}")
.doTest();
}
@Test
public void nonFunctionalInterfaceMethod() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Predicate;",
"class Test {",
" private static final Predicate<String> F = x -> \"hello \".equals(x);",
" void g() {",
" Predicate<String> l = Test.F.and(x -> true);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void variable_bind() {
testHelper
.addInputLines(
"Bind.java",
"package com.google.inject.testing.fieldbinder;",
"import static java.lang.annotation.ElementType.FIELD;",
"import static java.lang.annotation.RetentionPolicy.RUNTIME;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.Target;",
"@Retention(RUNTIME)",
"@Target({FIELD})",
"public @interface Bind {}")
.expectUnchanged()
.addInputLines(
"Test.java",
"import java.util.function.Function;",
"import com.google.inject.testing.fieldbinder.Bind;",
"class Test {",
" @Bind",
" private final Function<String, String> camelCase = x -> \"hello \" + x;",
" void g() {",
" Function<String, String> f = camelCase;",
" System.err.println(camelCase.apply(\"world\"));",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void variable_notAFunctionalInterface() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Function;",
"class Test {",
" private static final Object F = (Function<String, String>) x -> \"hello \" + x;",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void recursiveLambda_ignored() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Predicate;",
"class Test {",
" private static final Predicate<String> F = x -> Test.F.test(x);",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void producesIgnored() {
testHelper
.addInputLines(
"Produces.java", //
"@interface Produces {",
"}")
.expectUnchanged()
.addInputLines(
"Test.java",
"import javax.inject.Provider;",
"class Test {",
" private class A {",
" @Produces",
" public Provider<String> foo() {",
" return () -> \"hello \";",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void e() {
testHelper
.addInputLines(
"Test.java",
"import java.util.function.Predicate;",
"class Test {",
" private void foo(Predicate<Object> p) {}",
" public void test() {",
" foo(E.ELEM.pred());",
" }",
" private enum E {",
" ELEM;",
" Predicate<Object> pred() {",
" return o -> true;",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.Predicate;",
"class Test {",
" private void foo(Predicate<Object> p) {}",
" public void test() {",
" foo(E.ELEM::pred);",
" }",
" private enum E {",
" ELEM;",
" boolean pred(Object o) {",
" return true;",
" }",
" }",
"}")
.doTest();
}
}
| 12,140
| 29.971939
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/GetClassOnAnnotationTest.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 GetClassOnAnnotation}Test */
@RunWith(JUnit4.class)
public class GetClassOnAnnotationTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(GetClassOnAnnotation.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f(Deprecated deprecated) {",
" // BUG: Diagnostic contains: System.err.println(deprecated.annotationType());",
" System.err.println(deprecated.getClass());",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f(Deprecated deprecated) {",
" System.err.println(this.getClass());",
" }",
"}")
.doTest();
}
}
| 1,743
| 29.068966
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SelfAlwaysReturnsThisTest.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 org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for the {@link SelfAlwaysReturnsThis}. */
@RunWith(JUnit4.class)
public class SelfAlwaysReturnsThisTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(SelfAlwaysReturnsThis.class, getClass());
@Test
public void selfReturnsThis() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" return this;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void selfReturnsThis_withCast() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" return (Builder) this;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void selfReturnsThis_withParenthesizedCast() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" return ((Builder) (this));",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void selfReturnsThis_withCastAndTryCatch() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" try {",
" return (Builder) this;",
" } catch (ClassCastException e) {",
// sometimes people log here?
" throw e;",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void selfReturnsThis_withMultipleReturnStatements() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" if (System.currentTimeMillis() % 2 == 0) {",
" return this;",
" } else {",
" return this;",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void selfReturnsThis_withTwoStatementCast() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" // sometimes people write comments here :-)",
" Builder self = (Builder) this;",
" return self;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void selfReturnsThis_withImplComment() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" // this is an impl comment",
" return this;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void selfReturnsThis_withInlineComment() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" return /* self */ this;",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void selfReturnsNewBuilder() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" return new Builder();",
" }",
"}")
.addOutputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self() {",
" return this;",
" }",
"}")
.doTest();
}
@Test
public void getThisReturnsNewBuilder() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder getThis() {",
" return new Builder();",
" }",
"}")
.addOutputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder getThis() {",
" return this;",
" }",
"}")
.doTest();
}
@Test
public void self_voidReturn() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public void self() {",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void self_differentReturnType() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public String self() {",
" return \"hi\";",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void self_static() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public static Builder self() {",
" return new Builder();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void self_notNamedSelf() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder selfie() {",
" return new Builder();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void self_hasParams() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public final class Builder {",
" public Builder self(int foo) {",
" return new Builder();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void self_abstract() {
helper
.addInputLines(
"Builder.java",
"package com.google.frobber;",
"public abstract class Builder {",
" public abstract Builder self();",
"}")
.expectUnchanged()
.doTest();
}
// TODO(kak): add a test for the inheritance style Builder (which requires a (T) cast).
}
| 7,910
| 25.726351
| 91
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DiscardedPostfixExpressionTest.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;
/** {@link DiscardedPostfixExpression}Test */
@RunWith(JUnit4.class)
public final class DiscardedPostfixExpressionTest {
@Test
public void negative() {
CompilationTestHelper.newInstance(DiscardedPostfixExpression.class, getClass())
.addSourceLines(
"Test.java",
"import java.util.function.UnaryOperator;",
"class Test {",
" int x;",
" UnaryOperator<Integer> f = x1 -> x++;",
" UnaryOperator<Integer> g = x1 -> x--;",
" UnaryOperator<Integer> h = x -> ++x;",
" UnaryOperator<Integer> i = x -> --x;",
"}")
.doTest();
}
@Test
public void refactoring() {
BugCheckerRefactoringTestHelper.newInstance(DiscardedPostfixExpression.class, getClass())
.addInputLines(
"Test.java",
"import java.util.function.UnaryOperator;",
"class Test {",
" UnaryOperator<Integer> f = x -> x++;",
" UnaryOperator<Integer> g = x -> x--;",
"}")
.addOutputLines(
"Test.java",
"import java.util.function.UnaryOperator;",
"class Test {",
" UnaryOperator<Integer> f = x -> x + 1;",
" UnaryOperator<Integer> g = x -> x - 1;",
"}")
.doTest();
}
}
| 2,192
| 33.265625
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StreamToStringTest.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 StreamToString}Test */
@RunWith(JUnit4.class)
public class StreamToStringTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(StreamToString.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Arrays;",
"class Test {",
" public static void main(String[] args) {",
" // BUG: Diagnostic contains:",
" System.err.println(Arrays.asList(42).stream());",
" // BUG: Diagnostic contains:",
" Arrays.asList(42).stream().toString();",
" // BUG: Diagnostic contains:",
" String.valueOf(Arrays.asList(42).stream());",
" // BUG: Diagnostic contains:",
" String s = \"\" + Arrays.asList(42).stream();",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Arrays;",
"import java.util.stream.Collectors;",
"class Test {",
" public static void main(String[] args) {",
" System.err.println(Arrays.asList(42).stream()",
" .map(String::valueOf).collect(Collectors.joining(\", \")));",
" String.valueOf(Arrays.asList(42).stream()",
" .map(String::valueOf).collect(Collectors.joining(\", \")));",
" String s = \"\" + Arrays.asList(42).stream()",
" .map(String::valueOf).collect(Collectors.joining(\", \"));",
" String.format(\"%s %s\", null, null);",
" }",
"}")
.doTest();
}
@Test
public void withinStreamClass() {
compilationHelper
.addSourceLines(
"Test.java",
"public abstract class Test implements java.util.stream.Stream {",
" public String s() {",
" return toString();",
" }",
"}")
.doTest();
}
}
| 2,923
| 33
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MissingTestCallTest.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 MissingTestCallTest} bugpattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class MissingTestCallTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(MissingTestCall.class, getClass());
@Test
public void positive() {
helper
.addSourceLines(
"Case.java",
"import com.google.common.testing.EqualsTester;",
"import com.google.errorprone.BugCheckerRefactoringTestHelper;",
"import com.google.errorprone.CompilationTestHelper;",
"import org.junit.Test;",
"class Case {",
" @Test",
" // BUG: Diagnostic contains:",
" void test() {",
" new EqualsTester().addEqualityGroup(this, this);",
" hashCode();",
" }",
" @Test",
" // BUG: Diagnostic contains:",
" void test2(CompilationTestHelper helper) {",
" helper.addSourceFile(\"Foo.java\");",
" }",
" @Test",
" // BUG: Diagnostic contains:",
" void test3(BugCheckerRefactoringTestHelper helper) {",
" helper.addInput(\"Foo.java\");",
" }",
"}")
.doTest();
}
@Test
public void negative() {
helper
.addSourceLines(
"Case.java",
"import com.google.common.testing.EqualsTester;",
"import com.google.errorprone.CompilationTestHelper;",
"import org.junit.Test;",
"class Case {",
" CompilationTestHelper helper;",
" @Test",
" void test() {",
" new EqualsTester().addEqualityGroup(this, this).testEquals();",
" }",
" @Test",
" void doesNotMatchIfNotAtEnd() {",
" helper.addSourceFile(\"Foo.java\");",
" hashCode();",
" }",
"}")
.doTest();
}
@Test
public void negativeNotTest() {
helper
.addSourceLines(
"Case.java",
"import com.google.common.testing.EqualsTester;",
"class Case {",
" private EqualsTester et;",
" void add() {",
" et.addEqualityGroup(this, this);",
" }",
"}")
.doTest();
}
}
| 3,215
| 30.529412
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.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 org.junit.Assert.assertThrows;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.annotations.DoNotCall;
import java.sql.Date;
import java.sql.Time;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link DoNotCallChecker}Test */
@SuppressWarnings("DoNotCall")
@RunWith(JUnit4.class)
public class DoNotCallCheckerTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(DoNotCallChecker.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.DoNotCall;",
"class Test {",
" @DoNotCall(\"satisfying explanation\") final void f() {}",
" @DoNotCall final void g() {}",
" void m() {",
" // BUG: Diagnostic contains:",
" // This method should not be called: satisfying explanation",
" f();",
" // BUG: Diagnostic contains:",
" // This method should not be called, see its documentation for details",
" g();",
" // BUG: Diagnostic contains:",
" Runnable r = this::g;",
" }",
"}")
.doTest();
}
@Test
public void positiveWhereDeclaredTypeIsSuper() {
testHelperWithImmutableList()
.addSourceLines(
"Test.java",
"import java.util.List;",
"class Test {",
" void foo() {",
" List<Integer> xs = ImmutableList.of();",
" // BUG: Diagnostic contains:",
" xs.add(1);",
" xs.get(1);",
" }",
"}")
.doTest();
}
@Test
public void positiveWhereDeclaredTypeIsSuper_butAssignedMultipleTimes() {
testHelperWithImmutableList()
.addSourceLines(
"Test.java",
"import java.util.List;",
"class Test {",
" void foo() {",
" List<Integer> xs;",
" if (hashCode() == 0) {",
" xs = ImmutableList.of();",
" } else {",
" xs = ImmutableList.of();",
" }",
" // BUG: Diagnostic contains:",
" xs.add(1);",
" xs.get(1);",
" }",
"}")
.doTest();
}
private CompilationTestHelper testHelperWithImmutableList() {
// Stub out an ImmutableList with the annotations we need for testing.
return testHelper
.addSourceLines(
"ImmutableCollection.java",
"import com.google.errorprone.annotations.DoNotCall;",
"import java.util.List;",
"abstract class ImmutableCollection<T> implements java.util.Collection<T> {",
" @DoNotCall @Override public final boolean add(T t) { throw new"
+ " UnsupportedOperationException(); }",
"}")
.addSourceLines(
"ImmutableList.java",
"import com.google.errorprone.annotations.DoNotCall;",
"import java.util.List;",
"abstract class ImmutableList<T> extends ImmutableCollection<T> implements List<T> {",
" public static <T> ImmutableList<T> of() {",
" return null;",
" }",
"}");
}
@Test
public void positiveWhereDeclaredTypeIsSuper_butNotAssignedOnce() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" void foo() {",
" List<Integer> xs;",
" if (true) {",
" xs = ImmutableList.of();",
" } else {",
" xs = new ArrayList<>();",
" xs.add(2);",
" }",
" }",
"}")
.doTest();
}
@Test
public void concreteFinal() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.DoNotCall;",
"public class Test {",
" // BUG: Diagnostic contains: should be final",
" @DoNotCall public void f() {}",
" @DoNotCall public final void g() {}",
"}")
.doTest();
}
@Test
public void requiredOverride() {
testHelper
.addSourceLines(
"A.java",
"import com.google.errorprone.annotations.DoNotCall;",
"public interface A {",
" @DoNotCall public void f();",
"}")
.addSourceLines(
"B.java",
"public class B implements A {",
" // BUG: Diagnostic contains: overrides f in A which is annotated",
" @Override public void f() {}",
"}")
.doTest();
}
@Test
public void annotatedOverride() {
testHelper
.addSourceLines(
"A.java",
"import com.google.errorprone.annotations.DoNotCall;",
"public interface A {",
" @DoNotCall public void f();",
"}")
.addSourceLines(
"B.java",
"import com.google.errorprone.annotations.DoNotCall;",
"public class B implements A {",
" @DoNotCall @Override public final void f() {}",
"}")
.doTest();
}
// The interface tries to make Object#toString @DoNotCall, and because
// the declaration in B is implicit it doesn't get checked.
// In practice, making default Object methods @DoNotCall isn't super
// useful - typically users interface with the interface directly
// (e.g. Hasher) or there's an override that has unwanted behaviour (Localizable).
// TODO(cushon): check class declarations for super-interfaces that do this?
@Test
public void interfaceRedeclaresObjectMethod() {
testHelper
.addSourceLines(
"I.java",
"import com.google.errorprone.annotations.DoNotCall;",
"public interface I {",
" @DoNotCall public String toString();",
"}")
.addSourceLines(
"B.java", //
"public class B implements I {",
"}")
.addSourceLines(
"Test.java", //
"public class Test {",
" void f(B b) {",
" b.toString();",
" I i = b;",
" // BUG: Diagnostic contains:",
" i.toString();",
" }",
"}")
.doTest();
}
@Test
public void finalClass() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.DoNotCall;",
"public final class Test {",
" @DoNotCall public void f() {}",
"}")
.doTest();
}
@Test
public void privateMethod() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.DoNotCall;",
"public final class Test {",
" // BUG: Diagnostic contains: private method",
" @DoNotCall private void f() {}",
"}")
.doTest();
}
/** Test class containing a method annotated with @DNC. */
public static final class DNCTest {
@DoNotCall
public static void f() {}
private DNCTest() {}
}
@Test
public void noDNConClasspath() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" // BUG: Diagnostic contains: This method should not be called",
" com.google.errorprone.bugpatterns.DoNotCallCheckerTest.DNCTest.f();",
" }",
"}")
.withClasspath(DNCTest.class, DoNotCallCheckerTest.class)
.doTest();
}
@Test
public void thirdParty() {
testHelper
.addSourceLines(
"Test.java",
"import org.junit.Assert;",
"public class Test {",
" public void foo() {",
" // BUG: Diagnostic contains: DoNotCall",
" Assert.assertEquals(2.0, 2.0);",
" // BUG: Diagnostic contains: DoNotCall",
" Assert.assertEquals(\"msg\", 2.0, 2.0);",
// These are OK since they pass a tolerance
" Assert.assertEquals(2.0, 2.0, 0.01);",
" Assert.assertEquals(\"msg\", 2.0, 2.0, 0.01);",
" }",
"}")
.doTest();
}
@Test
public void javaSqlDate_toInstant() {
assertThrows(UnsupportedOperationException.class, () -> new Date(1234567890L).toInstant());
testHelper
.addSourceLines(
"TestClass.java",
"import java.sql.Date;",
"import java.time.Instant;",
"public class TestClass {",
" public void badApis(Date date) {",
" // BUG: Diagnostic contains: toLocalDate()",
" Instant instant = date.toInstant();",
" }",
"}")
.doTest();
}
@Test
public void javaSqlDate_timeGetters() {
Date date = new Date(1234567890L);
assertThrows(IllegalArgumentException.class, () -> date.getHours());
assertThrows(IllegalArgumentException.class, () -> date.getMinutes());
assertThrows(IllegalArgumentException.class, () -> date.getSeconds());
testHelper
.addSourceLines(
"TestClass.java",
"import java.sql.Date;",
"public class TestClass {",
" public void badApis(Date date) {",
" // BUG: Diagnostic contains: DoNotCall",
" int hour = date.getHours();",
" // BUG: Diagnostic contains: DoNotCall",
" int mins = date.getMinutes();",
" // BUG: Diagnostic contains: DoNotCall",
" int secs = date.getSeconds();",
" }",
"}")
.doTest();
}
@Test
public void javaSqlDate_timeSetters() {
Date date = new Date(1234567890L);
assertThrows(IllegalArgumentException.class, () -> date.setHours(1));
assertThrows(IllegalArgumentException.class, () -> date.setMinutes(1));
assertThrows(IllegalArgumentException.class, () -> date.setSeconds(1));
testHelper
.addSourceLines(
"TestClass.java",
"import java.sql.Date;",
"public class TestClass {",
" public void badApis(Date date) {",
" // BUG: Diagnostic contains: DoNotCall",
" date.setHours(1);",
" // BUG: Diagnostic contains: DoNotCall",
" date.setMinutes(1);",
" // BUG: Diagnostic contains: DoNotCall",
" date.setSeconds(1);",
" }",
"}")
.doTest();
}
@Test
public void javaSqlDate_staticallyTypedAsJavaUtilDate() {
testHelper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"import java.util.Date;",
"public class TestClass {",
" public void badApis() {",
" Date date = new java.sql.Date(1234567890L);",
" Instant instant = date.toInstant();",
" int hour = date.getHours();",
" int mins = date.getMinutes();",
" int secs = date.getSeconds();",
" date.setHours(1);",
" date.setMinutes(1);",
" date.setSeconds(1);",
" }",
"}")
.doTest();
}
@Test
public void javaSqlTime_toInstant() {
assertThrows(UnsupportedOperationException.class, () -> new Time(1234567890L).toInstant());
testHelper
.addSourceLines(
"TestClass.java",
"import java.sql.Time;",
"import java.time.Instant;",
"public class TestClass {",
" public void badApis(Time time) {",
" // BUG: Diagnostic contains: toLocalTime()",
" Instant instant = time.toInstant();",
" }",
"}")
.doTest();
}
@Test
public void javaSqlTime_dateGetters() {
Time time = new Time(1234567890L);
assertThrows(IllegalArgumentException.class, () -> time.getYear());
assertThrows(IllegalArgumentException.class, () -> time.getMonth());
assertThrows(IllegalArgumentException.class, () -> time.getDay());
assertThrows(IllegalArgumentException.class, () -> time.getDate());
testHelper
.addSourceLines(
"TestClass.java",
"import java.sql.Time;",
"public class TestClass {",
" public void badApis(Time time) {",
" // BUG: Diagnostic contains: DoNotCall",
" int year = time.getYear();",
" // BUG: Diagnostic contains: DoNotCall",
" int month = time.getMonth();",
" // BUG: Diagnostic contains: DoNotCall",
" int day = time.getDay();",
" // BUG: Diagnostic contains: DoNotCall",
" int date = time.getDate();",
" }",
"}")
.doTest();
}
@Test
public void javaSqlTime_dateSetters() {
Time time = new Time(1234567890L);
assertThrows(IllegalArgumentException.class, () -> time.setYear(1));
assertThrows(IllegalArgumentException.class, () -> time.setMonth(1));
assertThrows(IllegalArgumentException.class, () -> time.setDate(1));
testHelper
.addSourceLines(
"TestClass.java",
"import java.sql.Time;",
"public class TestClass {",
" public void badApis(Time time) {",
" // BUG: Diagnostic contains: DoNotCall",
" time.setYear(1);",
" // BUG: Diagnostic contains: DoNotCall",
" time.setMonth(1);",
" // BUG: Diagnostic contains: DoNotCall",
" time.setDate(1);",
" }",
"}")
.doTest();
}
@Test
public void javaSqlTime_staticallyTypedAsJavaUtilDate() {
testHelper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"import java.util.Date;",
"public class TestClass {",
" public void badApis() {",
" Date time = new java.sql.Time(1234567890L);",
" Instant instant = time.toInstant();",
" int year = time.getYear();",
" int month = time.getMonth();",
" int date = time.getDate();",
" int day = time.getDay();",
" time.setYear(1);",
" time.setMonth(1);",
" time.setDate(1);",
" }",
"}")
.doTest();
}
@Test
public void readLock_newCondition() {
assertThrows(
UnsupportedOperationException.class,
() -> new ReentrantReadWriteLock().readLock().newCondition());
testHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.locks.ReentrantReadWriteLock;",
"public class Test {",
" public void foo() {",
" ReentrantReadWriteLock.ReadLock lock = new ReentrantReadWriteLock().readLock();",
" // BUG: Diagnostic contains: DoNotCall",
" lock.newCondition();",
" }",
"}")
.doTest();
}
@Test
public void threadLocalRandom_setSeed() {
assertThrows(
UnsupportedOperationException.class, () -> ThreadLocalRandom.current().setSeed(42));
testHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.ThreadLocalRandom;",
"public class Test {",
" public void foo() {",
" ThreadLocalRandom random = ThreadLocalRandom.current();",
" // BUG: Diagnostic contains: DoNotCall",
" random.setSeed(42L);",
" }",
"}")
.doTest();
}
@Test
public void memberReferencesOnThirdPartyMethods() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.concurrent.ThreadLocalRandom;",
"import java.util.Optional;",
"public class Test {",
" public void foo(Optional<Long> x) {",
" ThreadLocalRandom random = ThreadLocalRandom.current();",
" // BUG: Diagnostic contains: DoNotCall",
" x.ifPresent(random::setSeed);",
" }",
"}")
.doTest();
}
@Test
public void typeArgs_dontCrash() {
testHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"class Test<T extends java.util.Collection<Object>> {",
" @Override public boolean equals(Object o) {",
" T foo = (T) o;",
" return foo.equals(1);",
" }",
"}")
.doTest();
}
@Test
public void positive_getSimpleName_refactoredToGetClassName() {
testHelper
.addSourceLines(
"Test.java",
"class Test{",
" void f() {",
" try {",
" throw new Exception();",
" } catch (Exception ex) {",
" // BUG: Diagnostic contains: getClassName",
" ex.getStackTrace()[0].getClass().getSimpleName();",
" }",
" }",
"}")
.doTest();
}
@Test
public void positive_stackWalkerGetClass() {
testHelper
.addSourceLines(
"Test.java",
"class Test{",
" void f(StackWalker w) {",
" // BUG: Diagnostic contains: getCallerClass",
" w.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_stackFrameGetClass() {
testHelper
.addSourceLines(
"Test.java",
"import java.lang.StackWalker.StackFrame;",
"class Test{",
" void f(StackFrame f) {",
" // BUG: Diagnostic contains: getClassName",
" f.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_constructorGetClass() {
testHelper
.addSourceLines(
"Test.java",
"import java.lang.reflect.Constructor;",
"class Test{",
" void f(Constructor<?> c) {",
" // BUG: Diagnostic contains: getDeclaringClass",
" c.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_fieldGetClass() {
testHelper
.addSourceLines(
"Test.java",
"import java.lang.reflect.Field;",
"class Test{",
" void f(Field f) {",
" // BUG: Diagnostic contains: getDeclaringClass",
" f.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_methodGetClass() {
testHelper
.addSourceLines(
"Test.java",
"import java.lang.reflect.Method;",
"class Test{",
" void f(Method m) {",
" // BUG: Diagnostic contains: getDeclaringClass",
" m.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_beanDescriptorGetClass() {
testHelper
.addSourceLines(
"Test.java",
"import java.beans.BeanDescriptor;",
"class Test{",
" void f(BeanDescriptor b) {",
" // BUG: Diagnostic contains: getBeanClass",
" b.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_lockInfoGetClass() {
testHelper
.addSourceLines(
"Test.java",
"import java.lang.management.LockInfo;",
"import java.lang.management.MonitorInfo;",
"class Test{",
" void f(LockInfo l, MonitorInfo m) {",
" // BUG: Diagnostic contains: getClassName",
" l.getClass();",
" // BUG: Diagnostic contains: getClassName",
" m.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_parameterizedTypeGetClass() {
testHelper
.addSourceLines(
"Test.java",
"import java.lang.reflect.ParameterizedType;",
"class Test{",
" void f(ParameterizedType t) {",
" // BUG: Diagnostic contains: getRawType",
" t.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_classInfoGetClass() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.common.reflect.ClassPath.ClassInfo;",
"class Test{",
" void f(ClassInfo i) {",
" // BUG: Diagnostic contains: getName",
" i.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_typeTokenGetClass() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.common.reflect.TypeToken;",
"class Test{",
" void f(TypeToken<?> t) {",
" // BUG: Diagnostic contains: getRawType",
" t.getClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_threadRun() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f(Thread t) {",
" // BUG: Diagnostic contains: start",
" t.run();",
" }",
"}")
.doTest();
}
@Test
public void negative_threadSuperRun() {
testHelper
.addSourceLines(
"Test.java",
"class Test extends Thread {",
" @Override public void run() {",
" super.run();",
" }",
"}")
.doTest();
}
}
| 23,084
| 30.408163
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ArrayAsKeyOfSetOrMapTest.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;
/**
* {@link ArrayAsKeyOfSetOrMap}Test
*
* @author siyuanl@google.com (Siyuan Liu)
* @author eleanorh@google.com (Eleanor Harris) /
* <p>/** {@link ArrayAsKeyOfSetOrMap}Test
*/
@RunWith(JUnit4.class)
public final class ArrayAsKeyOfSetOrMapTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ArrayAsKeyOfSetOrMap.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Arrays;",
"import java.util.Set;",
"import java.util.Map;",
"import java.util.LinkedHashMap;",
"import java.util.concurrent.ConcurrentHashMap;",
"import com.google.common.collect.Sets;",
"import com.google.common.collect.Maps;",
"import com.google.common.collect.HashMultiset;",
"import com.google.common.collect.LinkedHashMultiset;",
"import com.google.common.collect.HashBiMap;",
"import com.google.common.collect.HashMultimap;",
"import com.google.common.collect.LinkedHashMultimap;",
"import com.google.common.collect.ArrayListMultimap;",
"import com.google.common.collect.LinkedListMultimap;",
"import java.util.HashMap;",
"import java.util.HashSet;",
"class Test{",
" public static void main(String[] args) {",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" Map<String[], Integer> testNewMap = Maps.newHashMap();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" Set<String[]> testNewSet = Sets.newHashSet();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" HashMap<String[], Integer> testNewHashMap = Maps.newHashMap();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" HashSet<String[]> testNewHashSet = Sets.newHashSet();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" Map<String[], Integer> testMap = new HashMap<String[], Integer>();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" Set<String[]> testSet = new HashSet<String[]>();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" HashMap<String[], Integer> testHashMap = new HashMap<String[], Integer>();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" HashSet<String[]> testHashSet = new HashSet<String[]>();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" HashMultimap<String[], Integer> testHashMultimap = HashMultimap.create();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" ArrayListMultimap<String[], Integer> testArrayListMultimap"
+ " = ArrayListMultimap.create();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" LinkedHashMultimap<String[], Integer> testLinkedHashMultimap"
+ "= LinkedHashMultimap.create();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" LinkedListMultimap<String[], Integer> testLinkedListMultimap"
+ "= LinkedListMultimap.create();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" HashBiMap<String[], Integer> testHashBiMap = HashBiMap.create();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" LinkedHashMap<String[], Integer> testLinkedHashMap"
+ "= new LinkedHashMap<String[], Integer>();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" ConcurrentHashMap<String[], Integer> testConcurrentHashMap"
+ "= new ConcurrentHashMap<String[], Integer>();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" HashMultiset<String[]> testHashMultiSet = HashMultiset.create();",
" // BUG: Diagnostic contains: ArrayAsKeyOfSetOrMap",
" LinkedHashMultiset<String[]> testLinkedHashMultiSet"
+ "= LinkedHashMultiset.create();",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Arrays;",
"import java.util.Set;",
"import java.util.Map;",
"import java.util.LinkedHashMap;",
"import java.util.concurrent.ConcurrentHashMap;",
"import com.google.common.collect.Sets;",
"import com.google.common.collect.Maps;",
"import java.util.HashMap;",
"import java.util.HashSet;",
"import java.util.TreeSet;",
"import com.google.common.collect.HashMultiset;",
"import com.google.common.collect.LinkedHashMultiset;",
"import com.google.common.collect.HashBiMap;",
"import com.google.common.collect.HashMultimap;",
"import com.google.common.collect.LinkedHashMultimap;",
"import com.google.common.collect.ArrayListMultimap;",
"import com.google.common.collect.LinkedListMultimap;",
"import com.google.common.collect.Ordering;",
"class Test {",
" public static void main(String[] args) {",
" Map<Integer, Integer> testMap = new HashMap<Integer, Integer>();",
" Set<String> testSet = new HashSet<String>();",
" HashMap<Integer, Integer> testHashMap = new HashMap<Integer, Integer>();",
" HashSet<String> testHashSet = new HashSet<String>();",
" Set testSet2 = new HashSet();",
" Map testMap2 = new HashMap();",
" Map<Integer, Integer> mapFromMethod = Maps.newHashMap();",
" Set<String> setFromMethod = Sets.newHashSet();",
" Set<String[]> thisShouldWork = new TreeSet<String[]>"
+ "(Ordering.natural().lexicographical().onResultOf(Arrays::asList));",
" HashMultimap<String, Integer> testHashMultimap = HashMultimap.create();",
" ArrayListMultimap<String, Integer> testArrayListMultimap"
+ " = ArrayListMultimap.create();",
" LinkedHashMultimap<String, Integer> testLinkedHashMultimap"
+ "= LinkedHashMultimap.create();",
" LinkedListMultimap<String, Integer> testLinkedListMultimap"
+ "= LinkedListMultimap.create();",
" HashBiMap<String, Integer> testHashBiMap = HashBiMap.create();",
" LinkedHashMap<String, Integer> testLinkedHashMap"
+ "= new LinkedHashMap<String, Integer>();",
" ConcurrentHashMap<String, Integer> testConcurrentHashMap"
+ "= new ConcurrentHashMap<String, Integer>();",
" HashMultiset<String> testHashMultiSet = HashMultiset.create();",
" LinkedHashMultiset<String> testLinkedHashMultiSet"
+ "= LinkedHashMultiset.create();",
" }",
"}")
.doTest();
}
}
| 8,111
| 49.7
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AvoidObjectArraysTest.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 AvoidObjectArrays}. */
@RunWith(JUnit4.class)
public class AvoidObjectArraysTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(AvoidObjectArrays.class, getClass());
@Test
public void methodParam_instanceMethods() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"public class ArrayUsage {",
" // BUG: Diagnostic contains: consider an Iterable<Object> instead",
" public void objectArray(Object[] objectArray) {",
" }",
" // BUG: Diagnostic contains: consider an Iterable<String> instead",
" public void stringArray(String[] stringArray) {",
" }",
" public void intArray(int[] intArray) {",
" }",
" public void objectValue(Object objectValue) {",
" }",
" public void stringValue(String stringValue) {",
" }",
" public void intValue(int intValue) {",
" }",
"}")
.doTest();
}
@Test
public void methodParam_staticMethods() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"public class ArrayUsage {",
" // BUG: Diagnostic contains: consider an Iterable<Object> instead",
" public static void objectArray(Object[] objectArray) {",
" }",
" // BUG: Diagnostic contains: consider an Iterable<String> instead",
" public static void stringArray(String[] stringArray) {",
" }",
" public static void intArray(int[] intArray) {",
" }",
" public static void objectValue(Object objectValue) {",
" }",
" public static void stringValue(String stringValue) {",
" }",
" public static void intValue(int intValue) {",
" }",
"}")
.doTest();
}
@Test
public void methodParam_instanceMethods_withIterableOverload() {
compilationHelper
.addSourceLines(
"IterableSubject.java",
"public class IterableSubject {",
" public final void containsAnyIn(Iterable<?> expected) {",
" }",
" public final void containsAnyIn(Object[] expected) {",
" }",
"}")
.doTest();
}
@Test
public void returnType_instanceMethods() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"public class ArrayUsage {",
" // BUG: Diagnostic contains: consider an ImmutableList<Object> instead",
" public Object[] objectArray() {",
" return new String[]{\"a\"};",
" }",
" // BUG: Diagnostic contains: consider an ImmutableList<String> instead",
" public String[] stringArray() {",
" return new String[]{\"a\"};",
" }",
" public int[] intArray() {",
" return new int[]{42};",
" }",
" public Object objectValue() {",
" return \"a\";",
" }",
" public String stringValue() {",
" return \"a\";",
" }",
" public int intValue() {",
" return 42;",
" }",
"}")
.doTest();
}
@Test
public void returnType_staticMethods() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"public class ArrayUsage {",
" // BUG: Diagnostic contains: consider an ImmutableList<Object> instead",
" public static Object[] objectArray() {",
" return new String[]{\"a\"};",
" }",
" // BUG: Diagnostic contains: consider an ImmutableList<String> instead",
" public static String[] stringArray() {",
" return new String[]{\"a\"};",
" }",
" public static int[] intArray() {",
" return new int[]{42};",
" }",
" public static Object objectValue() {",
" return \"a\";",
" }",
" public static String stringValue() {",
" return \"a\";",
" }",
" public static int intValue() {",
" return 42;",
" }",
"}")
.doTest();
}
@Test
public void mainMethod() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"public class ArrayUsage {",
" public static void main(String[] args) {",
" }",
"}")
.doTest();
}
@Test
public void twoDimensionalArrays() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"public class ArrayUsage {",
" // BUG: Diagnostic contains: Avoid returning a String[][]",
" public String[][] returnValue() {",
" return new String[2][2];",
" }",
"}")
.doTest();
}
@Test
public void varArgs() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"public class ArrayUsage {",
" public void varArgs(String... strings) {",
" }",
" // BUG: Diagnostic contains: consider an Iterable<Class> instead",
" public void varArgs(Class[] clazz, String... strings) {",
" }",
"}")
.doTest();
}
@Test
public void annotationMethod() {
compilationHelper
.addSourceLines(
"TestAnnotation.java",
"public @interface TestAnnotation {", //
" String[] value();", //
"}")
.doTest();
}
@Test
public void overridden() {
compilationHelper
.addSourceLines(
"Parent.java",
"public abstract class Parent {",
" // BUG: Diagnostic contains: consider an ImmutableList<String> instead",
" public abstract String[] stringArray();",
"}")
.addSourceLines(
"Child.java",
"public class Child extends Parent {",
" @Override",
// we intentionally don't complain about this API since it's the parent class's fault
" public String[] stringArray() {",
" return new String[]{\"a\"};",
" }",
"}")
.doTest();
}
@Test
public void junitParams() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"import org.junit.runners.Parameterized.Parameters;",
"public class ArrayUsage {",
" @Parameters(name = \"{0}\")",
" public static Object[] locales() {",
" return new Object[] {\"vi\"};",
" }",
"}")
.doTest();
}
@Test
public void stringArrayNamedArgs() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"public class ArrayUsage {",
" // BUG: Diagnostic contains: consider an Iterable<String> instead",
" public static void doSomething1(String[] args) {",
" }",
" // BUG: Diagnostic contains: consider an Iterable<String> instead",
" public static void doSomething2(String[] argv) {",
" }",
" // BUG: Diagnostic contains: consider an Iterable<String> instead",
" public static void doSomething3(String[] argz) {",
" }",
"}")
.doTest();
}
}
| 8,498
| 31.688462
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.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.common.collect.ImmutableList;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.util.RuntimeVersion;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link UnusedVariable}. */
@RunWith(JUnit4.class)
public class UnusedVariableTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(UnusedVariable.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(UnusedVariable.class, getClass());
@Test
public void exemptedByReceiverParameter() {
helper
.addSourceLines(
"ExemptedByReceiverParameter.java",
"package unusedvars;",
"public class ExemptedByReceiverParameter {",
" public void test() {",
" used();",
" }",
" private void used(ExemptedByReceiverParameter this) {",
" // the receiver parameter should not be marked as unused",
" }",
" class Inner {",
" private Inner(ExemptedByReceiverParameter ExemptedByReceiverParameter.this) {",
" // the receiver parameter should not be marked as unused",
" }",
" }",
"}")
.doTest();
}
@Test
public void unicodeBytes() {
helper
.addSourceLines(
"UnicodeBytes.java",
"package unusedvars;",
"/**",
" * This file contains Unicode characters: ❁❁❁❁❁❁❁❁❁",
" */",
"public class UnicodeBytes {",
" public void test() {",
" // BUG: Diagnostic contains: is never read",
" int notUsedLocal;",
" String usedLocal = \"\";",
" System.out.println(usedLocal);",
" }",
"}")
.doTest();
}
@Test
public void unusedArray() {
helper
.addSourceLines(
"UnusedArray.java",
"package unusedvars;",
"public class UnusedArray {",
" private int[] ints;",
" public void test() {",
" ints[0] = 0;",
" ints[0]++;",
" ints[0]--;",
" ints[0] -= 0;",
" }",
"}")
.doTest();
}
@Test
public void unusedEnhancedForLoop() {
refactoringHelper
.addInputLines(
"UnusedEnhancedForLoop.java",
"package unusedvars;",
"import java.util.ArrayList;",
"import java.util.List;",
"class UnusedEnhancedForLoop {",
" public List<String> makeList(List<String> input) {",
" List<String> output = new ArrayList<>();",
" for (final String firstVar : input) {",
" output.add(\"a string\");",
" }",
" return output;",
" }",
" public List<String> listData(List<List<String>> input) {",
" List<String> output = new ArrayList<>();",
" for (List<String> secondVar : input) {",
" output.add(\"a string\");",
" }",
" return output;",
" }",
"}")
.addOutputLines(
"UnusedEnhancedForLoop.java",
"package unusedvars;",
"import java.util.ArrayList;",
"import java.util.List;",
"class UnusedEnhancedForLoop {",
" public List<String> makeList(List<String> input) {",
" List<String> output = new ArrayList<>();",
" for (final String unused : input) {",
" output.add(\"a string\");",
" }",
" return output;",
" }",
" public List<String> listData(List<List<String>> input) {",
" List<String> output = new ArrayList<>();",
" for (List<String> unused : input) {",
" output.add(\"a string\");",
" }",
" return output;",
" }",
"}")
.doTest();
}
@Test
public void unusedField() {
helper
.addSourceLines(
"UnusedField.java",
"package unusedvars;",
"import java.util.ArrayList;",
"import java.util.List;",
"public class UnusedField {",
" // BUG: Diagnostic contains: is never read",
" private int notUsedInt;",
" // BUG: Diagnostic contains: is never read",
" private List<String> list = new ArrayList<>();",
" public void test() {",
" notUsedInt = 0;",
" if (hashCode() > 0) {",
" list = null;",
" } else {",
" list = makeList();",
" }",
" }",
" private List<String> makeList() {",
" return null;",
" }",
" public UnusedField(List<String> list) {",
" this.list = list;",
" }",
" // These fields are special, and should not be flagged as unused.",
" private static final long serialVersionUID = 0;",
" private static final String TAG = \"UnusedFieldTestThingy\";",
" @SuppressWarnings(\"unchecked\")",
" // BUG: Diagnostic contains: is never read",
" private long fieldWithAnn;",
"}")
.doTest();
}
@Test
public void unusedLocalVarInitialized() {
helper
.addSourceLines(
"UnusedLocalVarInitialized.java",
"package unusedvars;",
"public class UnusedLocalVarInitialized {",
" public void test() {",
" String s = \"\";",
" System.out.println(s);",
" // BUG: Diagnostic contains: is never read",
" int notUsed = UnusedLocalVarInitialized.setData();",
" notUsed = this.hashCode();",
" }",
" public static int setData() {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void unusedLocalVar() {
helper
.addSourceLines(
"UnusedLocalVar.java",
"package unusedvars;",
"public class UnusedLocalVar {",
" public void test() {",
" // BUG: Diagnostic contains: is never read",
" int notUsedLocal;",
" notUsedLocal = 0;",
" String usedLocal = \"\";",
" if (usedLocal.length() == 0) {",
" notUsedLocal = 10 + usedLocal.length();",
" } else {",
" notUsedLocal = this.calculate()",
" + 1 ;",
" notUsedLocal--;",
" notUsedLocal += Integer.valueOf(1);",
" System.out.println(usedLocal);",
" }",
" System.out.println(usedLocal);",
" }",
" int calculate() {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void unusedNative() {
helper
.addSourceLines(
"UnusedNative.java",
"package unusedvars;",
"public class UnusedNative {",
" private int usedInNative1 = 0;",
" private String usedInNative2 = \"\";",
" private native void aNativeMethod();",
"}")
.doTest();
}
@Test
public void unusedParamInPrivateMethod() {
helper
.addSourceLines(
"UnusedParamInPrivateMethod.java",
"package unusedvars;",
"public class UnusedParamInPrivateMethod {",
" // BUG: Diagnostic contains: 'j' is never read",
" private void test(int i, int j) {",
" System.out.println(i);",
" }",
" public void main() {",
" test(1, 2);",
" }",
"}")
.doTest();
}
@Test
public void unuseds() {
helper
.addSourceLines(
"Unuseds.java",
"package unusedvars;",
"import java.io.IOException;",
"import java.io.ObjectStreamException;",
"import java.util.List;",
"import javax.inject.Inject;",
"public class Unuseds {",
" // BUG: Diagnostic contains:",
" private static final String NOT_USED_CONST_STR = \"unused_test\";",
" private static final String CONST_STR = \"test\";",
" // BUG: Diagnostic contains:",
" private int notUsed;",
" private List<String> used;",
" public int publicOne;",
" private int[] ints;",
" @Inject",
" private int unusedExemptedByAnnotation;",
" @Inject",
" private void unusedMethodExemptedByAnnotation() {}",
" void test() {",
" this.notUsed = 0;",
" this.notUsed++;",
" this.notUsed += 0;",
" // BUG: Diagnostic contains:",
" int notUsedLocal;",
" notUsedLocal = 10;",
" int usedLocal = 0;",
" if (!used.get(usedLocal).toString().equals(CONST_STR)) {",
" used.add(\"test\");",
" }",
" // j is used",
" int j = 0;",
" used.get(j++);",
" ints[j--]++;",
" ints[1] = 0;",
" // Negative case (:( data flow analysis...).",
" byte[] notUsedLocalArray = new byte[]{};",
" notUsedLocalArray[0] += this.used.size();",
" char[] out = new char[]{};",
" for (int m = 0, n = 0; m < 1; m++) {",
" out[n++] = out[m];",
" }",
" // Negative case",
" double timestamp = 0.0;",
" set(timestamp += 1.0);",
" int valuesIndex1 = 0;",
" int valuesIndex2 = 0;",
" double[][][] values = null;",
" values[0][valuesIndex1][valuesIndex2] = 10;",
" System.out.println(values);",
" }",
" public void set(double d) {}",
" public void usedInMethodCall(double d) {",
" List<Unuseds> notUseds = null;",
" int indexInMethodCall = 0;",
" // Must not be reported as unused",
" notUseds.get(indexInMethodCall).publicOne = 0;",
" }",
" void memberSelectUpdate1() {",
" List<Unuseds> l = null;",
" // `u` should not be reported as unused.",
" Unuseds u = getFirst(l);",
" u.notUsed = 10;",
" System.out.println(l);",
" getFirst(l).notUsed = 100;",
" }",
" void memberSelectUpdate2() {",
" List<Unuseds> l = null;",
" // `l` should not be reported as unused.",
" l.get(0).notUsed = 10;",
" }",
" Unuseds getFirst(List<Unuseds> l) {",
" return l.get(0);",
" }",
" // Negative case. Must not report.",
" private int usedCount = 0;",
" int incCounter() {",
" return usedCount += 2;",
" }",
" // For testing the lack of NPE on return statement.",
" public void returnNothing() {",
" return;",
" }",
" // Negative case. Must not report.",
" public void testUsedArray() {",
" ints[0] = 0;",
" ints[0]++;",
" ints[0]--;",
" ints[0] -= 0;",
" }",
" @SuppressWarnings({\"deprecation\", \"unused\"})",
" class UsesSuppressWarning {",
" private int f1;",
" private void test1() {",
" int local;",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactoring() {
refactoringHelper
.addInputLines(
"Unuseds.java",
"package unusedvars;",
"public class Unuseds {",
" private static final String NOT_USED_CONST_STR = \"unused_test\";",
" private static final String CONST_STR = \"test\";",
" private int notUsed;",
" public int publicOne;",
" void test() {",
" this.notUsed = 0;",
" this.notUsed++;",
" this.notUsed += 0;",
" int notUsedLocal;",
" notUsedLocal = 10;",
" System.out.println(CONST_STR);",
" }",
"}")
.addOutputLines(
"Unuseds.java",
"package unusedvars;",
"public class Unuseds {",
" private static final String CONST_STR = \"test\";",
" public int publicOne;",
" void test() {",
" System.out.println(CONST_STR);",
" }",
"}")
.doTest();
}
@Test
public void overridableMethods() {
helper
.addSourceLines(
"Unuseds.java",
"package unusedvars;",
"public class Unuseds {",
" // BUG: Diagnostic contains: The parameter 'j' is never read",
" private int usedPrivateMethodWithUnusedParam(int i, int j) {",
" return i * 2;",
" }",
" int a = usedPrivateMethodWithUnusedParam(1, 2);",
" // In the following three cases, parameters should not be reported as unused,",
" // because methods are non-private.",
" public void publicMethodWithUnusedParam(int i, int j) {}",
" public void protectedMethodWithUnusedParam(int i, int j) {}",
" public void packageMethodWithUnusedParam(int i, int j) {}",
"}")
.doTest();
}
@Test
public void exemptedByName() {
helper
.addSourceLines(
"Unuseds.java",
"package unusedvars;",
"class ExemptedByName {",
" private int unused;",
" private int unusedInt;",
" private static final int UNUSED_CONSTANT = 5;",
" private int ignored;",
"}")
.doTest();
}
@Test
public void suppressions() {
helper
.addSourceLines(
"Unuseds.java",
"package unusedvars;",
"class Suppressed {",
" @SuppressWarnings({\"deprecation\", \"unused\"})",
" class UsesSuppressWarning {",
" private int f1;",
" private void test1() {",
" int local;",
" }",
" @SuppressWarnings(value = \"unused\")",
" private void test2() {",
" int local;",
" }",
" }",
"}")
.doTest();
}
@Test
public void unusedStaticField() {
helper
.addSourceLines(
"UnusedStaticField.java",
"package unusedvars;",
"import java.util.ArrayList;",
"import java.util.List;",
"public class UnusedStaticField {",
" // BUG: Diagnostic contains: is never read",
" private static final List<String> DATA = new ArrayList<>();",
"}")
.doTest();
}
@Test
public void unusedStaticPrivate() {
helper
.addSourceLines(
"UnusedStaticPrivate.java",
"package unusedvars;",
"public class UnusedStaticPrivate {",
" // BUG: Diagnostic contains: is never read",
" private static final String NOT_USED_CONST_STR = \"unused_test\";",
" static final String CONST_STR = \"test\";",
"}")
.doTest();
}
@Test
public void unusedTryResource() {
helper
.addSourceLines(
"UnusedTryResource.java",
"package unusedvars;",
"public class UnusedTryResource {",
" public static void main(String[] args) {",
" try (A a = new A()) {",
" }",
" }",
"}",
"class A implements AutoCloseable {",
" public void close() {}",
"}")
.doTest();
}
@Test
public void removal_javadocsAndNonJavadocs() {
refactoringHelper
.addInputLines(
"UnusedWithComment.java",
"package unusedvars;",
"public class UnusedWithComment {",
" /**",
" * Comment for a field */",
" @SuppressWarnings(\"test\")",
" private Object field;",
"}")
.addOutputLines(
"UnusedWithComment.java", //
"package unusedvars;",
"public class UnusedWithComment {",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void removal_trailingComment() {
refactoringHelper
.addInputLines(
"Test.java",
"public class Test {",
" public static final int A = 1; // foo",
"",
" private static final int B = 2;",
"}")
.addOutputLines(
"Test.java", //
"public class Test {",
" public static final int A = 1; // foo",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void removal_javadocAndSingleLines() {
refactoringHelper
.addInputLines(
"Test.java",
"public class Test {",
" public static final int A = 1; // foo",
"",
" /** Javadoc. */",
" // TODO: fix",
" // BUG: bug",
" private static final int B = 2;",
"}")
.addOutputLines(
"Test.java", //
"public class Test {",
" public static final int A = 1; // foo",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void removal_rogueBraces() {
refactoringHelper
.addInputLines(
"Test.java",
"@SuppressWarnings(\"foo\" /* { */)",
"public class Test {",
" private static final int A = 1;",
"}")
.addOutputLines(
"Test.java", //
"@SuppressWarnings(\"foo\" /* { */)",
"public class Test {",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void unusedWithComment_interspersedComments() {
helper
.addSourceLines(
"UnusedWithComment.java",
"package unusedvars;",
"public class UnusedWithComment {",
" private static final String foo = null, // foo",
" // BUG: Diagnostic contains:",
" bar = null;",
" public static String foo() { return foo; }",
"}")
.doTest();
}
@Test
public void usedInLambda() {
helper
.addSourceLines(
"UsedInLambda.java",
"package unusedvars;",
"import java.util.Arrays;",
"import java.util.List;",
"import java.util.function.Function;",
"import java.util.stream.Collectors;",
"/** Method parameters used in lambdas and anonymous classes */",
"public class UsedInLambda {",
" private Function<Integer, Integer> usedInLambda() {",
" return x -> 1;",
" }",
" private String print(Object o) {",
" return o.toString();",
" }",
" public List<String> print(List<Object> os) {",
" return os.stream().map(this::print).collect(Collectors.toList());",
" }",
" public static void main(String[] args) {",
" System.err.println(new UsedInLambda().usedInLambda());",
" System.err.println(new UsedInLambda().print(Arrays.asList(1, 2, 3)));",
" }",
"}")
.doTest();
}
@Test
public void utf8Handling() {
helper
.addSourceLines(
"Utf8Handling.java",
"package unusedvars;",
"public class Utf8Handling {",
" private int foo = 1;",
" public void test() {",
" System.out.println(\"広\");",
" for (int i = 0; i < 10; ++i) {",
" // BUG: Diagnostic contains: is never read",
" int notUsedLocal = calculate();",
" }",
" System.out.println(foo);",
" }",
" int calculate() {",
" return ++foo;",
" }",
"}")
.doTest();
}
@Test
public void methodAnnotationsExemptingParameters() {
helper
.addSourceLines(
"A.java",
"package unusedvars;",
"class A {",
" { foo(1); }",
" @B",
" private static void foo(int a) {}",
"}",
"@interface B {}")
.setArgs(
ImmutableList.of("-XepOpt:Unused:methodAnnotationsExemptingParameters=unusedvars.B"))
.doTest();
}
@Test
public void usedUnaryExpression() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"import java.util.Map;",
"import java.util.HashMap;",
"public class Test {",
" private int next = 1;",
" private Map<String, Integer> xs = new HashMap<>();",
" public int frobnicate(String s) {",
" Integer x = xs.get(s);",
" if (x == null) {",
" x = next++;",
" xs.put(s, x);",
" }",
" return x;",
" }",
"}")
.doTest();
}
@Test
public void unusedInject() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"import javax.inject.Inject;",
"public class Test {",
// Package-private @Inject fields are assumed to be only used within the class, and only
// visible for performance.
" // BUG: Diagnostic contains:",
" @Inject Object foo;",
" @Inject public Object bar;",
"}")
.setArgs(ImmutableList.of("-XepOpt:Unused:ReportInjectedFields"))
.doTest();
}
@Test
public void unusedInjectConstructorParameter() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"import javax.inject.Inject;",
"public class Test {",
" @Inject Test(",
" // BUG: Diagnostic contains:",
" String foo) {}",
"}")
.doTest();
}
@Test
public void unusedInject_notByDefault() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"import javax.inject.Inject;",
"public class Test {",
" @Inject Object foo;",
" @Inject public Object bar;",
"}")
.doTest();
}
@Test
public void variableKeepingSideEffects() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" private final ImmutableList<Integer> foo = ImmutableList.of();",
" void test() {",
" ImmutableList<Integer> foo = ImmutableList.of();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" { ImmutableList.of(); }",
" void test() {",
" ImmutableList.of();",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void variableRemovingSideEffects() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" private final ImmutableList<Integer> foo = ImmutableList.of();",
" void test() {",
" ImmutableList<Integer> foo = ImmutableList.of();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" void test() {",
" }",
"}")
.doTest();
}
@Test
public void exemptedFieldsByType() {
helper
.addSourceLines(
"Test.java",
"import org.junit.rules.TestRule;",
"class Test {",
" private TestRule rule;",
"}")
.doTest();
}
@Test
public void findingBaseSymbol() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" int a;",
" void test() {",
" Test o = new Test();",
" ((Test) o).a = 1;",
" (((o))).a = 1;",
" Test p = new Test();",
" id(p).a = 1;",
" }",
" Test id(Test t) { return t; }",
"}")
.doTest();
}
@Test
public void fixPrivateMethod_usagesToo() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" int a = foo(1);",
" private int foo(int b) {",
" b = 1;",
" return 1;",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int a = foo();",
" private int foo() {",
" return 1;",
" }",
"}")
.doTest();
}
@Test
public void fixPrivateMethod_parameterLocations() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" int a = foo(1, 2, 3) + bar(1, 2, 3) + baz(1, 2, 3);",
" private int foo(int a, int b, int c) { return a * b; }",
" private int bar(int a, int b, int c) { return b * c; }",
" private int baz(int a, int b, int c) { return a * c; }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int a = foo(1, 2) + bar(2, 3) + baz(1, 3);",
" private int foo(int a, int b) { return a * b; }",
" private int bar(int b, int c) { return b * c; }",
" private int baz(int a, int c) { return a * c; }",
"}")
.doTest();
}
@Test
public void fixPrivateMethod_varArgs() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" int a = foo(1, 2, 3, 4);",
" private int foo(int a, int... b) { return a; }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int a = foo(1);",
" private int foo(int a) { return a; }",
"}")
.doTest();
}
@Test
public void fixPrivateMethod_varArgs_noArgs() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" int a = foo(1);",
" private int foo(int a, int... b) { return a; }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" int a = foo(1);",
" private int foo(int a) { return a; }",
"}")
.doTest();
}
@Ignore("b/118437729")
@Test
public void enumField() {
refactoringHelper
.addInputLines(
"Test.java", //
"enum Test {",
" ONE(\"1\", 1) {};",
" private String a;",
" private Test(String a, int x) {",
" this.a = a;",
" }",
" String a() {",
" return a;",
" }",
"}")
.addOutputLines(
"Test.java", //
"enum Test {",
" ONE(\"1\") {};",
" private String a;",
" private Test(String a) {",
" this.a = a;",
" }",
" String a() {",
" return a;",
" }",
"}")
.doTest();
}
@Ignore("b/118437729")
@Test
public void onlyEnumField() {
refactoringHelper
.addInputLines(
"Test.java", //
"enum Test {",
" ONE(1) {};",
" private Test(int x) {",
" }",
"}")
.addOutputLines(
"Test.java", //
"enum Test {",
" ONE() {};",
" private Test() {",
" }",
"}")
.doTest();
}
@Test
public void sideEffectFix() {
refactoringHelper
.addInputLines(
"Test.java", //
"class Test {",
" private static final int[] xs = new int[0];",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
"}")
.doTest();
}
@Test
public void sideEffectFieldFix() {
refactoringHelper
.addInputLines(
"Test.java", //
"class Test {",
" private int x = 1;",
" public int a() {",
" x = a();",
" return 1;",
" }",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
" public int a() {",
" a();",
" return 1;",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void blockFixTest() {
refactoringHelper
.addInputLines(
"Test.java", //
"class Test {",
" void foo() {",
" int a = 1;",
" if (hashCode() > 0)",
" a = 2;",
" }",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
" void foo() {",
" if (hashCode() > 0) {}",
" }",
"}")
.doTest();
}
@Test
public void unusedAssignment() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test() {",
" Integer a = 1;",
" a.hashCode();",
" // BUG: Diagnostic contains: assignment to",
" a = 2;",
" }",
"}")
.doTest();
}
@Test
public void unusedAssignment_messages() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public int test() {",
" // BUG: Diagnostic contains: This assignment to the local variable",
" int a = 1;",
" a = 2;",
" int b = a;",
" int c = b;",
" // BUG: Diagnostic contains: This assignment to the local variable",
" b = 2;",
" b = 3;",
" return b + c;",
" }",
"}")
.doTest();
}
@Test
public void unusedAssignment_nulledOut_noWarning() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test() {",
" Integer a = 1;",
" a.hashCode();",
" a = null;",
" }",
"}")
.doTest();
}
@Test
public void unusedAssignment_nulledOut_thenAssignedAgain() {
refactoringHelper
.addInputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test() {",
" Integer a = 1;",
" a.hashCode();",
" a = null;",
" a = 2;",
" }",
"}")
.addOutputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test() {",
" Integer a = 1;",
" a.hashCode();",
" a = null;",
" }",
"}")
.doTest();
}
@Test
public void unusedAssignment_initialAssignmentNull_givesWarning() {
refactoringHelper
.addInputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public String test() {",
" String a = null;",
" hashCode();",
" a = toString();",
" return a;",
" }",
"}")
.addOutputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public String test() {",
" hashCode();",
" String a = toString();",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void unusedAssignmentAfterUse() {
refactoringHelper
.addInputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test() {",
" int a = 1;",
" System.out.println(a);",
" a = 2;",
" }",
"}")
.addOutputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test() {",
" int a = 1;",
" System.out.println(a);",
" }",
"}")
.doTest();
}
@Test
public void unusedAssignmentWithFinalUse() {
refactoringHelper
.addInputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test() {",
" int a = 1;",
" a = 2;",
" a = 3;",
" System.out.println(a);",
" }",
"}")
.addOutputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test() {",
" int a = 3;",
" System.out.println(a);",
" }",
"}")
.doTest();
}
@Test
public void assignmentUsedInExpression() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public int test() {",
" int a = 1;",
" a = a * 2;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void assignmentToParameter() {
refactoringHelper
.addInputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test(int a) {",
" a = 2;",
" }",
"}")
.addOutputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test(int a) {",
" }",
"}")
.doTest();
}
@Test
public void assignmentToParameter_thenUsed() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public int test(int a) {",
" a = 2;",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void assignmentToEnhancedForLoop() {
refactoringHelper
.addInputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test(Iterable<Integer> as) {",
" for (int a : as) {",
" System.out.println(a);",
" a = 2;",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test(Iterable<Integer> as) {",
" for (int a : as) {",
" System.out.println(a);",
" }",
" }",
"}")
.doTest();
}
@Test
public void assignmentWithinForLoop() {
helper
.addSourceLines(
"Test.java",
"public class Test {",
" public void test() {",
" for (int a = 0; a < 10; a = a + 1) {}",
" }",
"}")
.doTest();
}
@Test
public void assignmentSeparateFromDeclaration_noComplaint() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public void test() {",
" int a;",
" a = 1;",
" System.out.println(a);",
" }",
"}")
.doTest();
}
@Test
public void unusedAssignment_negatives() {
helper
.addSourceLines(
"Test.java",
"package unusedvars;",
"public class Test {",
" public int frobnicate() {",
" int a = 1;",
" if (hashCode() == 0) {",
" a = 2;",
" }",
" return a;",
" }",
"}")
.doTest();
}
@Test
public void exemptedMethods() {
helper
.addSourceLines(
"Unuseds.java",
"package unusedvars;",
"import java.io.IOException;",
"import java.io.ObjectStreamException;",
"public class Unuseds implements java.io.Serializable {",
" private void readObject(java.io.ObjectInputStream in) throws IOException {}",
" private void writeObject(java.io.ObjectOutputStream out) throws IOException {}",
" private Object readResolve() {",
" return null;",
" }",
" private void readObjectNoData() throws ObjectStreamException {}",
"}")
.doTest();
}
@Test
public void unusedReassignment_removeSideEffectsFix() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.Collection;",
"import java.util.List;",
"import static java.util.stream.Collectors.toList;",
"public class Test {",
" public void f(List<List<String>> lists) {",
" List<String> result =",
" lists.stream().collect(ArrayList::new, Collection::addAll,"
+ " Collection::addAll);",
" result = lists.stream().collect(ArrayList::new, ArrayList::addAll,"
+ " ArrayList::addAll);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.Collection;",
"import java.util.List;",
"import static java.util.stream.Collectors.toList;",
"public class Test {",
" public void f(List<List<String>> lists) {",
" }",
"}")
.setFixChooser(FixChoosers.FIRST)
.doTest();
}
@Test
public void unusedReassignment_keepSideEffectsFix() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.Collection;",
"import java.util.List;",
"import static java.util.stream.Collectors.toList;",
"public class Test {",
" public void f(List<List<String>> lists) {",
" List<String> result =",
" lists.stream().collect(ArrayList::new, Collection::addAll,"
+ " Collection::addAll);",
" result = lists.stream().collect(ArrayList::new, ArrayList::addAll,"
+ " ArrayList::addAll);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.Collection;",
"import java.util.List;",
"import static java.util.stream.Collectors.toList;",
"public class Test {",
" public void f(List<List<String>> lists) {",
" lists.stream().collect(ArrayList::new, Collection::addAll, Collection::addAll);",
" lists.stream().collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll);",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void simpleRecord() {
assumeTrue(RuntimeVersion.isAtLeast16());
helper
.addSourceLines(
"SimpleRecord.java", //
"public record SimpleRecord (Integer foo, Long bar) {}")
.expectNoDiagnostics()
.doTest();
}
@Test
public void nestedRecord() {
assumeTrue(RuntimeVersion.isAtLeast16());
helper
.addSourceLines(
"SimpleClass.java",
"public class SimpleClass {",
" public record SimpleRecord (Integer foo, Long bar) {}",
"}")
.expectNoDiagnostics()
.doTest();
}
@Test
public void unusedInRecord() {
assumeTrue(RuntimeVersion.isAtLeast16());
helper
.addSourceLines(
"SimpleClass.java",
"public class SimpleClass {",
" public record SimpleRecord (Integer foo, Long bar) {",
" void f() {",
" // BUG: Diagnostic contains: is never read",
" int x = foo;",
" }",
" }",
"}")
.doTest();
}
@Test
public void manyUnusedAssignments_terminalAssignmentBecomesVariable() {
refactoringHelper
.addInputLines(
"Test.java",
"public class Test {",
" public void test () {",
" Integer a = 1;",
" a = 2;",
" a = 3;",
" a.hashCode();",
" }",
"}")
.addOutputLines(
"Test.java",
"public class Test {",
" public void test () {",
" Integer a = 3;",
" a.hashCode();",
" }",
"}")
.doTest();
}
@Test
public void unusedVariable_withinPrivateInnerClass() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private class Inner {",
" // BUG: Diagnostic contains:",
" public int foo = 1;",
" }",
"}")
.doTest();
}
@Test
public void parcelableCreator_noFinding() {
helper
.addSourceFile("android/testdata/stubs/android/os/Parcel.java")
.addSourceFile("android/testdata/stubs/android/os/Parcelable.java")
.addSourceLines(
"Test.java",
"import android.os.Parcelable;",
"class Test {",
" private static final Parcelable.Creator<Test> CREATOR = null;",
"}")
.doTest();
}
}
| 44,966
| 29.465447
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CacheLoaderNullTest.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;
/** {@link CacheLoaderNull}Test */
@RunWith(JUnit4.class)
public class CacheLoaderNullTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(CacheLoaderNull.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.cache.CacheLoader;",
"class Test {",
" {",
" new CacheLoader<String, String>() {",
" @Override",
" public String load(String key) {",
" // BUG: Diagnostic contains:",
" return null;",
" }",
" };",
" abstract class MyCacheLoader extends CacheLoader<String, String> {}",
" new MyCacheLoader() {",
" @Override",
" public String load(String key) {",
" // BUG: Diagnostic contains:",
" return null;",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.cache.CacheLoader;",
"import java.util.function.Supplier;",
"class Test {",
" public String load(String key) {",
" return null;",
" }",
" {",
" new CacheLoader<String, String>() {",
" @Override",
" public String load(String key) {",
" Supplier<String> s = () -> { return null; };",
" Supplier<String> t = new Supplier<String>() {",
" public String get() {",
" return null;",
" }",
" };",
" class MySupplier implements Supplier<String> {",
" public String get() {",
" return null;",
" }",
" };",
" return \"\";",
" }",
" };",
" }",
"}")
.doTest();
}
}
| 3,050
| 31.806452
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ConstantFieldTest.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.BugCheckerRefactoringTestHelper.FixChoosers;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ConstantField}Test */
@RunWith(JUnit4.class)
public class ConstantFieldTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ConstantField.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: static final Object CONSTANT1 = 42;",
" Object CONSTANT1 = 42;",
" // BUG: Diagnostic contains: @Deprecated static final Object CONSTANT2 = 42;",
" @Deprecated Object CONSTANT2 = 42;",
" // BUG: Diagnostic contains: static final Object CONSTANT3 = 42;",
" static Object CONSTANT3 = 42;",
" // BUG: Diagnostic contains: static final Object CONSTANT4 = 42;",
" final Object CONSTANT4 = 42;",
" // BUG: Diagnostic contains:"
+ " @Deprecated private static final Object CONSTANT5 = 42;",
" @Deprecated private Object CONSTANT5 = 42;",
"}")
.doTest();
}
@Test
public void rename() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: 'Object constantCaseName = 42;'",
" Object CONSTANT_CASE_NAME = 42;",
"}")
.doTest();
}
@Test
public void skipStaticFixOnInners() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" class Inner {",
" // BUG: Diagnostic matches: F",
" final String CONSTANT_CASE_NAME = \"a\";",
" }",
" enum InnerEnum {",
" FOO {",
" // BUG: Diagnostic matches: F",
" final String CONSTANT_CASE_NAME = \"a\";",
" };",
" // BUG: Diagnostic contains: static final String CAN_MAKE_STATIC",
" final String CAN_MAKE_STATIC = \"\";",
" }",
"}")
.expectErrorMessage(
"F", d -> !d.contains("static final String") && d.contains("ConstantField"))
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" static final Object CONSTANT = 42;",
" Object nonConst = 42;",
" public static final Object FLAG_foo = new Object();",
" protected static final int FOO_BAR = 100;",
" static final int FOO_BAR2 = 100;",
" private static final int[] intArray = {0};",
" private static final Object mutable = new Object();",
"}")
.doTest();
}
@Test
public void renameUsages() {
BugCheckerRefactoringTestHelper.newInstance(ConstantField.class, getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" Object CONSTANT_CASE = 42;",
" void f() {",
" System.err.println(CONSTANT_CASE);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" Object constantCase = 42;",
" void f() {",
" System.err.println(constantCase);",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void primitivesAreConstant_negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" static final int CONSTANT = 42;",
" static final Integer BOXED_CONSTANT = 42;",
" static final String STRING_CONSTANT = \"\";",
"}")
.doTest();
}
@Test
public void primitivesAreConstant_serializable() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.io.ObjectStreamField;",
"import java.io.Serializable;",
"class Test implements Serializable {",
" private static final long serialVersionUID = 1L;",
" private static final ObjectStreamField[] serialPersistentFields = {};",
"}")
.doTest();
}
}
| 5,236
| 32.570513
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ConditionalExpressionNumericPromotionTest.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 ConditionalExpressionNumericPromotion}Test */
@RunWith(JUnit4.class)
public class ConditionalExpressionNumericPromotionTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(
ConditionalExpressionNumericPromotion.class, getClass());
@Test
public void positive() {
testHelper
.addInputLines(
"in/Test.java",
"import java.io.Serializable;",
"class Test {",
" Object returnObject(boolean b) {",
" return b ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" Number returnNumber(boolean b) {",
" // Extra parentheses, just for fun.",
" return (b ? Integer.valueOf(0) : Long.valueOf(0));",
" }",
" Serializable returnSerializable(boolean b) {",
" return b ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" void assignObject(boolean b, Object obj) {",
" obj = b ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" void assignNumber(boolean b, Number obj) {",
" obj = b ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" void variableObject(boolean b) {",
" Object obj = b ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" void variableNumber(boolean b) {",
" Number obj = b ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" void invokeMethod(boolean b, Number n) {",
" invokeMethod(b, b ? Integer.valueOf(0) : Long.valueOf(0));",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.io.Serializable;",
"class Test {",
" Object returnObject(boolean b) {",
" return b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0));",
" }",
" Number returnNumber(boolean b) {",
" // Extra parentheses, just for fun.",
" return (b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0)));",
" }",
" Serializable returnSerializable(boolean b) {",
" return b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0));",
" }",
" void assignObject(boolean b, Object obj) {",
" obj = b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0));",
" }",
" void assignNumber(boolean b, Number obj) {",
" obj = b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0));",
" }",
" void variableObject(boolean b) {",
" Object obj = b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0));",
" }",
" void variableNumber(boolean b) {",
" Number obj = b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0));",
" }",
" void invokeMethod(boolean b, Number n) {",
" invokeMethod(b, b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0)));",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" Long returnLong(boolean b) {",
" // OK, because the return type is the correct type.",
" return false ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" void assignLong(boolean b, Long obj) {",
" obj = b ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" void variableLong(boolean b) {",
" Long obj = b ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" void variablePrimitive(boolean b) {",
" long obj = b ? Integer.valueOf(0) : Long.valueOf(0);",
" }",
" void invokeMethod(boolean b, Long n) {",
" invokeMethod(b, b ? Integer.valueOf(0) : Long.valueOf(0));",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| 5,066
| 39.536
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TearDownNotRunTest.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 glorioso@google.com (Nick Glorioso)
*/
@RunWith(JUnit4.class)
public class JUnit4TearDownNotRunTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JUnit4TearDownNotRun.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("JUnit4TearDownNotRunPositiveCases.java").doTest();
}
@Test
public void positiveCase_customAnnotation() {
compilationHelper.addSourceFile("JUnit4TearDownNotRunPositiveCaseCustomAfter.java").doTest();
}
@Test
public void positiveCase_customAnnotationDifferentName() {
compilationHelper.addSourceFile("JUnit4TearDownNotRunPositiveCaseCustomAfter2.java").doTest();
}
@Test
public void negativeCases() {
compilationHelper.addSourceFile("JUnit4TearDownNotRunNegativeCases.java").doTest();
}
}
| 1,653
| 30.207547
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DangerousLiteralNullCheckerTest.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 DangerousLiteralNullChecker}. */
@RunWith(JUnit4.class)
public class DangerousLiteralNullCheckerTest {
private CompilationTestHelper helper =
CompilationTestHelper.newInstance(DangerousLiteralNullChecker.class, getClass());
@Test
public void javaUtilOptional() {
helper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"",
"class Test {",
" void bad(Optional<Object> o) {",
" // BUG: Diagnostic contains: o.orElse(null)",
" o.orElseGet(null);",
" // BUG: Diagnostic contains: o.orElseThrow(NullPointerException::new)",
" o.orElseThrow(null);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
helper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"",
"class Test {",
" void fine(Optional<Object> o) {",
" o.orElseGet(() -> null);", // lame, but behaves as expected so we let it slide
" o.orElseThrow(() -> new RuntimeException());",
" }",
"}")
.doTest();
}
}
| 2,029
| 30.71875
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ThrowSpecificExceptionsTest.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 ThrowSpecificExceptions}. */
@RunWith(JUnit4.class)
public final class ThrowSpecificExceptionsTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(ThrowSpecificExceptions.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(ThrowSpecificExceptions.class, getClass());
@Test
public void positive() {
helper
.addSourceLines(
"Test.java",
"public class Test {",
" void test() {",
" // BUG: Diagnostic contains: new VerifyException",
" throw new RuntimeException();",
" }",
"}")
.doTest();
}
@Test
public void refactoring() {
refactoringHelper
.addInputLines(
"Test.java",
"public class Test {",
" void test() {",
" throw new RuntimeException();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.VerifyException;",
"public class Test {",
" void test() {",
" throw new VerifyException();",
" }",
"}")
.doTest();
}
@Test
public void anonymousClass() {
helper
.addSourceLines(
"Test.java",
"public class Test {",
" void test() {",
" throw new RuntimeException() {};",
" }",
"}")
.doTest();
}
@Test
public void negative() {
helper
.addSourceLines(
"Test.java",
"public class Test {",
" void test() {",
" throw new IllegalStateException();",
" }",
"}")
.doTest();
}
@Test
public void dontMatchIfNotThrown() {
helper
.addSourceLines(
"Test.java",
"public class Test {",
" StackTraceElement[] getStackTrace() {",
" return new Throwable().getStackTrace();",
" }",
"}")
.doTest();
}
}
| 3,032
| 27.345794
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EqualsUsingHashCodeTest.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 EqualsUsingHashCode} bugpattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class EqualsUsingHashCodeTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(EqualsUsingHashCode.class, getClass());
@Test
public void negative() {
helper
.addSourceLines(
"Test.java",
"import com.google.common.base.Objects;",
"class Test {",
" private int a;",
" @Override public boolean equals(Object o) {",
" Test that = (Test) o;",
" return o.hashCode() == hashCode() && a == that.a;",
" }",
"}")
.doTest();
}
@Test
public void positive() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int a;",
" private int b;",
" @Override public boolean equals(Object o) {",
" // BUG: Diagnostic contains:",
" return o.hashCode() == hashCode();",
" }",
"}")
.doTest();
}
@Test
public void positiveBinary() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" private int a;",
" private int b;",
" @Override public boolean equals(Object o) {",
" // BUG: Diagnostic contains:",
" return o instanceof Test && o.hashCode() == hashCode();",
" }",
"}")
.doTest();
}
}
| 2,388
| 28.134146
| 79
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BigDecimalEqualsTest.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 BigDecimalEquals}.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class BigDecimalEqualsTest {
@Test
public void positive() {
CompilationTestHelper.newInstance(BigDecimalEquals.class, getClass())
.addSourceLines(
"Test.java",
"import com.google.common.base.Objects;",
"import java.math.BigDecimal;",
"class Test {",
" void test(BigDecimal a, BigDecimal b) {",
" // BUG: Diagnostic contains:",
" boolean foo = a.equals(b);",
" // BUG: Diagnostic contains:",
" boolean bar = !a.equals(b);",
" // BUG: Diagnostic contains:",
" boolean baz = Objects.equal(a, b);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
CompilationTestHelper.newInstance(BigDecimalEquals.class, getClass())
.addSourceLines(
"Test.java",
"import java.math.BigDecimal;",
"class Test {",
" BigDecimal a;",
" BigDecimal b;",
" boolean f(String a, String b) {",
" return a.equals(b);",
" }",
" @Override public boolean equals(Object o) {",
" return a.equals(b);",
" }",
"}")
.doTest();
}
}
| 2,211
| 30.6
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InconsistentCapitalizationTest.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;
/** Test for InconsistentCapitalization bug checker */
@RunWith(JUnit4.class)
public class InconsistentCapitalizationTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(InconsistentCapitalization.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(InconsistentCapitalization.class, getClass());
@Test
public void negativeCases() {
compilationHelper.addSourceFile("InconsistentCapitalizationNegativeCases.java").doTest();
}
@Test
public void correctsInconsistentVariableNameInMethodDefinitionToFieldCase() {
refactoringHelper
.addInputLines(
"in/Test.java",
"class Test {",
" Object aa;",
" void method(Object aA) {",
" this.aa = aA;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" Object aa;",
" void method(Object aa) {",
" this.aa = aa;",
" }",
"}")
.doTest();
}
@Test
public void correctsInconsistentVariableNameInConstructorDefinitionToFieldCase() {
refactoringHelper
.addInputLines(
"in/Test.java",
"class Test {",
" Object aa;",
" Test(Object aA) {",
" this.aa = aA;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" Object aa;",
" Test(Object aa) {",
" this.aa = aa;",
" }",
"}")
.doTest();
}
@Test
public void correctsInconsistentVariableNameInLambdaDefinitionToFieldCase() {
refactoringHelper
.addInputLines(
"in/Test.java",
"import java.util.function.Function;",
"class Test {",
" Object ea;",
" Test() {",
" Function<Void, Object> f = (eA) -> {",
" this.ea = eA;",
" return eA;",
" };",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.function.Function;",
"class Test {",
" Object ea;",
" Test() {",
" Function<Void, Object> f = (ea) -> {",
" this.ea = ea;",
" return ea;",
" };",
" }",
"}")
.doTest();
}
@Test
public void
correctsInconsistentVariableNameInConstructorDefinitionWithMultipleOccurrencesToFieldCase() {
refactoringHelper
.addInputLines(
"in/Test.java",
"class Test {",
" Object aa;",
" Test(Object aA) {",
" this.aa = aA;",
" if (aA == this.aa) {",
" for (Object i = aA;;) {",
" }",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" Object aa;",
" Test(Object aa) {",
" this.aa = aa;",
" if (aa == this.aa) {",
" for (Object i = aa;;) {",
" }",
" }",
" }",
"}")
.doTest();
}
@Test
public void correctsInconsistentVariableNameToFieldCaseAndQualifiesField() {
refactoringHelper
.addInputLines(
"in/Test.java",
"class Test {",
" Object aa;",
" Test(Object aA) {",
" aa = aA;",
" if (aA == aa) {",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" Object aa;",
" Test(Object aa) {",
" this.aa = aa;",
" if (aa == this.aa) {",
" }",
" }",
"}")
.doTest();
}
@Test
public void correctsInconsistentVariableNameToFieldCaseAndQualifiesNestedClassField() {
refactoringHelper
.addInputLines(
"in/Test.java",
"import java.util.function.Function;",
"class Test {",
" Object aa;",
" Object ab;",
" class Nested {",
" Object aB;",
" Nested(Object aA) {",
" aa = aA;",
" if (aa == aA) {}",
" Test.this.aa = aA;",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.function.Function;",
"class Test {",
" Object aa;",
" Object ab;",
" class Nested {",
" Object aB;",
" Nested(Object aa) {",
" Test.this.aa = aa;",
" if (Test.this.aa == aa) {}",
" Test.this.aa = aa;",
" }",
" }",
"}")
.doTest();
}
@Test
public void correctsInconsistentVariableNameToFieldCaseAndQualifiesNestedChildClassField() {
refactoringHelper
.addInputLines(
"in/Test.java",
"import java.util.function.Function;",
"class Test {",
" static class A {",
" Object aa;",
" static class Nested extends A {",
" Nested(Object aA) {",
" aa = aA;",
" if (aa == aA) {}",
" super.aa = aA;",
" }",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.function.Function;",
"class Test {",
" static class A {",
" Object aa;",
" static class Nested extends A {",
" Nested(Object aa) {",
" super.aa = aa;",
" if (super.aa == aa) {}",
" super.aa = aa;",
" }",
" }",
" }",
"}")
.doTest();
}
@Test
public void
correctsInconsistentVariableNameToFieldCaseInAnonymousClassAndQualifiesNestedChildClassField() {
refactoringHelper
.addInputLines(
"in/Test.java",
"import java.util.function.Function;",
"class Test {",
" Object aa;",
" Function<Object, Object> f = new Function() {",
" public Object apply(Object aA) {",
" aa = aA;",
" return aA;",
" }",
" };",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.function.Function;",
"class Test {",
" Object aa;",
" Function<Object, Object> f = new Function() {",
" public Object apply(Object aa) {",
" Test.this.aa = aa;",
" return aa;",
" }",
" };",
"}")
.doTest();
}
// regression test for https://github.com/google/error-prone/issues/999
@Test
public void clash() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" Object _DocumentObjectData_QNAME;",
" Object _DocumentObjectdata_QNAME;",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" Object _DocumentObjectData_QNAME;",
" Object _DocumentObjectdata_QNAME;",
"}")
.doTest();
}
@Test
public void i1008() {
compilationHelper
.addSourceLines(
"Callback.java",
"public class Callback {",
" interface WaitHandler { } // ignore",
" private final WaitHandler waitHandler;",
" // BUG: Diagnostic contains:",
" protected Callback(final WaitHandler waithandler) {",
" this.waitHandler = waithandler;",
" }",
" public static Callback doOnSuccess() {",
" return new Callback(null) {};",
" }",
"}")
.doTest();
}
}
| 9,282
| 28.848875
| 102
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BanClassLoaderTest.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;
/** {@link BanClassLoader}Test */
@RunWith(JUnit4.class)
public class BanClassLoaderTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(BanClassLoader.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(BanClassLoader.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("BanClassLoaderPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("BanClassLoaderNegativeCases.java").doTest();
}
}
| 1,489
| 32.863636
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedAssignmentTest.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 awturner@google.com (Andy Turner)
*/
@RunWith(JUnit4.class)
public class UnnecessaryBoxedAssignmentTest {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryBoxedAssignment.class, getClass());
@Test
public void cases() {
helper
.addInput("testdata/UnnecessaryBoxedAssignmentCases.java")
.addOutput("testdata/UnnecessaryBoxedAssignmentCases_expected.java")
.doTest();
}
}
| 1,294
| 31.375
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NonCanonicalStaticImportTest.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 NonCanonicalStaticImport}Test */
@RunWith(JUnit4.class)
public class NonCanonicalStaticImportTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NonCanonicalStaticImport.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"a/A.java", //
"package a;",
"public class A {",
" public static class Inner {}",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {}")
.addSourceLines(
"b/Test.java",
"package b;",
"// BUG: Diagnostic contains: import a.A.Inner;",
"import static b.B.Inner;",
"class Test {}")
.doTest();
}
@Test
public void negativeStaticMethod() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"public class A {",
" public static class Inner {",
" public static void f() {}",
" }",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {}")
.addSourceLines(
"b/Test.java", //
"package b;",
"import static a.A.Inner.f;",
"class Test {}")
.doTest();
}
@Test
public void negativeGenericTypeStaticMethod() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"public class A {",
" public static class Inner<T> {",
" public static void f() {}",
" }",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {}")
.addSourceLines(
"b/Test.java", //
"package b;",
"import static a.A.Inner.f;",
"class Test {}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"a/A.java", //
"package a;",
"public class A {",
" public static class Inner {}",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {}")
.addSourceLines(
"b/Test.java", //
"package b;",
"import static a.A.Inner;",
"class Test {}")
.doTest();
}
@Test
public void negativeOnDemand() {
compilationHelper
.addSourceLines(
"a/A.java", //
"package a;",
"public class A {",
" public static class Inner {}",
"}")
.addSourceLines(
"b/B.java", //
"package b;",
"import a.A;",
"public class B extends A {}")
.addSourceLines(
"b/Test.java", //
"package b;",
"import static a.A.Inner.*;",
"class Test {}")
.doTest();
}
}
| 4,042
| 26.882759
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnicodeEscapeTest.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.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;
/** Tests for {@link UnicodeEscape}. */
@RunWith(JUnit4.class)
public final class UnicodeEscapeTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(UnicodeEscape.class, getClass());
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(UnicodeEscape.class, getClass());
@Test
public void printableAsciiCharacter_finding() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains:",
" private static final String FOO = \"\\u0020\";",
"}")
.doTest();
}
@Test
public void suppression() {
helper
.addSourceLines(
"Test.java",
"@SuppressWarnings(\"UnicodeEscape\")",
"class Test {",
" private static final String FOO = \"\\u0020\";",
"}")
.doTest();
}
@Test
public void unicodeEscapeRefactoredToLiteral() {
refactoring
.addInputLines(
"Test.java", //
"class Test {",
" private static final String FOO = \"\\u0020\";",
" private static final String BAR = \"\\uuuuu0020\";",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
" private static final String FOO = \" \";",
" private static final String BAR = \" \";",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void jdk8269150() {
refactoring
.addInputLines(
"Test.java", //
"class Test {",
" private static final String FOO = \"\\u005c\\\\u005d\";",
"}")
.addOutputLines(
"Test.java", //
"class Test {",
" private static final String FOO = \"\\\\]\";",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void newlinesRefactored() {
refactoring
.addInputLines(
"Test.java", //
"class Test {\\u000Dprivate static final String FOO = null;",
"}")
.addOutputLines(
"Test.java", //
"class Test {\rprivate static final String FOO = null;",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void nonPrintableAsciiCharacter_noFinding() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" private static final String FOO = \"\\u0312\";",
"}")
.doTest();
}
@Test
public void extraEscapes_noFinding() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" private static final String FOO = \"\\\\u0020\";",
"}")
.doTest();
}
@Test
public void everythingObfuscated() {
refactoring
.addInputLines("A.java", "\\u0063\\u006c\\u0061\\u0073\\u0073\\u0020\\u0041\\u007b\\u007d")
.addOutputLines("A.java", "class A{}")
.doTest(TEXT_MATCH);
}
@Test
public void escapedLiteralBackslashU() {
refactoring
.addInputLines(
"A.java", //
"/** \\u005Cu */",
"class A {}")
.expectUnchanged()
.doTest(TEXT_MATCH);
}
}
| 4,232
| 27.601351
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AttemptedNegativeZeroTest.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.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link AttemptedNegativeZero}Test. */
@RunWith(JUnit4.class)
public final class AttemptedNegativeZeroTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(AttemptedNegativeZero.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Foo.java",
"class Foo {",
" // BUG: Diagnostic contains: ",
" double x = -0;",
" // BUG: Diagnostic contains: ",
" double y = -0L;", // I didn't see the `long` case in the wild.
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Foo.java",
"class Foo {",
" int w = -0;", // weird but not likely to be hiding any bugs
" double x = -0.0;",
" double y = 0;",
" double z = +0;",
"}")
.doTest();
}
}
| 1,773
| 29.586207
| 81
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BadInstanceofTest.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 BadInstanceof} bugpattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class BadInstanceofTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(BadInstanceof.class, getClass());
@Test
public void refactoring() {
BugCheckerRefactoringTestHelper.newInstance(BadInstanceof.class, getClass())
.addInputLines(
"Test.java",
"class A {",
" boolean foo(C c) {",
" return c instanceof A;",
" }",
" boolean notFoo(C c) {",
" return !(c instanceof A);",
" }",
" static class C extends A {}",
"}")
.addOutputLines(
"Test.java",
"class A {",
" boolean foo(C c) {",
" return c != null;",
" }",
" boolean notFoo(C c) {",
" return c == null;",
" }",
" static class C extends A {}",
"}")
.doTest();
}
@Test
public void positiveCases() {
compilationHelper
.addSourceLines(
"Test.java",
"class A {",
" // BUG: Diagnostic contains: `new C()` is a non-null instance of C "
+ "which is a subtype of A",
" boolean t = new C() instanceof A;",
" boolean foo(C c) {",
" // BUG: Diagnostic contains: `c` is an instance of C which is a subtype of A",
" return c instanceof A;",
" }",
" boolean notFoo(C c) {",
" // BUG: Diagnostic contains: `c` is an instance of C which is a subtype of A",
" return !(c instanceof A);",
" }",
"}",
"class C extends A {}")
.doTest();
}
@Test
public void negativeCases() {
compilationHelper
.addSourceLines(
"Test.java",
"class A {",
" boolean foo(A a) {",
" return a instanceof C;",
" }",
"}",
"class C extends A {}")
.doTest();
}
}
| 3,053
| 29.848485
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RxReturnValueIgnoredTest.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 friedj@google.com (Jake Fried)
*/
@RunWith(JUnit4.class)
public class RxReturnValueIgnoredTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(RxReturnValueIgnored.class, getClass())
// Rx1 stubs
.addSourceLines(
"rx1/Observable.java", //
"package rx;", //
"public class Observable<T> {}" //
)
.addSourceLines(
"rx1/Single.java", //
"package rx;", //
"public class Single<T> {}" //
)
.addSourceLines(
"rx1/Completable.java", //
"package rx;", //
"public class Completable<T> {}" //
)
// Rx2 stubs
.addSourceLines(
"rx2/Observable.java", //
"package io.reactivex;", //
"public class Observable<T> {}" //
)
.addSourceLines(
"rx2/Single.java", //
"package io.reactivex;", //
"public class Single<T> {}" //
)
.addSourceLines(
"rx2/Completable.java", //
"package io.reactivex;", //
"public class Completable<T> {}" //
)
.addSourceLines(
"rx2/Maybe.java", //
"package io.reactivex;", //
"public class Maybe<T> {}" //
)
.addSourceLines(
"rx2/Flowable.java", //
"package io.reactivex;", //
"public class Flowable<T> {}" //
);
@Test
public void positiveCases() {
compilationHelper.addSourceFile("RxReturnValueIgnoredPositiveCases.java").doTest();
}
@Test
public void negativeCases() {
compilationHelper.addSourceFile("RxReturnValueIgnoredNegativeCases.java").doTest();
}
@Test
public void rx2Observable() {
compilationHelper
.addSourceLines(
"Test.java",
"import io.reactivex.Observable;",
"class Test {",
" Observable getObservable() { return null; }",
" void f() {",
" // BUG: Diagnostic contains: Rx objects must be checked.",
" getObservable();",
" }",
"}")
.doTest();
}
@Test
public void rx2Single() {
compilationHelper
.addSourceLines(
"Test.java",
"import io.reactivex.Single;",
"class Test {",
" Single getSingle() { return null; }",
" void f() {",
" // BUG: Diagnostic contains: Rx objects must be checked.",
" getSingle();",
" }",
"}")
.doTest();
}
@Test
public void rx2Completable() {
compilationHelper
.addSourceLines(
"Test.java",
"import io.reactivex.Completable;",
"class Test {",
" Completable getCompletable() { return null; } ",
" void f() {",
" // BUG: Diagnostic contains: Rx objects must be checked.",
" getCompletable();",
" }",
"}")
.doTest();
}
@Test
public void rx2Flowable() {
compilationHelper
.addSourceLines(
"Test.java",
"import io.reactivex.Flowable;",
"class Test {",
" Flowable getFlowable() { return null; } ",
" void f() {",
" // BUG: Diagnostic contains: Rx objects must be checked.",
" getFlowable();",
" }",
"}")
.doTest();
}
@Test
public void rx2Maybe() {
compilationHelper
.addSourceLines(
"Test.java",
"import io.reactivex.Maybe;",
"class Test {",
" Maybe getMaybe() { return null; }",
" void f() {",
" // BUG: Diagnostic contains: Rx objects must be checked.",
" getMaybe();",
" }",
"}")
.doTest();
}
@Test
public void rx1Observable() {
compilationHelper
.addSourceLines(
"Test.java",
"import rx.Observable;",
"class Test {",
" Observable getObservable() { return null; }",
" void f() {",
" // BUG: Diagnostic contains: Rx objects must be checked.",
" getObservable();",
" }",
"}")
.doTest();
}
@Test
public void rx1Single() {
compilationHelper
.addSourceLines(
"Test.java",
"import rx.Single;",
"class Test {",
" Single getSingle() { return null; }",
" void f() {",
" // BUG: Diagnostic contains: Rx objects must be checked.",
" getSingle();",
" }",
"}")
.doTest();
}
@Test
public void rx1Completable() {
compilationHelper
.addSourceLines(
"Test.java",
"import rx.Completable;",
"class Test {",
" Completable getCompletable() { return null; } ",
" void f() {",
" // BUG: Diagnostic contains: Rx objects must be checked.",
" getCompletable();",
" }",
"}")
.doTest();
}
}
| 6,190
| 28.065728
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ClassCanBeStaticTest.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;
/** {@link ClassCanBeStatic}Test */
@RunWith(JUnit4.class)
public class ClassCanBeStaticTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ClassCanBeStatic.class, getClass());
@Test
public void negativeCase() {
compilationHelper.addSourceFile("ClassCanBeStaticNegativeCases.java").doTest();
}
@Test
public void positiveCase1() {
compilationHelper.addSourceFile("ClassCanBeStaticPositiveCase1.java").doTest();
}
@Test
public void positiveCase2() {
compilationHelper.addSourceFile("ClassCanBeStaticPositiveCase2.java").doTest();
}
@Test
public void positiveCase3() {
compilationHelper.addSourceFile("ClassCanBeStaticPositiveCase3.java").doTest();
}
@Test
public void positiveReference() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains:",
" private class One { int field; }",
" // BUG: Diagnostic contains:",
" private class Two { String field; }",
"}")
.doTest();
}
@Test
public void nonMemberField() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" int x;",
" private class One {",
" {",
" System.err.println(x);",
" }",
" }",
" // BUG: Diagnostic contains:",
" private class Two {",
" void f(Test t) {",
" System.err.println(t.x);",
" }",
" }",
"}")
.doTest();
}
@Test
public void qualifiedThis() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" private class One {",
" {",
" System.err.println(Test.this);",
" }",
" }",
" // BUG: Diagnostic contains:",
" private class Two {",
" void f(Test t) {",
" System.err.println(Test.class);",
" }",
" }",
"}")
.doTest();
}
@Test
public void referencesSibling() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" private class One {",
" {",
" new Two();",
" }",
" }",
" private class Two {",
" void f(Test t) {",
" System.err.println(Test.this);",
" }",
" }",
"}")
.doTest();
}
@Test
public void referenceInAnonymousClass() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" private class Two {",
" {",
" new Runnable() {",
" @Override public void run() {",
" System.err.println(Test.this);",
" }",
" }.run();",
" }",
" }",
"}")
.doTest();
}
@Test
public void extendsInnerClass() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" private class One {",
" {",
" System.err.println(Test.this);",
" }",
" }",
" private class Two extends One {",
" }",
"}")
.doTest();
}
@Test
public void ctorParametricInnerClass() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" private class One<T> {",
" {",
" System.err.println(Test.this);",
" }",
" }",
" private abstract class Two {",
" {",
" new One<String>();",
" }",
" }",
"}")
.doTest();
}
@Test
public void extendsParametricInnerClass() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" private class One<T> {",
" {",
" System.err.println(Test.this);",
" }",
" }",
" private abstract class Two<T> extends One<T> {}",
"}")
.doTest();
}
@Test
public void referencesTypeParameter() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"class Test<T> {",
" private class One {",
" List<T> xs;",
" }",
"}")
.doTest();
}
@Test
public void referencesTypeParameterImplicit() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"class Test<T> {",
" class One {",
" {",
" System.err.println(Test.this);",
" }",
" }",
" class Two {",
" One one; // implicit reference of Test<T>.One",
" }",
"}")
.doTest();
}
@Test
public void negative_referencesTypeParameterImplicit() {
compilationHelper
.addSourceLines(
"One.java",
"package test;",
"public class One<T> {",
" public class Inner {",
" {",
" System.err.println(One.this);",
" }",
" }",
"}")
.addSourceLines(
"Test.java",
"import test.One.Inner;",
"class Test {",
" // BUG: Diagnostic contains:",
" class Two {",
" Inner inner; // ok: implicit reference of One.Inner",
" }",
"}")
.doTest();
}
@Test
public void qualifiedSuperReference() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" class One {",
" {",
" Test.super.getClass();",
" }",
" }",
"}")
.doTest();
}
@Test
public void annotationMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains:",
" class One {",
" @SuppressWarnings(value = \"\")",
" void f() {}",
" }",
"}")
.doTest();
}
@Test
public void extendsHiddenInnerClass() {
compilationHelper
.addSourceLines(
"A.java", //
"public class A {",
" public class Inner {",
" {",
" System.err.println(A.this);",
" }",
" }",
"}")
.addSourceLines(
"B.java", //
"public class B extends A {",
" public class Inner extends A.Inner {}",
"}")
.doTest();
}
@Test
public void nestedInAnonymous() {
compilationHelper
.addSourceLines(
"A.java", //
"public class A {",
" static Runnable r =",
" new Runnable() {",
" class Inner {",
" }",
" public void run() {}",
" };",
"}")
.doTest();
}
@Test
public void nestedInLocal() {
compilationHelper
.addSourceLines(
"A.java", //
"public class A {",
" static void f() {",
" class Outer {",
" class Inner {",
" }",
" }",
" }",
"}")
.doTest();
}
@Test
public void innerClassMethodReference() {
compilationHelper
.addSourceLines(
"T.java", //
"import java.util.function.Supplier;",
"public class T {",
" class A {",
" {",
" System.err.println(T.this);",
" }",
" }",
" class B {",
" {",
" Supplier<A> s = A::new; // capture enclosing instance",
" System.err.println(s.get());",
" }",
" }",
"}")
.doTest();
}
@Test
public void labelledBreak() {
compilationHelper
.addSourceLines(
"A.java",
"public class A {",
" // BUG: Diagnostic contains:",
" class Inner {",
" void f() {",
" OUTER:",
" while (true) {",
" break OUTER;",
" }",
" }",
" }",
"}")
.doTest();
}
@Test
public void refaster() {
compilationHelper
.addSourceLines(
"BeforeTemplate.java",
"package com.google.errorprone.refaster.annotation;",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.RetentionPolicy;",
"import java.lang.annotation.Target;",
"@Target(ElementType.METHOD)",
"@Retention(RetentionPolicy.SOURCE)",
"public @interface BeforeTemplate {}")
.addSourceLines(
"A.java",
"import com.google.errorprone.refaster.annotation.BeforeTemplate;",
"public class A {",
" class Inner {",
" @BeforeTemplate void f() {}",
" }",
"}")
.doTest();
}
@Test
public void junitNestedClass() {
compilationHelper
.addSourceLines(
"Nested.java",
"package org.junit.jupiter.api;",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.RetentionPolicy;",
"import java.lang.annotation.Target;",
"@Target(ElementType.TYPE)",
"@Retention(RetentionPolicy.RUNTIME)",
"public @interface Nested {}")
.addSourceLines(
"A.java",
"import org.junit.jupiter.api.Nested;",
"public class A {",
" @Nested class Inner {",
" void f() {}",
" }",
"}")
.doTest();
}
}
| 11,411
| 25.601399
| 83
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnusedAnonymousClassTest.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 UnusedAnonymousClass}Test */
@RunWith(JUnit4.class)
public class UnusedAnonymousClassTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(UnusedAnonymousClass.class, getClass());
@Test
public void deadObject() {
compilationHelper
.addSourceLines(
"a/One.java",
"package a;",
"public class One {",
" public static void main(String[] args) {",
" new Object();",
" }",
"}")
.doTest();
}
// Thread has a known side-effect free constructor
@Test
public void deadThread() {
compilationHelper
.addSourceLines(
"a/One.java",
"package a;",
"public class One {",
" public static void main(String[] args) {",
" // BUG: Diagnostic contains:",
" new Thread() {",
" public void run() {}",
" };",
" }",
"}")
.doTest();
}
@Test
public void liveObject() {
compilationHelper
.addSourceLines(
"a/One.java",
"package a;",
"public class One {",
" public static void main(String[] args) {",
" new Object().toString();",
" }",
"}")
.doTest();
}
@Test
public void deadCallable() {
compilationHelper
.addSourceLines(
"a/One.java",
"package a;",
"import java.util.concurrent.Callable;",
"public class One {",
" public static void main(String[] args) throws Exception {",
" // BUG: Diagnostic contains:",
" new Callable<Void>() {",
" public Void call() throws Exception {",
" return null;",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void liveCallable() {
compilationHelper
.addSourceLines(
"a/One.java",
"package a;",
"import java.util.concurrent.Callable;",
"public class One {",
" public static void main(String[] args) throws Exception {",
" new Callable<Void>() {",
" public Void call() throws Exception {",
" return null;",
" }",
" }.call();",
" }",
"}")
.doTest();
}
@Test
public void liveCallableViaCinit() {
compilationHelper
.addSourceLines(
"a/One.java",
"package a;",
"import java.util.concurrent.Callable;",
"import java.util.ArrayList;",
"public class One {",
" static ArrayList<Callable<Void>> callables = new ArrayList<>();",
" public static void main(String[] args) throws Exception {",
" new Callable<Void>() {",
" { callables.add(this); }",
" public Void call() throws Exception {",
" return null;",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void deadCallableWithField() {
compilationHelper
.addSourceLines(
"a/One.java",
"package a;",
"import java.util.concurrent.Callable;",
"import java.util.ArrayList;",
"public class One {",
" public static void main(String[] args) throws Exception {",
" // BUG: Diagnostic contains:",
" new Callable<Void>() {",
" Void register;",
" public Void call() throws Exception {",
" return null;",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void liveCallableViaField() {
compilationHelper
.addSourceLines(
"a/One.java",
"package a;",
"import java.util.concurrent.Callable;",
"import java.util.ArrayList;",
"public class One {",
" static ArrayList<Callable<Void>> callables = new ArrayList<>();",
" static Void register(Callable<Void> callable) {",
" callables.add(callable);",
" return null;",
" }",
" public static void main(String[] args) throws Exception {",
" new Callable<Void>() {",
" Void register = register(this);",
" public Void call() throws Exception {",
" return null;",
" }",
" };",
" }",
"}")
.doTest();
}
}
| 5,603
| 29.291892
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NullablePrimitiveTest.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;
/**
* @author sebastian.h.monte@gmail.com (Sebastian Monte)
*/
@RunWith(JUnit4.class)
public class NullablePrimitiveTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NullablePrimitive.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("NullablePrimitivePositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("NullablePrimitiveNegativeCases.java").doTest();
}
@Test
public void negativeConstructor() {
compilationHelper
.addSourceLines(
"Test.java",
"import javax.annotation.Nullable;",
"class Test {",
" @Nullable public Test() {}",
"}")
.doTest();
}
@Test
public void negativeVoid() {
compilationHelper
.addSourceLines(
"Test.java",
"import javax.annotation.Nullable;",
"class Test {",
" @Nullable void f() {}",
"}")
.doTest();
}
@Test
public void positiveArray() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"class Test {",
" // BUG: Diagnostic contains:",
" List<@Nullable int[]> xs;",
"}")
.doTest();
}
// regression test for #418
@Test
public void typeParameter() {
compilationHelper
.addSourceLines(
"Nullable.java",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.RetentionPolicy;",
"import java.lang.annotation.Target;",
"@Retention(RetentionPolicy.RUNTIME)",
"@Target(ElementType.TYPE_USE)",
"public @interface Nullable {}")
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains:",
" @Nullable int x;",
" // BUG: Diagnostic contains:",
" @Nullable int f() {",
" return 42;",
" }",
" <@Nullable T> int g() {",
" return 42;",
" }",
" int @Nullable [] y;",
"}")
.doTest();
}
}
| 3,213
| 28.218182
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NonRuntimeAnnotationTest.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 scottjohnson@google.com (Scott Johnson)
*/
@RunWith(JUnit4.class)
public class NonRuntimeAnnotationTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NonRuntimeAnnotation.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("NonRuntimeAnnotationPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("NonRuntimeAnnotationNegativeCases.java").doTest();
}
}
| 1,323
| 29.790698
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FunctionalInterfaceMethodChangedTest.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 lowasser@google.com (Louis Wasserman)
*/
@RunWith(JUnit4.class)
public class FunctionalInterfaceMethodChangedTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FunctionalInterfaceMethodChanged.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("FunctionalInterfaceMethodChangedPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("FunctionalInterfaceMethodChangedNegativeCases.java").doTest();
}
}
| 1,369
| 30.860465
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ThreeLetterTimeZoneIDTest.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.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TimeZone;
import java.util.stream.Collectors;
import org.junit.Ignore;
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 ThreeLetterTimeZoneIDTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ThreeLetterTimeZoneID.class, getClass());
@Test
public void allThreeLetterIdsAreCoveredByZoneIdShortIds() {
// The check's logic is predicated on there being an entry in SHORT_IDS for all three-letter
// IDs in TimeZone.getAvailableIDs() that aren't in ZoneId.getAvailableZoneIds().
Set<String> availableZoneIds = new HashSet<>(ZoneId.getAvailableZoneIds());
Set<String> expectedIds =
Arrays.stream(TimeZone.getAvailableIDs())
.filter(s -> s.length() == 3)
.filter(s -> !availableZoneIds.contains(s))
.collect(Collectors.toSet());
assertThat(ZoneId.SHORT_IDS.keySet()).containsExactlyElementsIn(expectedIds);
}
@Test
@Ignore
public void printMappings() {
// This is here for debugging, to allow printing of the suggested replacements.
for (String id : TimeZone.getAvailableIDs()) {
if (id.length() == 3) {
System.out.printf("%s %s %s%n", id, replacements(id, false), replacements(id, true));
}
}
}
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"import java.util.TimeZone;",
"class A {",
" public static void test_PST() {",
" // BUG: Diagnostic contains: TimeZone.getTimeZone(\"America/Los_Angeles\")",
" TimeZone.getTimeZone(\"PST\");",
" }",
" public static void test_EST() {",
" // BUG: Diagnostic contains: TimeZone.getTimeZone(\"Etc/GMT+5\")",
" TimeZone.getTimeZone(\"EST\");",
" }",
" public static void test_noPreferredReplacements() {",
" // BUG: Diagnostic contains: TimeZone.getTimeZone(\"Asia/Dhaka\")",
" TimeZone.getTimeZone(\"BST\");",
" }",
"}")
.doTest();
}
@Test
public void positiveCaseJodaTime() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"import java.util.TimeZone;",
"import org.joda.time.DateTimeZone;",
"class A {",
" public static void test_EST() {",
" // BUG: Diagnostic contains: TimeZone.getTimeZone(\"America/New_York\")",
" DateTimeZone.forTimeZone(TimeZone.getTimeZone(\"EST\"));",
" }",
" public static void test_HST() {",
" // BUG: Diagnostic contains: TimeZone.getTimeZone(\"Pacific/Honolulu\")",
" DateTimeZone.forTimeZone(TimeZone.getTimeZone(\"HST\"));",
" }",
" public static void test_MST() {",
" // BUG: Diagnostic contains: TimeZone.getTimeZone(\"America/Denver\")",
" DateTimeZone.forTimeZone(TimeZone.getTimeZone(\"MST\"));",
" }",
" public static void test_PST() {",
" // Not a special case, but should still work.",
" // BUG: Diagnostic contains: TimeZone.getTimeZone(\"America/Los_Angeles\")",
" DateTimeZone.forTimeZone(TimeZone.getTimeZone(\"PST\"));",
" }",
"}")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"import java.util.TimeZone;",
"class A {",
" public static void notThreeLetter() {",
" TimeZone.getTimeZone(\"\");",
" TimeZone.getTimeZone(\"America/Los_Angeles\");",
" }",
" public static void threeLetterButAllowed() {",
" TimeZone.getTimeZone(\"GMT\");",
" TimeZone.getTimeZone(\"UTC\");",
" TimeZone.getTimeZone(\"CET\");",
" TimeZone.getTimeZone(\"PRC\");",
" }",
"}")
.doTest();
}
@Test
public void replacements_pST() {
ImmutableList<String> replacements = replacements("PST", false);
// Suggests IANA ID first, then the fixed offset.
assertThat(replacements).containsExactly("America/Los_Angeles", "Etc/GMT+8").inOrder();
}
@Test
public void replacements_eST() {
ImmutableList<String> replacements = replacements("EST", false);
// Suggests fixed offset first, then the IANA ID, because this the former has the same rules as
// TimeZone.getTimeZone("EST").
assertThat(replacements).containsExactly("Etc/GMT+5", "America/New_York").inOrder();
}
@Test
public void replacements_iST() {
ImmutableList<String> replacements = replacements("IST", false);
assertThat(replacements).containsExactly("Asia/Kolkata").inOrder();
}
@Test
public void replacements_cST() {
// Only rule-equivalent suggestions are made (unless we have explicitly provided suggestions) -
// we don't suggest "China Standard Time" for CST, because the existing code is semantically
// equivalent to US "Central Standard Time".
ImmutableList<String> replacements = replacements("CST", false);
assertThat(replacements).contains("America/Chicago");
assertThat(replacements).doesNotContain("Asia/Shanghai");
}
private static ImmutableList<String> replacements(String zone, boolean inJodaTimeContext) {
return ThreeLetterTimeZoneID.getReplacement(zone, inJodaTimeContext, "message").replacements;
}
}
| 6,690
| 36.379888
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IdentityBinaryExpressionTest.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 IdentityBinaryExpression}Test */
@RunWith(JUnit4.class)
public class IdentityBinaryExpressionTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(IdentityBinaryExpression.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean f(boolean a) {",
" // BUG: Diagnostic contains:",
" return a || a;",
" }",
" boolean g(boolean a) {",
" // BUG: Diagnostic contains:",
" return a && a;",
" }",
" boolean h(boolean a) {",
" // BUG: Diagnostic contains:",
" return f(a) && f(a);",
" }",
" boolean i(boolean a) {",
" boolean r;",
" // BUG: Diagnostic contains:",
" r = a & a;",
" // BUG: Diagnostic contains:",
" r = a | a;",
" return r;",
" }",
" int j(int x) {",
" int r;",
" // BUG: Diagnostic contains:",
" r = x & x;",
" // BUG: Diagnostic contains:",
" r = x | x;",
" return x;",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean f(boolean a, boolean b) {",
" return a || b;",
" }",
" boolean g(boolean a, boolean b) {",
" return a && b;",
" }",
" boolean h(boolean a, boolean b) {",
" return a & b;",
" }",
" boolean i(boolean a, boolean b) {",
" return a | b;",
" }",
" int j(int a, int b) {",
" return a & b;",
" }",
" int k(int a, int b) {",
" return a | b;",
" }",
"}")
.doTest();
}
@Test
public void negativeLiteral() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" double f() {",
" return 1.0 / 1.0;",
" }",
"}")
.doTest();
}
@Test
public void fixes() {
compilationHelper
.addSourceLines(
"in/Test.java", //
"class Test {",
" void f(int a) {",
" // BUG: Diagnostic contains: equivalent to `1`",
" int r = a / a;",
" // BUG: Diagnostic contains: equivalent to `0`",
" r = a - a;",
" // BUG: Diagnostic contains: equivalent to `0`",
" r = a % a;",
" // BUG: Diagnostic contains: equivalent to `true`",
" boolean b = a >= a;",
" // BUG: Diagnostic contains: equivalent to `true`",
" b = a == a;",
" // BUG: Diagnostic contains: equivalent to `true`",
" b = a <= a;",
" // BUG: Diagnostic contains: equivalent to `false`",
" b = a > a;",
" // BUG: Diagnostic contains: equivalent to `false`",
" b = a < a;",
" // BUG: Diagnostic contains: equivalent to `false`",
" b = a != a;",
" // BUG: Diagnostic contains: equivalent to `false`",
" b = b ^ b;",
" }",
"}")
.doTest();
}
@Test
public void negativeAssert() {
compilationHelper
.addSourceLines(
"Test.java",
"import static org.junit.Assert.assertTrue;",
"import static org.junit.Assert.assertFalse;",
"class Test {",
" void f(int x) {",
" assertTrue(x == x);",
" assertFalse(x != x);",
" }",
"}")
.doTest();
}
@Test
public void isNaN() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean f(float a, Float b, double c, Double d) {",
" boolean r = false;",
" // BUG: Diagnostic contains: equivalent to `!Float.isNaN(a)`",
" r |= a == a;",
" // BUG: Diagnostic contains: equivalent to `Float.isNaN(a)`",
" r |= a != a;",
" // BUG: Diagnostic contains: equivalent to `!Float.isNaN(b)`",
" r |= b == b;",
" // BUG: Diagnostic contains: equivalent to `Float.isNaN(b)`",
" r |= b != b;",
" // BUG: Diagnostic contains: equivalent to `!Double.isNaN(c)`",
" r |= c == c;",
" // BUG: Diagnostic contains: equivalent to `Double.isNaN(c)`",
" r |= c != c;",
" // BUG: Diagnostic contains: equivalent to `!Double.isNaN(d)`",
" r |= d == d;",
" // BUG: Diagnostic contains: equivalent to `Double.isNaN(d)`",
" r |= d != d;",
" return r;",
" }",
"}")
.doTest();
}
}
| 6,121
| 31.56383
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LoopConditionCheckerTest.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 LoopConditionChecker}Test */
@RunWith(JUnit4.class)
public class LoopConditionCheckerTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(LoopConditionChecker.class, getClass());
@Test
public void positive() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" int h9() {",
" int sum = 0;",
" int i, j;",
" for (i = 0; i < 10; ++i) {",
" // BUG: Diagnostic contains:",
" for (j = 0; j < 10; ++i) {",
" sum += j;",
" }",
" }",
" return sum;",
" }",
"}")
.doTest();
}
@Test
public void positive_noUpdate() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains:",
" for (int i = 0; i < 10; ) {",
" }",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" int h9() {",
" int sum = 0;",
" int i, j;",
" for (i = 0; i < 10; ++i) {",
" for (j = 0; j < 10; ++i) {",
" sum += j;",
" j++;",
" }",
" }",
" return sum;",
" }",
"}")
.doTest();
}
@Test
public void negative_forExpression() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" for (int i = 0; i < 10; i++) {",
" System.err.println(i);",
" }",
" }",
"}")
.doTest();
}
@Test
public void negative_noVariable() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Iterator;",
"class Test {",
" void f(Iterable<String> xs) {",
" Iterator<String> it = xs.iterator();",
" while (it.hasNext()) {",
" System.err.println(it.next());",
" }",
" }",
"}")
.doTest();
}
@Test
public void negative_noCondition() {
compilationTestHelper
.addSourceLines(
"Test.java", //
"class Test {",
" void f() {",
" for (;;) {}",
" }",
"}")
.doTest();
}
@Test
public void negative_noUpdate() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" for (int i = 0; i < 10; ) {",
" i++;",
" }",
" }",
"}")
.doTest();
}
@Test
public void negative_conditionUpdate() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" int i = 0;",
" while (i++ < 10) {}",
" }",
"}")
.doTest();
}
@Test
public void negative_field() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" int i = 0;",
" void f() {",
" while (i < 10) {",
" g();",
" }",
" }",
" void g() {",
" i++;",
" }",
"}")
.doTest();
}
}
| 4,610
| 24.475138
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ObjectEqualsForPrimitivesTest.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;
/**
* @author vlk@google.com (Volodymyr Kachurovskyi)
*/
@RunWith(JUnit4.class)
public class ObjectEqualsForPrimitivesTest {
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(ObjectEqualsForPrimitives.class, getClass());
@Test
public void boxedIntegers() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean doTest(Integer a, Integer b) {",
" return Objects.equals(a, b);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void boxedAndPrimitive() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean doTest(Integer a, int b) {",
" return Objects.equals(a, b);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void primitiveAndBoxed() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean doTest(int a, Integer b) {",
" return Objects.equals(a, b);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void objects() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean doTest(Object a, Object b) {",
" return Objects.equals(a, b);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void primitives() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean testBooleans(boolean a, boolean b) {",
" return Objects.equals(a, b);",
" }",
" private static boolean testInts(int a, int b) {",
" return Objects.equals(a, b);",
" }",
" private static boolean testLongs(long a, long b) {",
" return Objects.equals(a, b);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean testBooleans(boolean a, boolean b) {",
" return (a == b);",
" }",
" private static boolean testInts(int a, int b) {",
" return (a == b);",
" }",
" private static boolean testLongs(long a, long b) {",
" return (a == b);",
" }",
"}")
.doTest();
}
@Test
public void primitivesNegated() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean testBooleans(boolean a, boolean b) {",
" return !Objects.equals(a, b);",
" }",
" private static boolean testInts(int a, int b) {",
" return !Objects.equals(a, b);",
" }",
" private static boolean testLongs(long a, long b) {",
" return !Objects.equals(a, b);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean testBooleans(boolean a, boolean b) {",
" return !(a == b);",
" }",
" private static boolean testInts(int a, int b) {",
" return !(a == b);",
" }",
" private static boolean testLongs(long a, long b) {",
" return !(a == b);",
" }",
"}")
.doTest();
}
@Test
public void intAndLong() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean doTest(int a, long b) {",
" return Objects.equals(a, b);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Objects;",
"public class Test {",
" private static boolean doTest(int a, long b) {",
" return (a == b);",
" }",
"}")
.doTest();
}
}
| 5,602
| 29.617486
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FinallyTest.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 cushon@google.com (Liam Miller-Cushon)
*/
@RunWith(JUnit4.class)
public class FinallyTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(Finally.class, getClass());
@Test
public void positiveCase1() {
compilationHelper.addSourceFile("FinallyPositiveCase1.java").doTest();
}
@Test
public void positiveCase2() {
compilationHelper.addSourceFile("FinallyPositiveCase2.java").doTest();
}
@Test
public void negativeCase1() {
compilationHelper.addSourceFile("FinallyNegativeCase1.java").doTest();
}
@Test
public void negativeCase2() {
compilationHelper.addSourceFile("FinallyNegativeCase2.java").doTest();
}
@Test
public void lambda() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" try {",
" } catch (Throwable t) {",
" } finally {",
" Runnable r = () -> { return; };",
" }",
" }",
"}")
.doTest();
}
}
| 1,904
| 26.214286
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TryWithResourcesVariableTest.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 org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link TryWithResourcesVariable}Test */
@RunWith(JUnit4.class)
public class TryWithResourcesVariableTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(TryWithResourcesVariable.class, getClass());
@Test
public void refactoring() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f (AutoCloseable r1) {",
" try (AutoCloseable r2 = r1) {",
" System.err.println(r2);",
" } catch (Exception e) {",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" void f (AutoCloseable r1) {",
" try (r1) {",
" System.err.println(r1);",
" } catch (Exception e) {",
" }",
" }",
"}")
.doTest();
}
@Test
public void refactoringTwoVariables() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f (AutoCloseable a1, AutoCloseable a2) {",
" try (AutoCloseable b1 = a1; AutoCloseable b2 = a2) {",
" System.err.println(b1);",
" System.err.println(b2);",
" } catch (Exception e) {",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" void f (AutoCloseable a1, AutoCloseable a2) {",
" try (a1; a2) {",
" System.err.println(a1);",
" System.err.println(a2);",
" } catch (Exception e) {",
" }",
" }",
"}")
.doTest();
}
@Test
public void negativeNonFinal() {
testHelper
.addInputLines(
"Test.java",
"abstract class Test {",
" abstract AutoCloseable reassign(AutoCloseable r);",
" void f (AutoCloseable r1) {",
" r1 = reassign(r1);",
" try (AutoCloseable r2 = r1) {",
" System.err.println(r2);",
" } catch (Exception e) {",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| 3,160
| 29.68932
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TypeParameterQualifierTest.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 TypeParameterQualifier}Test */
@RunWith(JUnit4.class)
public class TypeParameterQualifierTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(TypeParameterQualifier.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Foo.java",
// force a line break
"class Foo {",
" static class Builder {}",
"}")
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: populate(Foo.Builder builder)",
" static <T extends Foo> T populate(T.Builder builder) {",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void positiveMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" static <T extends Enum<T>> T get(Class<T> clazz, String value) {",
" // BUG: Diagnostic contains: Enum.valueOf(clazz, value);",
" return T.valueOf(clazz, value);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Foo.java",
// force a line break
"class Foo {",
" static class Builder {}",
"}")
.addSourceLines(
"Test.java",
"class Test {",
" static <T extends Foo> T populate(T builder) {",
" return null;",
" }",
"}")
.doTest();
}
}
| 2,458
| 28.27381
| 82
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnit4SetUpNotRunTest.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.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.JUnit4;
import org.junit.runners.ParentRunner;
/**
* @author glorioso@google.com (Nick Glorioso)
*/
@RunWith(JUnit4.class)
public class JUnit4SetUpNotRunTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JUnit4SetUpNotRun.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(JUnit4SetUpNotRun.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("JUnit4SetUpNotRunPositiveCases.java").doTest();
}
@Test
public void positiveCase_customBefore() {
compilationHelper.addSourceFile("JUnit4SetUpNotRunPositiveCaseCustomBefore.java").doTest();
}
@Test
public void customBefore_refactoring() {
refactoringTestHelper
.addInputLines("Before.java", " @interface Before {}")
.expectUnchanged()
.addInputLines(
"in/Foo.java",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(JUnit4.class)",
"public class Foo {",
" @Before",
" public void initMocks() {}",
" @Before",
" protected void badVisibility() {}",
"}")
.addOutputLines(
"out/Foo.java",
"import org.junit.Before;",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(JUnit4.class)",
"public class Foo {",
" @Before",
" public void initMocks() {}",
" @Before",
" public void badVisibility() {}",
"}")
.doTest();
}
@Test
public void positiveCase_customBeforeDifferentName() {
compilationHelper.addSourceFile("JUnit4SetUpNotRunPositiveCaseCustomBefore2.java").doTest();
}
@Test
public void negativeCases() {
compilationHelper.addSourceFile("JUnit4SetUpNotRunNegativeCases.java").doTest();
}
public abstract static class SuperTest {
@Before
public void setUp() {}
}
@Test
public void noBeforeOnClasspath() {
compilationHelper
.addSourceLines(
"Test.java",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"import " + SuperTest.class.getCanonicalName() + ";",
"@RunWith(JUnit4.class)",
"class Test extends SuperTest {",
" @Override public void setUp() {}",
"}")
.withClasspath(
RunWith.class,
JUnit4.class,
BlockJUnit4ClassRunner.class,
ParentRunner.class,
SuperTest.class,
SuperTest.class.getEnclosingClass())
.doTest();
}
}
| 3,728
| 30.871795
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EqualsNaNTest.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 EqualsNaNTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(EqualsNaN.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("EqualsNaNPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("EqualsNaNNegativeCases.java").doTest();
}
}
| 1,277
| 28.72093
| 76
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnTypeTest.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 org.junit.Assume.assumeTrue;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
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 MixedMutabilityReturnType} bugpattern. */
@RunWith(JUnit4.class)
public final class MixedMutabilityReturnTypeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(MixedMutabilityReturnType.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(MixedMutabilityReturnType.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Collections;",
"import java.util.List;",
"import java.util.ArrayList;",
"class Test {",
" // BUG: Diagnostic contains: MixedMutabilityReturnType",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return Collections.emptyList();",
" }",
" return new ArrayList<>();",
" }",
"}")
.doTest();
}
@Test
public void whenSuppressed_noWarning() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Collections;",
"import java.util.List;",
"import java.util.ArrayList;",
"class Test {",
" @SuppressWarnings(\"MixedMutabilityReturnType\")",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return Collections.emptyList();",
" }",
" return new ArrayList<>();",
" }",
"}")
.doTest();
}
@Test
public void tracksActualVariableTypes() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Collections;",
"import java.util.List;",
"import java.util.ArrayList;",
"class Test {",
" // BUG: Diagnostic contains: MixedMutabilityReturnType",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return Collections.emptyList();",
" }",
" List<Integer> ints = new ArrayList<>();",
" return ints;",
" }",
"}")
.doTest();
}
@Test
public void uninferrableTypes_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Collections;",
"import java.util.List;",
"import java.util.ArrayList;",
"class Test {",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return Collections.emptyList();",
" }",
" return bar();",
" }",
" List<Integer> bar() {",
" return new ArrayList<>();",
" }",
"}")
.doTest();
}
@Test
public void allImmutable_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Collections;",
"import java.util.List;",
"import java.util.ArrayList;",
"class Test {",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return Collections.emptyList();",
" }",
" return Collections.singletonList(1);",
" }",
"}")
.doTest();
}
@Test
public void nullType_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Collections;",
"import java.util.List;",
"import java.util.ArrayList;",
"class Test {",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return null;",
" }",
" return Collections.singletonList(1);",
" }",
"}")
.doTest();
}
@Test
public void immutableEnumSetNotMisclassified() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Sets;",
"import java.util.Set;",
"class Test {",
" enum E { A, B }",
" Set<E> test() {",
" return Sets.immutableEnumSet(E.A);",
" }",
"}")
.doTest();
}
@Test
public void simpleRefactoring() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"final class Test {",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return Collections.emptyList();",
" }",
" List<Integer> ints = new ArrayList<>();",
" ints.add(1);",
" return ints;",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"final class Test {",
" ImmutableList<Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableList.of();",
" }",
" ImmutableList.Builder<Integer> ints = ImmutableList.builder();",
" ints.add(1);",
" return ints.build();",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void refactoringOverridable() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"class Test {",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return Collections.emptyList();",
" }",
" List<Integer> ints = new ArrayList<>();",
" ints.add(1);",
" return ints;",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"class Test {",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableList.of();",
" }",
" List<Integer> ints = new ArrayList<>();",
" ints.add(1);",
" return ImmutableList.copyOf(ints);",
" }",
"}")
.doTest();
}
@Test
public void refactoringCantReplaceWithBuilder() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"final class Test {",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableList.of();",
" }",
" List<Integer> ints = new ArrayList<>();",
" ints.add(1);",
" ints.clear();",
" ints.add(2);",
" return ints;",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"final class Test {",
" ImmutableList<Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableList.of();",
" }",
" List<Integer> ints = new ArrayList<>();",
" ints.add(1);",
" ints.clear();",
" ints.add(2);",
" return ImmutableList.copyOf(ints);",
" }",
"}")
.doTest();
}
@Test
public void refactoringIgnoresAlreadyImmutableMap() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableMap;",
"import java.util.HashMap;",
"import java.util.Map;",
"final class Test {",
" Map<Integer, Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableMap.of(1, 1);",
" }",
" Map<Integer, Integer> ints = new HashMap<>();",
" ints.put(2, 2);",
" return ints;",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableMap;",
"import java.util.HashMap;",
"import java.util.Map;",
"final class Test {",
" ImmutableMap<Integer, Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableMap.of(1, 1);",
" }",
" ImmutableMap.Builder<Integer, Integer> ints = ImmutableMap.builder();",
" ints.put(2, 2);",
" return ints.build();",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void refactoringGuavaFactories() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.Lists;",
"import java.util.List;",
"final class Test {",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableList.of(1);",
" } else if (hashCode() < 0) {",
" List<Integer> ints = Lists.newArrayList();",
" ints.add(2);",
" return ints;",
" } else {",
" List<Integer> ints = Lists.newArrayList(1, 3);",
" ints.add(2);",
" return ints;",
" }",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.Lists;",
"import java.util.List;",
"final class Test {",
" ImmutableList<Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableList.of(1);",
" } else if (hashCode() < 0) {",
" ImmutableList.Builder<Integer> ints = ImmutableList.builder();",
" ints.add(2);",
" return ints.build();",
" } else {",
" List<Integer> ints = Lists.newArrayList(1, 3);",
" ints.add(2);",
" return ImmutableList.copyOf(ints);",
" }",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
@Test
public void refactoringTreeMap() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableMap;",
"import java.util.Map;",
"import java.util.TreeMap;",
"final class Test {",
" Map<Integer, Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableMap.of(1, 1);",
" }",
" Map<Integer, Integer> ints = new TreeMap<>();",
" ints.put(2, 1);",
" return ints;",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableMap;",
"import java.util.Map;",
"import java.util.TreeMap;",
"final class Test {",
" ImmutableMap<Integer, Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableMap.of(1, 1);",
" }",
" Map<Integer, Integer> ints = new TreeMap<>();",
" ints.put(2, 1);",
" return ImmutableMap.copyOf(ints);",
" }",
"}")
.doTest();
}
@Test
public void refactoringNonLocalReturnedVariable() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"class Test {",
" List<Integer> ints = new ArrayList<>();",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return Collections.emptyList();",
" }",
" ints.add(1);",
" return ints;",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"class Test {",
" List<Integer> ints = new ArrayList<>();",
" List<Integer> foo() {",
" if (hashCode() > 0) {",
" return ImmutableList.of();",
" }",
" ints.add(1);",
" return ImmutableList.copyOf(ints);",
" }",
"}")
.doTest();
}
@Test
public void refactoringWithNestedCollectionsHelper() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"class Test {",
" <T> List<T> foo(T a) {",
" if (hashCode() > 0) {",
" return new ArrayList<>(Collections.singleton(a));",
" }",
" return Collections.singletonList(a);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"class Test {",
" <T> List<T> foo(T a) {",
" if (hashCode() > 0) {",
" return ImmutableList.copyOf(new ArrayList<>(Collections.singleton(a)));",
" }",
" return ImmutableList.of(a);",
" }",
"}")
.doTest();
}
@Test
public void refactoringWithVar() {
assumeTrue(RuntimeVersion.isAtLeast15());
refactoringHelper
.addInputLines(
"Test.java",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"final class Test {",
" List<Object> foo() {",
" if (hashCode() > 0) {",
" return Collections.emptyList();",
" }",
" var ints = new ArrayList<>();",
" ints.add(1);",
" return ints;",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"final class Test {",
" ImmutableList<Object> foo() {",
" if (hashCode() > 0) {",
" return ImmutableList.of();",
" }",
" var ints = ImmutableList.builder();",
" ints.add(1);",
" return ints.build();",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
/** Regression test for b/192399621 */
@Test
public void biMap_doesNotCrash() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.BiMap;",
"import com.google.common.collect.HashBiMap;",
"import com.google.common.collect.ImmutableBiMap;",
"class Test {",
" // BUG: Diagnostic contains: MixedMutabilityReturnType",
" public BiMap<String, String> foo() {",
" if (hashCode() > 0) {",
" return ImmutableBiMap.of();",
" }",
" return HashBiMap.create(5);",
" }",
"}")
.doTest();
}
}
| 17,949
| 32.179298
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MethodCanBeStaticTest.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.common.collect.ImmutableList;
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 MethodCanBeStatic}Test */
@RunWith(JUnit4.class)
public class MethodCanBeStaticTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(MethodCanBeStatic.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(MethodCanBeStatic.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: private static int add(",
" private int add(int x, int y) {",
" return x + y;",
" }",
"}")
.doTest();
}
@Test
public void positiveCycle() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" private int a(int x) {",
" return b(x);",
" }",
" private int b(int x) {",
" return a(x);",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" private static int a(int x) {",
" return b(x);",
" }",
" private static int b(int x) {",
" return a(x);",
" }",
"}")
.doTest();
}
@Test
public void negativeCycle() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" public int f(int x) {",
" return x;",
" }",
" private int a(int x) {",
" return b(x) + f(x);",
" }",
" private int b(int x) {",
" return a(x) + f(x);",
" }",
"}")
.doTest();
}
@Test
public void positiveChain() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" private static final int FOO = 1;",
" private int a() { return FOO; }",
" private int b() { return a(); }",
" private int c() { return b(); }",
" private int d() { return c(); }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" private static final int FOO = 1;",
" private static int a() { return FOO; }",
" private static int b() { return a(); }",
" private static int c() { return b(); }",
" private static int d() { return c(); }",
"}")
.doTest();
}
@Test
public void positiveChain_oneFix() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" private static final int FOO = 1;",
" // BUG: Diagnostic contains: MethodCanBeStatic",
" private int a() { return FOO; }",
" private int b() { return a(); }",
" private int c() { return b(); }",
" private int d() { return c(); }",
"}")
.doTest();
}
@Test
public void positiveRecursive() {
refactoringHelper
.addInputLines(
"Test.java", //
"class Test {",
" private int a(int x) {",
" return a(x);",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" private static int a(int x) {",
" return a(x);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" int base = 0;",
" private int f(int x, int y) {",
" return base++ + x + y;",
" }",
"}")
.doTest();
}
@Test
public void positiveTypeParameter() {
testHelper
.addSourceLines(
"Test.java",
"class Test<T> {",
" // BUG: Diagnostic contains: private static <T> T f(",
" private <T> T f(int x, int y) {",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void negativeSuppressedByKeep() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Keep;",
"class Test {",
" @Keep",
" private int add(int x, int y) {",
" return x + y;",
" }",
"}")
.doTest();
}
@Test
public void negativeTypeParameter() {
testHelper
.addSourceLines(
"Test.java",
"class Test<T> {",
" private T f(int x, int y) {",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void negativeConstructor() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" Test() {",
"}",
"}")
.doTest();
}
@Test
public void negativePublic() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" public String toString() {",
" return \"\";",
" }",
"}")
.doTest();
}
@Test
public void negativeSynchronized() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" private synchronized String frobnicate() {",
" return \"\";",
" }",
"}")
.doTest();
}
@Test
public void negativeSuppressed() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"MethodCanBeStatic\")",
" private String f() {",
" return \"\";",
" }",
"}")
.doTest();
}
@Test
public void negativeSuppressedAlt() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"static-method\")",
" private String f() {",
" return \"\";",
" }",
"}")
.doTest();
}
@Test
public void negativeOverride() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" @Override",
" public String toString() {",
" return \"\";",
" }",
"}")
.doTest();
}
@Test
public void negativeMethodCall() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" int x;",
" int f() {",
" return x++;",
" }",
" private int g() {",
" return f();",
" }",
"}")
.doTest();
}
@Test
public void nativeMethod() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" private native int f();",
"}")
.doTest();
}
@Test
public void innerClass() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" class Inner {",
" private int incr(int x) {",
" return x + 1;",
" }",
" }",
"}")
.doTest();
}
@Test
public void negativeEnum() {
testHelper
.addSourceLines(
"Test.java", //
"enum Test {",
" VALUE {",
" private void foo() {}",
" }",
"}")
.doTest();
}
@Test
public void negativeAnonymous() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" static void foo() {",
" new Object() {",
" private void foo() {}",
" };",
" }",
"}")
.doTest();
}
@Test
public void negativeLocal() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" static void foo() {",
" class Local {",
" private void foo() {}",
" }",
" }",
"}")
.doTest();
}
@Test
public void negative_referencesTypeVariable() {
testHelper
.addSourceLines(
"Test.java",
"class Test<T> {",
" private int add(int x, int y) {",
" T t = null;",
" return x + y;",
" }",
"}")
.doTest();
}
@Test
public void negative_baseClass() {
testHelper
.addSourceLines(
"A.java", //
"class A {",
" void foo() {}",
"}")
.addSourceLines(
"B.java", //
"class B extends A {",
" private void bar() {",
" foo();",
" }",
"}")
.doTest();
}
@Test
public void serialization() {
testHelper
.addSourceLines(
"Test.java", //
"import java.io.ObjectInputStream;",
"import java.io.ObjectOutputStream;",
"import java.io.ObjectStreamException;",
"import java.io.IOException;",
"import java.io.Serializable;",
"class Test implements Serializable {",
" private void readObject(",
" ObjectInputStream stream) throws IOException, ClassNotFoundException {}",
" private void writeObject(",
" ObjectOutputStream stream) throws IOException {}",
" private void readObjectNoData() throws ObjectStreamException {}",
" private Object readResolve() { return null; }",
" private Object writeReplace() { return null; }",
"}")
.doTest();
}
@Test
public void methodReference() {
refactoringHelper
.addInputLines(
"in/Test.java",
"import java.util.function.ToIntBiFunction;",
"class Test {",
" private int add(int x, int y) {",
" return x + y;",
" }",
" ToIntBiFunction<Integer, Integer> f = this::add;",
" ToIntBiFunction<Integer, Integer> g = (x, y) -> this.add(x, y);",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.function.ToIntBiFunction;",
"class Test {",
" private static int add(int x, int y) {",
" return x + y;",
" }",
" ToIntBiFunction<Integer, Integer> f = Test::add;",
" ToIntBiFunction<Integer, Integer> g = (x, y) -> Test.add(x, y);",
"}")
.doTest();
}
@Test
public void multipleReports() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: static",
" private int a(int x) {",
" return b(x);",
" }",
" // BUG: Diagnostic contains: static",
" private int b(int x) {",
" return a(x);",
" }",
"}")
.setArgs(ImmutableList.of("-XepOpt:MethodCanBeStatic:FindingPerSite"))
.doTest();
}
@Test
public void abstractMethod_notFlagged() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" private static abstract class Foo {",
" abstract void frobnicate();",
" }",
"}")
.doTest();
}
@Test
public void defaultMethodExempted() {
testHelper
.addSourceLines(
"Test.java", //
"class Test {",
" private interface Foo { default void foo() {} }",
"}")
.doTest();
}
@Test
public void keepAnnotationsExempted() {
testHelper
.addSourceLines(
"DoFn.java",
"package org.apache.beam.sdk.transforms;",
"public class DoFn {",
" public @interface ProcessElement {}",
"}")
.addSourceLines(
"Test.java", //
"class Test {",
" @org.apache.beam.sdk.transforms.DoFn.ProcessElement",
" private void foo() {}",
"}")
.doTest();
}
}
| 13,503
| 25.119923
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StringSplitterTest.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.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link StringSplitter} check. */
@RunWith(JUnit4.class)
public class StringSplitterTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(StringSplitter.class, getClass());
@Test
public void positive() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" for (String s : \"\".split(\":\")) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" void f() {",
" for (String s : Splitter.on(':').split(\"\")) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
// Regression test for issue #1124
@Test
public void positive_localVarTypeInference() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" var lines = \"\".split(\":\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" void f() {",
" var lines = Splitter.on(':').split(\"\");",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void positive_patternIsSymbol() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" static final String NON_REGEX_PATTERN_STRING = \":\";",
" static final String REGEX_PATTERN_STRING = \".*\";",
" static final String CONVERTIBLE_PATTERN_STRING = \"\\\\Q\\\\E:\";",
" void f() {",
" for (String s : \"\".split(NON_REGEX_PATTERN_STRING)) {}",
" for (String s : \"\".split(REGEX_PATTERN_STRING)) {}",
" for (String s : \"\".split(CONVERTIBLE_PATTERN_STRING)) {}",
" for (String s : \"\".split((CONVERTIBLE_PATTERN_STRING))) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" static final String NON_REGEX_PATTERN_STRING = \":\";",
" static final String REGEX_PATTERN_STRING = \".*\";",
" static final String CONVERTIBLE_PATTERN_STRING = \"\\\\Q\\\\E:\";",
" void f() {",
" for (String s : Splitter.onPattern(NON_REGEX_PATTERN_STRING).split(\"\")) {}",
" for (String s : Splitter.onPattern(REGEX_PATTERN_STRING).split(\"\")) {}",
" for (String s : Splitter.onPattern(CONVERTIBLE_PATTERN_STRING).split(\"\")) {}",
" for (String s : Splitter.onPattern((CONVERTIBLE_PATTERN_STRING)).split(\"\")) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void positive_patternIsConcatenation() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" for (String s : \"\".split(\":\" + 0)) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" void f() {",
" for (String s : Splitter.onPattern(\":\" + 0).split(\"\")) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void positive_patternNotConstant() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" String pattern = \":\";",
" for (String s : \"\".split(pattern)) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" void f() {",
" String pattern = \":\";",
" for (String s : Splitter.onPattern(pattern).split(\"\")) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void positive_singleEscapedCharacter() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" for (String s : \"\".split(\"\\u0000\")) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" void f() {",
" for (String s : Splitter.on('\\u0000').split(\"\")) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void varLoop() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" String[] pieces = \"\".split(\":\");",
" for (String s : pieces) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" void f() {",
" Iterable<String> pieces = Splitter.on(':').split(\"\");",
" for (String s : pieces) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void varLoopLength() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" String[] pieces = \"\".split(\":\");",
" for (int i = 0; i < pieces.length; i++) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"import java.util.List;",
"class Test {",
" void f() {",
" List<String> pieces = Splitter.on(':').splitToList(\"\");",
" for (int i = 0; i < pieces.size(); i++) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void varList() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" String[] pieces = \"\".split(\":\");",
" System.err.println(pieces[0]);",
" System.err.println(pieces[1]);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"import java.util.List;",
"class Test {",
" void f() {",
" List<String> pieces = Splitter.on(':').splitToList(\"\");",
" System.err.println(pieces.get(0));",
" System.err.println(pieces.get(1));",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void positiveRegex() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" for (String s : \"\".split(\".*foo\\\\t\")) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" void f() {",
" for (String s : Splitter.onPattern(\".*foo\\\\t\").split(\"\")) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void character() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" for (String s : \"\".split(\"c\")) {}",
" for (String s : \"\".split(\"abc\")) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" void f() {",
" for (String s : Splitter.on('c').split(\"\")) {}",
" for (String s : Splitter.on(\"abc\").split(\"\")) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void negative() {
CompilationTestHelper.newInstance(StringSplitter.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" String[] pieces = \"\".split(\":\");",
" System.err.println(pieces);", // escapes
" }",
"}")
.doTest();
}
@Test
public void mutation() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" String[] xs = \"\".split(\"c\");",
" xs[0] = null;",
" System.err.println(xs[0]);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" void f() {",
" List<String> xs = new ArrayList<>(Splitter.on('c').splitToList(\"\"));",
" xs.set(0, null);",
" System.err.println(xs.get(0));",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
// regression test for b/72088500
@Test
public void b72088500() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f(String input) {",
" String[] lines = input.split(\"\\\\r?\\\\n\");",
" System.err.println(lines[0]);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"import java.util.List;",
"class Test {",
" void f(String input) {",
" List<String> lines = Splitter.onPattern(\"\\\\r?\\\\n\").splitToList(input);",
" System.err.println(lines.get(0));",
" }",
"}")
.doTest();
}
@Test
public void escape() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" String[] pieces = \"\".split(\"\\n\\t\\r\\f\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"class Test {",
" void f() {",
" Iterable<String> pieces = Splitter.on(\"\\n\\t\\r\\f\").split(\"\");",
" }",
"}")
.doTest();
}
@Test
public void immediateArrayAccess() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" String x = \"\".split(\"c\")[0];",
" x = \"\".split(\"c\")[1];",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"import com.google.common.collect.Iterables;",
"class Test {",
" void f() {",
" String x = Iterables.get(Splitter.on('c').split(\"\"), 0);",
" x = Iterables.get(Splitter.on('c').split(\"\"), 1);",
" }",
"}")
.doTest();
}
@Test
public void stringSplitPositive() {
CompilationTestHelper.newInstance(StringSplitter.class, getClass())
.addSourceFile("StringSplitterPositiveCases.java")
.doTest();
}
@Test
public void stringSplitNegative() {
CompilationTestHelper.newInstance(StringSplitter.class, getClass())
.addSourceFile("StringSplitterNegativeCases.java")
.doTest();
}
@Ignore("b/112270644")
@Test
public void noSplitterOnClassPath() {
testHelper
.addInputLines(
"Test.java",
"class Test {",
" void f() {",
" for (String s : \"\".split(\":\")) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" void f() {",
" for (String s : \"\".split(\":\", -1)) {}",
" }",
"}")
.setArgs("-cp", ":")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void patternSplit() {
testHelper
.addInputLines(
"Test.java",
"import java.util.regex.Pattern;",
"class Test {",
" void f() {",
" String x = Pattern.compile(\"\").split(\"c\")[0];",
" for (String s : Pattern.compile(\"\").split(\":\")) {}",
" String[] xs = Pattern.compile(\"c\").split(\"\");",
" xs[0] = null;",
" System.err.println(xs[0]);",
" String[] pieces = Pattern.compile(\":\").split(\"\");",
" for (int i = 0; i < pieces.length; i++) {}",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Splitter;",
"import com.google.common.collect.Iterables;",
"import java.util.ArrayList;",
"import java.util.List;",
"import java.util.regex.Pattern;",
"",
"class Test {",
" void f() {",
" String x = Iterables.get(Splitter.on(Pattern.compile(\"\")).split(\"c\"), 0);",
" for (String s : Splitter.on(Pattern.compile(\"\")).split(\":\")) {}",
" List<String> xs ="
+ " new ArrayList<>(Splitter.on(Pattern.compile(\"c\")).splitToList(\"\"));",
" xs.set(0, null);",
" System.err.println(xs.get(0));",
" List<String> pieces = Splitter.on(Pattern.compile(\":\")).splitToList(\"\");",
" for (int i = 0; i < pieces.size(); i++) {}",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
}
| 15,187
| 30.774059
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TransientMisuseTest.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;
/** Unit tests for {@link TransientMisuse}. */
@RunWith(JUnit4.class)
public class TransientMisuseTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(TransientMisuse.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains: static String foo1",
" static transient String foo1;",
" // BUG: Diagnostic contains: static String foo2",
" transient static String foo2;",
" // BUG: Diagnostic contains: static final public String foo3",
" static final public transient String foo3 = \"\";",
" // BUG: Diagnostic contains: protected final static String foo4",
" protected final static transient String foo4 = \"\";",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java", //
"class Test {",
" static String foo;",
"}")
.doTest();
}
}
| 1,948
| 31.483333
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BugPatternNamingTest.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;
/** Tests for {@link BugPatternNaming}. */
@RunWith(JUnit4.class)
public final class BugPatternNamingTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(BugPatternNaming.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(BugPatternNaming.class, getClass());
@Test
public void positive() {
helper
.addSourceLines(
"Test.java",
"package com.google.errorprone.bugpatterns;",
"import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;",
"import com.google.errorprone.BugPattern;",
"@BugPattern(name = \"Trololol\", severity = WARNING, summary = \"\")",
"// BUG: Diagnostic contains:",
"class Test extends BugChecker {}")
.doTest();
}
@Test
public void negative() {
helper
.addSourceLines(
"Test.java",
"package com.google.errorprone.bugpatterns;",
"import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;",
"import com.google.errorprone.BugPattern;",
"@BugPattern(severity = WARNING, summary = \"\")",
"class Test extends BugChecker {}")
.doTest();
}
@Test
public void nameMatchesClass_removed() {
refactoringHelper
.addInputLines(
"Test.java",
"package com.google.errorprone.bugpatterns;",
"import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;",
"import com.google.errorprone.BugPattern;",
"@BugPattern(name = \"Test\", severity = WARNING, summary = \"\")",
"class Test extends BugChecker {}")
.addOutputLines(
"Test.java",
"package com.google.errorprone.bugpatterns;",
"import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;",
"import com.google.errorprone.BugPattern;",
"@BugPattern(severity = WARNING, summary = \"\")",
"class Test extends BugChecker {}")
.doTest();
}
@Test
public void absentName_negative() {
helper
.addSourceLines(
"Test.java",
"package com.google.errorprone.bugpatterns;",
"import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;",
"import com.google.errorprone.BugPattern;",
"@BugPattern(severity = WARNING, summary = \"\")",
"class Test extends BugChecker {}")
.doTest();
}
}
| 3,445
| 36.053763
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ComparableAndComparatorTest.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 sulku@google.com (Marsela Sulku)
* @author mariasam@google.com (Maria Sam)
*/
@RunWith(JUnit4.class)
public class ComparableAndComparatorTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ComparableAndComparator.class, getClass());
@Test
public void positive() {
compilationHelper.addSourceFile("ComparableAndComparatorPositiveCases.java").doTest();
}
@Test
public void negative() {
compilationHelper.addSourceFile("ComparableAndComparatorNegativeCases.java").doTest();
}
}
| 1,359
| 31.380952
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MissingImplementsComparableTest.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;
/** Unit tests for {@link MissingImplementsComparable} check. */
@RunWith(JUnit4.class)
public final class MissingImplementsComparableTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(MissingImplementsComparable.class, getClass());
@Test
public void flagsMissingImplementsComparable() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" // BUG: Diagnostic contains:",
" public int compareTo(Test o) {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void doesNotFlagImplementsComparable() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test implements Comparable<Test> {",
" @Override",
" public int compareTo(Test o) {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void doesNotFlagComparableSuperType() {
compilationHelper
.addSourceLines("Foo.java", "abstract class Foo<T> implements Comparable<Foo<T>> {}")
.addSourceLines(
"Test.java",
"class Test extends Foo<String> {",
" @Override",
" public int compareTo(Foo<String> o) {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void doesNotFlagImproperCompareTo() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public int compareTo(Object o) {",
" return 0;",
" }",
"}")
.doTest();
}
}
| 2,513
| 27.896552
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ProtoBuilderReturnValueIgnoredTest.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 ProtoBuilderReturnValueIgnored} bugpattern.
*
* @author ghm@google.com (Graeme Morgan)
*/
@RunWith(JUnit4.class)
public final class ProtoBuilderReturnValueIgnoredTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(ProtoBuilderReturnValueIgnored.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(ProtoBuilderReturnValueIgnored.class, getClass());
@Test
public void refactoring() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.protobuf.Duration;",
"final class Test {",
" private void singleField(Duration.Builder proto) {",
" proto.clearSeconds().build();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.protobuf.Duration;",
"final class Test {",
" private void singleField(Duration.Builder proto) {",
" proto.clearSeconds();",
" }",
"}")
.doTest();
}
@Test
public void toBuilderExempted() {
helper
.addSourceLines(
"Test.java",
"import com.google.protobuf.Duration;",
"final class Test {",
" private void singleField(Duration proto) {",
" proto.toBuilder().clearSeconds().build();",
" }",
"}")
.doTest();
}
@Test
public void refactoringReceiverIsOnlyIdentifier() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.protobuf.Duration;",
"final class Test {",
" private void singleField(Duration.Builder proto) {",
" proto.build();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.protobuf.Duration;",
"final class Test {",
" private void singleField(Duration.Builder proto) {",
" }",
"}")
.doTest();
}
@Test
public void refactoringSecondFix() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.protobuf.Duration;",
"final class Test {",
" private void singleField(Duration.Builder proto) {",
" proto.build();",
" }",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkState;",
"import com.google.protobuf.Duration;",
"final class Test {",
" private void singleField(Duration.Builder proto) {",
" checkState(proto.isInitialized());",
" }",
"}")
.setFixChooser(FixChoosers.SECOND)
.doTest();
}
}
| 3,864
| 31.208333
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BooleanParameterTest.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 org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link BooleanParameter}Test */
@RunWith(JUnit4.class)
public class BooleanParameterTest {
@Test
public void refactoring() {
BugCheckerRefactoringTestHelper.newInstance(BooleanParameter.class, getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" Test(boolean foo) {}",
" void f(boolean foo) {}",
" void f(boolean foo, boolean bar) {}",
" void f_boxed(Boolean foo, Boolean bar) {}",
" void g(boolean p, boolean q) {}",
" void h(boolean arg0, boolean arg1) {}",
" {",
" f(/* foo= */ true);",
" f(false); // one arg",
" f(/* foo= */ true, false);",
" f(false, false);",
" f_boxed(false, false);",
" g(false, false); // single-char",
" h(false, false); // synthetic",
" new Test(false);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" Test(boolean foo) {}",
" void f(boolean foo) {}",
" void f(boolean foo, boolean bar) {}",
" void f_boxed(Boolean foo, Boolean bar) {}",
" void g(boolean p, boolean q) {}",
" void h(boolean arg0, boolean arg1) {}",
" {",
" f(/* foo= */ true);",
" f(false); // one arg",
" f(/* foo= */ true, /* bar= */ false);",
" f(/* foo= */ false, /* bar= */ false);",
" f_boxed(/* foo= */ false, /* bar= */ false);",
" g(false, false); // single-char",
" h(false, false); // synthetic",
" new Test(/* foo= */ false);",
" }",
"}")
.doTest(TEXT_MATCH);
}
@Test
public void dontRefactorNonBooleanParameters() {
BugCheckerRefactoringTestHelper.newInstance(BooleanParameter.class, getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" private static class Generic<T> {",
" private void doIt(T first, T second, T third) {}",
" }",
" void f(Object foo, Object bar) {}",
" {",
" Generic<Boolean> myGeneric = new Generic<>();",
" myGeneric.doIt(false, false, false);",
" f(false, false);",
" }",
"}")
.expectUnchanged()
.doTest(TEXT_MATCH);
}
@Test
public void considerAtomicBooleanSelfDocumenting() {
CompilationTestHelper.newInstance(BooleanParameter.class, getClass())
.addSourceLines(
"Test.java",
"import java.util.concurrent.atomic.AtomicBoolean;",
"class Test {",
" private static final AtomicBoolean b = new AtomicBoolean(false);",
"}")
.doTest();
}
}
| 3,892
| 34.715596
| 88
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DuplicateMapKeysTest.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;
/**
* Unit tests for {@link DuplicateMapKeys} check.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@RunWith(JUnit4.class)
public class DuplicateMapKeysTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(DuplicateMapKeys.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"import static java.util.Map.entry;",
"import java.util.Map;",
"class A {",
" public static void test() {",
" // BUG: Diagnostic contains: Foo",
" Map<String, String> map = Map.ofEntries(",
" entry(\"Foo\", \"Bar\"),",
" entry(\"Ping\", \"Pong\"),",
" entry(\"Kit\", \"Kat\"),",
" entry(\"Foo\", \"Bar\"));",
" }",
"}")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"import static java.util.Map.entry;",
"import java.util.Map;",
"class A {",
" public static void test() {",
" Map<String, String> map = Map.ofEntries(",
" entry(\"Foo\", \"Bar\"),",
" entry(\"Ping\", \"Pong\"),",
" entry(\"Kit\", \"Kat\"),",
" entry(\"Food\", \"Bar\"));",
" }",
"}")
.doTest();
}
}
| 2,338
| 29.776316
| 76
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AnnotationValueToStringTest.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 org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link AnnotationValueToString}Test */
@RunWith(JUnit4.class)
public class AnnotationValueToStringTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(AnnotationValueToString.class, getClass());
@Test
public void refactoring() {
testHelper
.addInputLines(
"Test.java",
"import javax.lang.model.element.AnnotationValue;",
"class Test {",
" String f(AnnotationValue av) {",
" return av.toString();",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.auto.common.AnnotationValues;",
"import javax.lang.model.element.AnnotationValue;",
"class Test {",
" String f(AnnotationValue av) {",
" return AnnotationValues.toString(av);",
" }",
"}")
.allowBreakingChanges() // TODO(cushon): remove after the next auto-common release
.doTest();
}
}
| 1,852
| 32.690909
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OptionalNotPresentTest.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)
*/
@RunWith(JUnit4.class)
public class OptionalNotPresentTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(OptionalNotPresent.class, getClass());
@Test
public void negativeCases() {
compilationTestHelper.addSourceFile("OptionalNotPresentNegativeCases.java").doTest();
}
@Test
public void positiveCases() {
compilationTestHelper.addSourceFile("OptionalNotPresentPositiveCases.java").doTest();
}
@Test
public void b80065837() {
compilationTestHelper
.addSourceLines(
"Test.java", //
"import java.util.Optional;",
"import java.util.Map;",
"class Test {",
" <T> Optional<T> f(T t) {",
" return Optional.ofNullable(t);",
" }",
" int g(Map<String, Optional<Integer>> m) {",
" if (!m.get(\"one\").isPresent()) {",
" return m.get(\"two\").get();",
" }",
" return -1;",
" }",
"}")
.doTest();
}
@Test
public void negation_butNotNegatingOptionalCheck() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" int g(Optional<Integer> o) {",
" if (!equals(this) && o.isPresent()) {",
" return o.orElseThrow();",
" }",
" return -1;",
" }",
"}")
.doTest();
}
@Test
public void isEmpty() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" int g(Optional<Integer> o) {",
" if (o.isEmpty()) {",
" // BUG: Diagnostic contains:",
" return o.get();",
" }",
" return -1;",
" }",
"}")
.doTest();
}
@Test
public void orElseThrow() {
compilationTestHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" int g(Optional<Integer> o) {",
" if (o.isEmpty()) {",
" // BUG: Diagnostic contains:",
" return o.orElseThrow();",
" }",
" return -1;",
" }",
"}")
.doTest();
}
}
| 3,331
| 27.724138
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ClassNamedLikeTypeParameterTest.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 ClassNamedLikeTypeParameter} */
@RunWith(JUnit4.class)
public class ClassNamedLikeTypeParameterTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ClassNamedLikeTypeParameter.class, getClass());
@Test
public void positiveCases() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains: ",
" static class A {}",
" // BUG: Diagnostic contains: ",
" static class B2 {}",
" // BUG: Diagnostic contains: ",
" static class FooT {}",
" // BUG: Diagnostic contains: ",
" static class X {}",
"}")
.doTest();
}
@Test
public void negativeCases() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" static class CAPITALT {}",
" static class MyClass {}",
" static class FooBar {}",
" static class HasGeneric<X> {",
" public <T> void genericMethod(X foo, T bar) {}",
" }",
"}")
.doTest();
}
}
| 2,029
| 30.230769
| 87
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.