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/testdata/CollectorShouldNotUseStateNegativeCases.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.testdata; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import java.util.function.BiConsumer; import java.util.stream.Collector; /** * @author sulku@google.com (Marsela Sulku) */ public class CollectorShouldNotUseStateNegativeCases { public void test() { Collector.of( ImmutableList::builder, new BiConsumer<ImmutableList.Builder<Object>, Object>() { private static final String bob = "bob"; @Override public void accept(Builder<Object> objectBuilder, Object o) { if (bob.equals("bob")) { System.out.println("bob"); } else { objectBuilder.add(o); } } }, (left, right) -> left.addAll(right.build()), ImmutableList.Builder::build); } }
1,499
31.608696
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnitParameterMethodNotFoundNegativeCaseBaseClass.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.testdata; import junitparams.JUnitParamsRunner; import org.junit.runner.RunWith; @RunWith(JUnitParamsRunner.class) public abstract class JUnitParameterMethodNotFoundNegativeCaseBaseClass { public Object named1() { return new Object[] {1}; } }
904
31.321429
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfAssignmentNegativeCases.java
/* * Copyright 2011 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.testdata; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Objects.requireNonNull; /** * Tests for self assignment * * @author eaftan@google.com (Eddie Aftandilian) */ public class SelfAssignmentNegativeCases { private int a; private static int b = StaticClass.b; private static final int C = SelfAssignmentNegativeCases.b; private static final int D = checkNotNull(SelfAssignmentNegativeCases.C); private static final int E = requireNonNull(SelfAssignmentNegativeCases.D); private static final int F = StaticClass.getIntArr().length; public void test1(int a) { int b = SelfAssignmentNegativeCases.b; this.a = a; this.a = checkNotNull(a); this.a = requireNonNull(a); } public void test2() { int a = 0; int b = a; a = b; } public void test3() { int a = 10; } public void test4() { int i = 1; i += i; } public void test5(SelfAssignmentNegativeCases n) { a = n.a; } public void test6() { Foo foo = new Foo(); Bar bar = new Bar(); foo.a = bar.a; foo.a = checkNotNull(bar.a); foo.a = requireNonNull(bar.a); } public void test7() { Foobar f1 = new Foobar(); f1.foo = new Foo(); f1.bar = new Bar(); f1.foo.a = f1.bar.a; f1.foo.a = checkNotNull(f1.bar.a); f1.foo.a = requireNonNull(f1.bar.a); } public void test8(SelfAssignmentNegativeCases that) { this.a = that.a; this.a = checkNotNull(that.a); this.a = requireNonNull(that.a); } public void test9(int a) { a += a; } private static class Foo { int a; } private static class Bar { int a; } private static class Foobar { Foo foo; Bar bar; } private static class StaticClass { static int b; public static int[] getIntArr() { return new int[10]; } } }
2,506
21.790909
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit3TestNotRunNegativeCase2.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.testdata; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * JUnit4 test class - we should not issue errors on that. * * @author rburny@google.com (Radoslaw Burny) */ @RunWith(JUnit4.class) public class JUnit3TestNotRunNegativeCase2 { // JUnit4 tests should be ignored, no matter what their names are. @Test public void nameDoesNotStartWithTest() {} @Test public void tesName() {} @Test public void tstName() {} @Test public void TestName() {} }
1,169
25.590909
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsRefactoringMultiple.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.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ class UngroupedOverloadsRefactoringMultiple { public void foo() {} public void foo(int x) {} private static class foo {} public void foo(int x, int y) {} public void bar() {} public static final String BAZ = "baz"; public void foo(int x, int y, int z) {} public void quux() {} public void quux(int x) {} public static final int X = 0; public static final int Y = 1; public void quux(int x, int y) {} private int quux; public void norf() {} public void quux(int x, int y, int z) {} public void thud() {} }
1,275
22.2
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/CheckReturnValueNegativeCases.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.testdata; import com.google.errorprone.annotations.CheckReturnValue; import java.util.function.Supplier; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class CheckReturnValueNegativeCases { public void test1() { test2(); Object obj = new String(); obj.toString(); } @SuppressWarnings("foo") // wrong annotation public void test2() {} @CheckReturnValue private int mustCheck() { return 5; } private int nothingToCheck() { return 42; } private void callRunnable(Runnable runnable) { runnable.run(); } private void testNonCheckedCallsWithMethodReferences() { Object obj = new String(); callRunnable(String::new); callRunnable(this::test2); callRunnable(obj::toString); } private void callSupplier(Supplier<Integer> supplier) { supplier.get(); } public void testResolvedToIntLambda(boolean predicate) { callSupplier(() -> mustCheck()); callSupplier(predicate ? () -> mustCheck() : () -> nothingToCheck()); } public void testMethodReference(boolean predicate) { callSupplier(this::mustCheck); callSupplier(predicate ? this::mustCheck : this::nothingToCheck); } }
1,835
25.228571
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/PrimitiveArrayPassedToVarargsMethodNegativeCases.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.testdata; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class PrimitiveArrayPassedToVarargsMethodNegativeCases { public void intVarargsMethod(int... ints) {} public void intArrayVarargsMethod(int[]... intArrays) {} public void objectVarargsMethodWithMultipleParams(Object obj1, Object... objs) {} public void doIt() { int[] intArray = {1, 2, 3}; intVarargsMethod(intArray); intArrayVarargsMethod(intArray); objectVarargsMethodWithMultipleParams(new Object()); } }
1,165
29.684211
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ImplementAssertionWithChainingNegativeCases.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.testdata; import com.google.common.truth.FailureMetadata; import com.google.common.truth.Subject; /** * @author cpovirk@google.com (Chris Povirk) */ public class ImplementAssertionWithChainingNegativeCases { static final class FooSubject extends Subject { private final Foo actual; private FooSubject(FailureMetadata metadata, Foo actual) { super(metadata, actual); this.actual = actual; } void doesNotHaveString(String other) { if (actual.string().equals(other)) { failWithActual("expected not to have string", other); } } void doesNotHaveInteger(int other) { if (actual.integer() == other) { failWithActual("expected not to have integer", other); } } void hasBoxedIntegerSameInstance(Integer expected) { if (actual.boxedInteger() != expected) { failWithActual("expected to have boxed integer", expected); } } } private static final class Foo { final String string; final int integer; final Integer boxedInteger; Foo(String string, int integer, Integer boxedInteger) { this.string = string; this.integer = integer; this.boxedInteger = boxedInteger; } String string() { return string; } int integer() { return integer; } Integer boxedInteger() { return boxedInteger; } Foo otherFoo() { return this; } } }
2,080
24.691358
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/PreconditionsExpensiveStringNegativeCase2.java
/* * Copyright 2011 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.testdata; import com.google.common.base.Preconditions; /** * Test for methodIs call including string concatenation. (Not yet supported, so this is a negative * case) * * @author sjnickerson@google.com (Simon Nickerson) */ public class PreconditionsExpensiveStringNegativeCase2 { public void error() { int foo = 42; Preconditions.checkState(true, "The foo" + foo + " is not a good foo"); } }
1,061
31.181818
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ChainingConstructorIgnoresParameterPositiveCases.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.testdata; import static com.google.errorprone.bugpatterns.testdata.ChainingConstructorIgnoresParameterPositiveCases.Location.TEST_TARGET; /** * @author cpovirk@google.com (Chris Povirk) */ public class ChainingConstructorIgnoresParameterPositiveCases { static class MissileLauncher { MissileLauncher(Location target, boolean askForConfirmation) {} MissileLauncher(Location target) { this(target, false); } MissileLauncher(boolean askForConfirmation) { // BUG: Diagnostic contains: this(TEST_TARGET, askForConfirmation) this(TEST_TARGET, false); } } static class ClassRatherThanPrimitive { ClassRatherThanPrimitive(String foo, boolean bar) {} ClassRatherThanPrimitive(String foo) { // BUG: Diagnostic contains: this(foo, false) this("default", false); } } static class CallerBeforeCallee { CallerBeforeCallee(String foo) { // BUG: Diagnostic contains: this(foo, false) this("default", false); } CallerBeforeCallee(String foo, boolean bar) {} } static class AssignableButNotEqual { AssignableButNotEqual(Object foo, boolean bar) {} AssignableButNotEqual(String foo) { // BUG: Diagnostic contains: this(foo, false) this("default", false); } } static class HasNestedClassCallerFirst { HasNestedClassCallerFirst(String foo) { // BUG: Diagnostic contains: this(foo, false) this("somethingElse", false); } static class NestedClass {} HasNestedClassCallerFirst(String foo, boolean bar) {} } static class HasNestedClassCalleeFirst { HasNestedClassCalleeFirst(String foo, boolean bar) {} static class NestedClass {} HasNestedClassCalleeFirst(String foo) { // BUG: Diagnostic contains: this(foo, false) this("somethingElse", false); } } static class MultipleQueuedErrors { MultipleQueuedErrors(Location target) { // BUG: Diagnostic contains: this(target, false) this(TEST_TARGET, false); } MultipleQueuedErrors(boolean askForConfirmation) { // BUG: Diagnostic contains: this(TEST_TARGET, askForConfirmation) this(TEST_TARGET, false); } MultipleQueuedErrors(Location target, boolean askForConfirmation) {} } enum Location { TEST_TARGET } }
2,947
27.07619
127
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NestedInstanceOfConditionsNegativeCases.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.testdata; import java.util.ArrayList; import java.util.List; /** * @author mariasam@google.com (Maria Sam) * @author sulku@google.com (Marsela Sulku) */ public class NestedInstanceOfConditionsNegativeCases { public static void nestedInstanceOfPositiveCases() { Object objectA = new Object(); Object objectB = new Object(); // different objects if (objectA instanceof SuperClass) { if (objectB instanceof DisjointClass) { System.out.println("yay"); } } // nested if checks to see if subtype of first if (objectA instanceof SuperClass) { if (objectA instanceof SubClass) { System.out.println("yay"); } } if (objectA instanceof SuperClass) { if (objectA instanceof SubClass) { if (objectB instanceof DisjointClass) { System.out.println("yay"); } } } if (objectA instanceof SuperClass) { if (objectB instanceof DisjointClass) { if (objectA instanceof SubClass) { System.out.println("yay"); } } } if (objectA instanceof SuperClass) { System.out.println("yay"); } else if (objectA instanceof DisjointClass) { System.out.println("boo"); } else if (objectA instanceof String) { System.out.println("aww"); } if (objectA instanceof SuperClass) { objectA = "yay"; if (objectA instanceof String) { System.out.println(); } } if (objectA instanceof SuperClass) { if (objectA instanceof String) { objectA = "yay"; } } List<Object> ls = new ArrayList<Object>(); ls.add("hi"); // even though this could potentially be an error, ls.get(0) can be altered in many ways in // between the two instanceof statements, therefore we do not match this case if (ls.get(0) instanceof String) { if (ls.get(0) instanceof SuperClass) { System.out.println("lol"); } } } /** test class */ public static class SuperClass {} ; /** test class */ public static class SubClass extends SuperClass {} ; /** test class */ public static class DisjointClass {} ; }
2,815
25.566038
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MustBeClosedCheckerPositiveCases.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.testdata; import com.google.errorprone.annotations.MustBeClosed; import java.util.function.Supplier; import java.util.stream.Stream; @SuppressWarnings({"UnusedNestedClass", "UnusedVariable"}) class MustBeClosedCheckerPositiveCases { class DoesNotImplementAutoCloseable { @MustBeClosed // BUG: Diagnostic contains: MustBeClosed should only annotate constructors of AutoCloseables. DoesNotImplementAutoCloseable() {} @MustBeClosed // BUG: Diagnostic contains: MustBeClosed should only annotate methods that return an // AutoCloseable. void doesNotReturnAutoCloseable() {} } class Closeable implements AutoCloseable { @Override public void close() {} public int method() { return 1; } } class Foo { @MustBeClosed Closeable mustBeClosedAnnotatedMethod() { return new Closeable(); } void sameClass() { // BUG: Diagnostic contains: mustBeClosedAnnotatedMethod(); } } class MustBeClosedAnnotatedConstructor extends Closeable { @MustBeClosed MustBeClosedAnnotatedConstructor() {} void sameClass() { // BUG: Diagnostic contains: new MustBeClosedAnnotatedConstructor(); } } void positiveCase1() { // BUG: Diagnostic contains: new Foo().mustBeClosedAnnotatedMethod(); } void positiveCase2() { // BUG: Diagnostic contains: Closeable closeable = new Foo().mustBeClosedAnnotatedMethod(); } void positiveCase3() { try { // BUG: Diagnostic contains: new Foo().mustBeClosedAnnotatedMethod(); } finally { } } void positiveCase4() { try (Closeable c = new Foo().mustBeClosedAnnotatedMethod()) { // BUG: Diagnostic contains: new Foo().mustBeClosedAnnotatedMethod(); } } void positiveCase5() { // BUG: Diagnostic contains: new MustBeClosedAnnotatedConstructor(); } Closeable positiveCase6() { // BUG: Diagnostic contains: return new MustBeClosedAnnotatedConstructor(); } Closeable positiveCase7() { // BUG: Diagnostic contains: return new Foo().mustBeClosedAnnotatedMethod(); } int existingDeclarationUsesVar() { // BUG: Diagnostic contains: var result = new Foo().mustBeClosedAnnotatedMethod(); return 0; } boolean twoCloseablesInOneExpression() { // BUG: Diagnostic contains: return new Foo().mustBeClosedAnnotatedMethod() == new Foo().mustBeClosedAnnotatedMethod(); } void voidLambda() { // Lambda has a fixless finding because no reasonable fix can be suggested. // BUG: Diagnostic contains: Runnable runnable = () -> new Foo().mustBeClosedAnnotatedMethod(); } void expressionLambda() { Supplier<Closeable> supplier = () -> // BUG: Diagnostic contains: new Foo().mustBeClosedAnnotatedMethod(); } void statementLambda() { Supplier<Closeable> supplier = () -> { // BUG: Diagnostic contains: return new Foo().mustBeClosedAnnotatedMethod(); }; } void methodReference() { Supplier<Closeable> supplier = // TODO(b/218377318): BUG: Diagnostic contains: new Foo()::mustBeClosedAnnotatedMethod; } void anonymousClass() { new Foo() { @Override public Closeable mustBeClosedAnnotatedMethod() { // BUG: Diagnostic contains: return new MustBeClosedAnnotatedConstructor(); } }; } void subexpression() { // BUG: Diagnostic contains: new Foo().mustBeClosedAnnotatedMethod().method(); } void ternary(boolean condition) { // BUG: Diagnostic contains: int result = condition ? new Foo().mustBeClosedAnnotatedMethod().method() : 0; } int variableDeclaration() { // BUG: Diagnostic contains: int result = new Foo().mustBeClosedAnnotatedMethod().method(); return result; } void tryWithResources_nonFinal() { Foo foo = new Foo(); // BUG: Diagnostic contains: Closeable closeable = foo.mustBeClosedAnnotatedMethod(); try { closeable = null; } finally { closeable.close(); } } void tryWithResources_noClose() { Foo foo = new Foo(); // BUG: Diagnostic contains: Closeable closeable = foo.mustBeClosedAnnotatedMethod(); try { } finally { } } class CloseableFoo implements AutoCloseable { @MustBeClosed CloseableFoo() {} // Doesn't autoclose Foo on Stream close. Stream<String> stream() { return null; } @Override public void close() {} } void twrStream() { // BUG: Diagnostic contains: try (Stream<String> stream = new CloseableFoo().stream()) {} } void constructorsTransitivelyRequiredAnnotation() { abstract class Parent implements AutoCloseable { @MustBeClosed Parent() {} // BUG: Diagnostic contains: Invoked constructor is marked @MustBeClosed Parent(int i) { this(); } } // BUG: Diagnostic contains: Implicitly invoked constructor is marked @MustBeClosed abstract class ChildDefaultConstructor extends Parent {} abstract class ChildExplicitConstructor extends Parent { // BUG: Diagnostic contains: Invoked constructor is marked @MustBeClosed ChildExplicitConstructor() {} // BUG: Diagnostic contains: Invoked constructor is marked @MustBeClosed ChildExplicitConstructor(int a) { super(); } } } }
6,055
24.338912
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TestNotRunPositiveCase2.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.testdata; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; /** * Mockito test runner that uses JUnit 4. * * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(MockitoJUnitRunner.class) public class JUnit4TestNotRunPositiveCase2 { // BUG: Diagnostic contains: @Test public void testThisIsATest() {} // BUG: Diagnostic contains: @Test public static void testThisIsAStaticTest() {} }
1,083
29.971429
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BanClassLoaderPositiveCases_expected.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.testdata; import static java.rmi.server.RMIClassLoader.loadClass; import com.google.security.annotations.SuppressBanClassLoaderCompletedSecurityReview; import java.lang.invoke.MethodHandles; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; class BanClassLoaderPositiveCases { /** Override loadClass with an insecure implementation. */ // BUG: Diagnostic contains: BanClassLoader @SuppressBanClassLoaderCompletedSecurityReview class InsecureClassLoader extends URLClassLoader { public InsecureClassLoader() { super(new URL[0]); } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { try { addURL(new URL("jar:https://evil.com/bad.jar")); } catch (MalformedURLException e) { } return findClass(name); } } /** Calling static methods in java.rmi.server.RMIClassLoader. */ @SuppressBanClassLoaderCompletedSecurityReview public static final Class<?> loadRMI() throws ClassNotFoundException, MalformedURLException { // BUG: Diagnostic contains: BanClassLoader return loadClass("evil.com", "BadClass"); } /** Calling constructor of java.net.URLClassLoader. */ @SuppressBanClassLoaderCompletedSecurityReview public ClassLoader loadFromURL() throws MalformedURLException { // BUG: Diagnostic contains: BanClassLoader URLClassLoader loader = new URLClassLoader(new URL[] {new URL("jar:https://evil.com/bad.jar")}); return loader; } /** Calling methods of nested class. */ @SuppressBanClassLoaderCompletedSecurityReview public static final Class<?> methodHandlesDefineClass(byte[] bytes) throws IllegalAccessException { // BUG: Diagnostic contains: BanClassLoader return MethodHandles.lookup().defineClass(bytes); } }
2,481
34.971014
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayToStringConcatenationPositiveCases.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.testdata; import java.util.*; /** * @author adgar@google.com (Mike Edgar) */ public class ArrayToStringConcatenationPositiveCases { private static final int[] a = {1, 2, 3}; public void stringLiteralLeftOperandIsArray() { // BUG: Diagnostic contains: Arrays.toString(a) + String b = a + " a string"; } public void stringLiteralRightOperandIsArray() { // BUG: Diagnostic contains: + Arrays.toString(a) String b = "a string" + a; } }
1,116
28.394737
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BadComparableNegativeCases.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.testdata; import java.util.Comparator; /** * @author irogers@google.com (Ian Rogers) */ public class BadComparableNegativeCases { // The corrected cases of the PositiveCases test. static class ComparableTest implements Comparable<ComparableTest> { private final long value = 0; public int compareTo(ComparableTest other) { return Long.compare(value, other.value); } } static class BoxedComparableTest implements Comparable<BoxedComparableTest> { private final Long value = Long.valueOf(0); public int compareTo(BoxedComparableTest other) { return value.compareTo(other.value); } } static final Comparator<Number> COMPARATOR_UNBOXED_INT_CAST = new Comparator<Number>() { public int compare(Number n1, Number n2) { return Long.compare(n1.longValue(), n2.longValue()); } }; static final Comparator<Long> COMPARATOR_BOXED_INT_CAST = new Comparator<Long>() { public int compare(Long n1, Long n2) { return n1.compareTo(n2); } }; // Don't match non-Comparable or Comparator cases. static class NonComparableTest { private final long value = 0; public int compareTo(ComparableTest other) { return (int) (value - other.value); } } static final Object COMPARATOR_LIKE_INT_CAST = new Object() { public int compare(Long n1, Long n2) { return (int) (n1 - n2); } }; // Narrowing conversions that don't follow the long -> int pattern. static final Comparator<Number> COMPARATOR_UNBOXED_NON_PATTERN_LONG_CAST = new Comparator<Number>() { // To match the Comparator API. @Override public int compare(Number n1, Number n2) { return (int) (n1.intValue() - n2.intValue()); } public short compare(int n1, int n2) { return (short) (n1 - n2); } public byte compare(long n1, long n2) { return (byte) (n1 - n2); } }; // Not narrowing conversions. static final Comparator<Number> COMPARATOR_UNBOXED_NON_NARROW_LONG_CAST = new Comparator<Number>() { // To match the Comparator API. @Override public int compare(Number n1, Number n2) { return (int) (n1.intValue() - n2.intValue()); } public long compare(long n1, long n2) { return (long) (n1 - n2); } }; static final Comparator<Number> COMPARATOR_UNBOXED_NON_NARROW_INT_CAST = new Comparator<Number>() { public int compare(Number n1, Number n2) { return (int) (n1.intValue() - n2.intValue()); } }; static final Comparator<Number> COMPARATOR_UNBOXED_NON_NARROW_SHORT_CAST = new Comparator<Number>() { // To match the Comparator API. @Override public int compare(Number n1, Number n2) { return (int) (n1.intValue() - n2.intValue()); } public short compare(short n1, short n2) { return (short) (n1 - n2); } }; static final Comparator<Number> COMPARATOR_UNBOXED_NON_NARROW_BYTE_CAST = new Comparator<Number>() { // To match the Comparator API. @Override public int compare(Number n1, Number n2) { return (int) (n1.intValue() - n2.intValue()); } public byte compare(byte n1, byte n2) { return (byte) (n1 - n2); } }; // Not signed conversions. static final Comparator<Number> COMPARATOR_UNBOXED_NON_NARROW_CHAR_CAST = new Comparator<Number>() { @Override public int compare(Number n1, Number n2) { return (char) (n1.shortValue() - n2.shortValue()); } public char compare(char n1, char n2) { return (char) (n1 - n2); } public char compare(byte n1, byte n2) { return (char) (n1 - n2); } }; }
4,572
28.694805
79
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/InsecureCipherModeNegativeCases.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.testdata; import java.security.KeyFactory; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import javax.crypto.Cipher; import javax.crypto.KeyAgreement; import javax.crypto.NoSuchPaddingException; /** * @author avenet@google.com (Arnaud J. Venet) */ public class InsecureCipherModeNegativeCases { static Cipher aesCipher; static { // We don't handle any exception as this code is not meant to be executed. try { aesCipher = Cipher.getInstance("AES/CBC/NoPadding"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static final String AES_STRING = "AES/CBC/NoPadding"; static Cipher aesCipherWithConstantString; static { try { aesCipherWithConstantString = Cipher.getInstance(AES_STRING); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher aesCipherWithProvider; static { try { aesCipherWithProvider = Cipher.getInstance("AES/CBC/NoPadding", "My Provider"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchProviderException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher arc4CipherConscrypt; static { try { arc4CipherConscrypt = Cipher.getInstance("ARC4", "Conscrypt"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchProviderException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher rc4CipherJsch; static { try { rc4CipherJsch = Cipher.getInstance("RC4", "JSch"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchProviderException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher arcfourCipherSunJce; static { try { arcfourCipherSunJce = Cipher.getInstance("ARCFOUR/ECB/NoPadding"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher desCipher; static { try { desCipher = Cipher.getInstance("DES/CBC/NoPadding"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher rsaCipher; static { try { rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher aesWrapCipher; static { try { aesWrapCipher = Cipher.getInstance("AESWrap/ECB/NoPadding"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } public void ellipticCurveDiffieHellman() { KeyFactory keyFactory; KeyAgreement keyAgreement; KeyPairGenerator keyPairGenerator; final String ecdh = "ECDH"; try { keyFactory = KeyFactory.getInstance(ecdh); keyAgreement = KeyAgreement.getInstance("ECDH"); keyPairGenerator = KeyPairGenerator.getInstance("EC" + "DH"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } } }
5,444
32.819876
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/InconsistentCapitalizationNegativeCases.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.testdata; /** Negative cases for {@link com.google.errorprone.bugpatterns.InconsistentCapitalizationTest}. */ public class InconsistentCapitalizationNegativeCases { public void doesntConflictWithOtherVariables() { int aa; int aA; } public void doesntConflictWithVariableOutOfScope() { if (true) { int a; } if (true) { int a; } } public void doesntConflictBetweenForVariables() { for (int i = 0; i < 1; i++) {} for (int i = 0; i < 1; i++) {} } private class DoesntConflictBetweenMethods { int a; void a() {} void b(int baba) { int c = baba; if (c == baba) {} } void c() { int c; } } private static class DoesntConflictWithClass { static int B; static class A { static int A; } class B {} } private static class DoesAllowUpperCaseStaticVariable { static int A; void method() { int a; } } private enum DoesntConflictWithUpperCaseEnum { TEST; private Object test; } public void doesntConflictWithMethodParameter(long aa) { int aA; } private class DoesntConflictWithConstructorParameter { DoesntConflictWithConstructorParameter(Object aa) { Object aA; } } private class DoesntConflictOutOfScope { class A { private Object aaa; private Object aab; } class B { private Object aaA; void method(String aaB) { char aAb; } } } private static class DoesntReplaceMember { class A { Object aa; Object ab; void method() { B b = new B(); aa = b.aA; ab = b.aB.aA; new B().aA(); aa.equals(ab); aa.equals(b.aB.aA); aa.equals(b.aB); } } class B { Object aA; C aB = new C(); void aA() {} } class C { Object aA; } } class DoesntConflictWithNested { Object aa; Object ab; class Nested { Object aB; Nested(Object aa) { DoesntConflictWithNested.this.aa = aa; } class Nested2 { Object aB; Nested2(Object aa) { DoesntConflictWithNested.this.aa = aa; } } } } static class DoesntFixExternalParentClassFieldMatch { static class Parent { Object aa; } static class Child extends Parent { Child(Object aA) { aa = aA; } } } }
3,100
16.72
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsRefactoringInterleaved.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.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ class UngroupedOverloadsRefactoringInterleaved { public void foo() {} public void baz() {} public void bar() {} public void foo(int x) {} public void baz(int x) {} public void foo(int x, int y) {} public void quux() {} public void baz(int x, int y) {} public void quux(int x) {} public void bar(int x) {} public void quux(int x, int y) {} public void foo(int x, int y, int z) {} public void bar(int x, int y) {} }
1,176
22.54
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/PreconditionsInvalidPlaceholderNegativeCase1.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.testdata; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Preconditions; public class PreconditionsInvalidPlaceholderNegativeCase1 { Integer foo; public void checkPositive(int x) { checkArgument(x > 0, "%s > 0", x); } public void checkTooFewArgs(int x) { checkArgument(x > 0, "%s %s", x); } public void checkFoo() { Preconditions.checkState(foo.intValue() == 0, "foo must be equal to 0 but was %s", foo); } public static void checkNotNull(Object foo, String bar, Object baz) {} public void checkSelf() { checkNotNull(foo, "Foo", this); } }
1,283
28.181818
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SizeGreaterThanOrEqualsZeroPositiveCases.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.testdata; import com.google.common.collect.Iterables; import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; /** * @author glorioso@google.com (Nick Glorioso) */ public class SizeGreaterThanOrEqualsZeroPositiveCases { private List<Integer> intList = new ArrayList<>(); private Set<Integer> intSet = new HashSet<>(); private Map<Integer, Integer> intMap = new HashMap<>(); private Collection<Integer> intCollection = intList; public boolean collectionSize() { // BUG: Diagnostic contains: !intList.isEmpty() boolean foo = intList.size() >= 0; // BUG: Diagnostic contains: !intSet.isEmpty() foo = intSet.size() >= 0; // BUG: Diagnostic contains: !intSet.isEmpty() foo = 0 <= intSet.size(); // BUG: Diagnostic contains: !intMap.isEmpty() foo = intMap.size() >= 0; // BUG: Diagnostic contains: !intCollection.isEmpty() foo = intCollection.size() >= 0; // Yes, that works as java code // BUG: Diagnostic contains: !new ArrayList<Integer>().isEmpty() if (new ArrayList<Integer>().size() >= 0) {} CollectionContainer baz = new CollectionContainer(); // BUG: Diagnostic contains: !baz.intList.isEmpty() if (baz.intList.size() >= 0) {} // BUG: Diagnostic contains: !baz.getIntList().isEmpty() if (baz.getIntList().size() >= 0) {} // BUG: Diagnostic contains: !Iterables.isEmpty(baz.getIntList()) foo = Iterables.size(baz.getIntList()) >= 0; return foo; } public void stringLength() { String myString = "foo"; CharSequence charSequence = myString; StringBuffer stringBuffer = new StringBuffer(myString); StringBuilder stringBuilder = new StringBuilder(myString); boolean foo = false; // BUG: Diagnostic contains: !myString.isEmpty() foo = myString.length() >= 0; // BUG: Diagnostic contains: !"My String Literal".isEmpty() foo = "My String Literal".length() >= 0; // BUG: Diagnostic contains: !myString.trim().substring(0).isEmpty(); foo = myString.trim().substring(0).length() >= 0; // BUG: Diagnostic contains: charSequence.length() > 0 foo = charSequence.length() >= 0; // BUG: Diagnostic contains: stringBuffer.length() > 0 foo = stringBuffer.length() >= 0; // BUG: Diagnostic contains: 0 < stringBuffer.length() foo = 0 <= stringBuffer.length(); // BUG: Diagnostic contains: stringBuilder.length() > 0 foo = stringBuilder.length() >= 0; } private static int[] staticIntArray; private int[] intArray; private boolean[][] twoDarray; public boolean arrayLength() { // BUG: Diagnostic contains: intArray.length > 0 boolean foo = intArray.length >= 0; // BUG: Diagnostic contains: twoDarray.length > 0 foo = twoDarray.length >= 0; // BUG: Diagnostic contains: staticIntArray.length > 0 foo = staticIntArray.length >= 0; // BUG: Diagnostic contains: twoDarray[0].length > 0 foo = twoDarray[0].length >= 0; // BUG: Diagnostic contains: 0 < twoDarray[0].length foo = 0 <= twoDarray[0].length; // BUG: Diagnostic contains: (((((twoDarray))))).length > 0 foo = (((((twoDarray))))).length >= 0; return foo; } public void protoCount(TestProtoMessage msg) { boolean foo; // BUG: Diagnostic contains: foo = !msg.getMultiFieldList().isEmpty(); foo = msg.getMultiFieldCount() >= 0; // BUG: Diagnostic contains: foo = !msg.getMultiFieldList().isEmpty(); foo = 0 <= msg.getMultiFieldCount(); // BUG: Diagnostic contains: foo = !(((((msg))))).getMultiFieldList().isEmpty(); foo = (((((msg))))).getMultiFieldCount() >= 0; // BUG: Diagnostic contains: if (!this.getMsg(msg).get().getMultiFieldList().isEmpty()) { if (this.getMsg(msg).get().getMultiFieldCount() >= 0) { foo = true; } } private Optional<TestProtoMessage> getMsg(TestProtoMessage msg) { return Optional.of(msg); } private static class CollectionContainer { List<Integer> intList; List<Integer> getIntList() { return intList; } } }
4,898
30.403846
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TestNotRunNegativeCase5.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.testdata; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Methods that override methods with @Test should not trigger an error (JUnit 4 will run them). * * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class JUnit4TestNotRunNegativeCase5 extends JUnit4TestNotRunBaseClass { @Override public void testSetUp() {} @Override public void testTearDown() {} @Override public void testOverrideThis() {} }
1,125
28.631579
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MultipleUnaryOperatorsInMethodCallNegativeCases.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.testdata; /** * @author sulku@google.com (Marsela Sulku) */ public class MultipleUnaryOperatorsInMethodCallNegativeCases { public static void tests(int a, int b, int[] xs) { testMethod(a, b); testMethod(a + 1, b); testMethod(b, a + 1); testMethod(a++, b); testMethod(--a, b); testMethod(a, b--); testMethod(a, ++b); testMethod(xs[0]++, xs[0]++); } public static void testMethod(int one, int two) {} }
1,093
30.257143
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/LambdaFunctionalInterfaceNegativeCases.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.testdata; import java.util.function.Function; import java.util.function.IntToDoubleFunction; public class LambdaFunctionalInterfaceNegativeCases { public double fooIntToDoubleFunction(int x, Function<Integer, Double> fn) { return fn.apply(x).doubleValue(); } public void fooIntToDoubleUtil(int y, IntToDoubleFunction fn) { fn.applyAsDouble(y); } public long fooIntToLongFunction(int x, Function<Integer, Long> fn) { return fn.apply(x); } public long fooIntToIntFunction(int x, Function<Integer, Long> fn) { return fn.apply(x); } public double fooDoubleToDoubleFunction(double x, Function<Double, Double> fn) { return fn.apply(x); } public int fooDoubleToIntFunction(double x, Function<Double, Integer> fn) { return fn.apply(x); } public String add(String string, Function<String, String> func) { return func.apply(string); } public void fooInterface(String str, Function<Integer, Double> func) {} public double fooDouble(double x, Function<Double, Integer> fn) { return fn.apply(x); } public static class WithCallSiteExplicitFunction { public static double generateDataSeries(Function<Double, Double> curveFunction) { final double scale = 100; final double modX = 2.0; return modX / curveFunction.apply(scale); } // call site private static double generateSpendCurveForMetric(double curved) { // explicit Function variable creation Function<Double, Double> curveFunction = x -> Math.pow(x, 1 / curved) * 100; return generateDataSeries(curveFunction); } } public static class WithCallSiteAnonymousFunction { public static double findOptimalMu(Function<Double, Long> costFunc, double mid) { return costFunc.apply(mid); } // call site: anonymous Function public Double getMu() { return findOptimalMu( new Function<Double, Long>() { @Override public Long apply(Double mu) { return 0L; } }, 3.0); } } public static class WithCallSiteLambdaFunction { public static double findOptimalMuLambda(Function<Double, Long> costFunc, double mid) { return costFunc.apply(mid); } // call site: anonymous Function public Double getMu() { return findOptimalMuLambda(mu -> 0L, 3.0); } } }
3,018
27.752381
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ThrowsUncheckedExceptionPositiveCases.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.testdata; import java.io.IOException; /** * @author yulissa@google.com (Yulissa Arroyo-Paredes) */ public class ThrowsUncheckedExceptionPositiveCases { // BUG: Diagnostic contains: 'public void doSomething() {' public void doSomething() throws IllegalArgumentException { throw new IllegalArgumentException("thrown"); } // BUG: Diagnostic contains: 'public void doSomethingElse() {' public void doSomethingElse() throws RuntimeException, NullPointerException { throw new NullPointerException("thrown"); } // BUG: Diagnostic contains: Unchecked exceptions do not need to be declared public void doMore() throws RuntimeException, IOException { throw new IllegalArgumentException("thrown"); } // BUG: Diagnostic contains: Unchecked exceptions do not need to be declared public void doEverything() throws RuntimeException, IOException, IndexOutOfBoundsException { throw new IllegalArgumentException("thrown"); } // BUG: Diagnostic contains: 'public void doBetter() {' public void doBetter() throws RuntimeException, AssertionError { throw new RuntimeException("thrown"); } }
1,778
35.306122
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayHashCodePositiveCases.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.testdata; import com.google.common.base.Objects; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class ArrayHashCodePositiveCases { private Object[] objArray = {1, 2, 3}; private String[] stringArray = {"1", "2", "3"}; private int[] intArray = {1, 2, 3}; private byte[] byteArray = {1, 2, 3}; private int[][] multidimensionalIntArray = {{1, 2, 3}, {4, 5, 6}}; private String[][] multidimensionalStringArray = {{"1", "2", "3"}, {"4", "5", "6"}}; public void objectHashCode() { int hashCode; // BUG: Diagnostic contains: Arrays.hashCode(objArray) hashCode = objArray.hashCode(); // BUG: Diagnostic contains: Arrays.hashCode(stringArray) hashCode = stringArray.hashCode(); // BUG: Diagnostic contains: Arrays.hashCode(intArray) hashCode = intArray.hashCode(); // BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalIntArray) hashCode = multidimensionalIntArray.hashCode(); // BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalStringArray) hashCode = multidimensionalStringArray.hashCode(); } public void guavaObjectsHashCode() { int hashCode; // BUG: Diagnostic contains: Arrays.hashCode(intArray) hashCode = Objects.hashCode(intArray); // BUG: Diagnostic contains: Arrays.hashCode(byteArray) hashCode = Objects.hashCode(byteArray); // BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalIntArray) hashCode = Objects.hashCode(multidimensionalIntArray); // BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalStringArray) hashCode = Objects.hashCode(multidimensionalStringArray); } public void varargsHashCodeOnMoreThanOneArg() { int hashCode; // BUG: Diagnostic contains: Objects.hashCode(Arrays.hashCode(objArray), // Arrays.hashCode(intArray)) hashCode = Objects.hashCode(objArray, intArray); // BUG: Diagnostic contains: Objects.hashCode(Arrays.hashCode(stringArray), // Arrays.hashCode(byteArray)) hashCode = Objects.hashCode(stringArray, byteArray); Object obj1 = new Object(); Object obj2 = new Object(); // BUG: Diagnostic contains: Objects.hashCode(obj1, obj2, Arrays.hashCode(intArray)) hashCode = Objects.hashCode(obj1, obj2, intArray); // BUG: Diagnostic contains: Objects.hashCode(obj1, Arrays.hashCode(intArray), obj2) hashCode = Objects.hashCode(obj1, intArray, obj2); // BUG: Diagnostic contains: Objects.hashCode(Arrays.hashCode(intArray), obj1, obj2) hashCode = Objects.hashCode(intArray, obj1, obj2); // BUG: Diagnostic contains: Objects.hashCode(obj1, obj2, // Arrays.deepHashCode(multidimensionalIntArray)) hashCode = Objects.hashCode(obj1, obj2, multidimensionalIntArray); // BUG: Diagnostic contains: Objects.hashCode(obj1, obj2, // Arrays.deepHashCode(multidimensionalStringArray)) hashCode = Objects.hashCode(obj1, obj2, multidimensionalStringArray); } }
3,582
40.662791
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MissingFailPositiveCases.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.testdata; import junit.framework.TestCase; import org.junit.Assert; import org.mockito.Mockito; /** Test cases for missing fail */ public class MissingFailPositiveCases extends TestCase { private boolean foo = true; public void expectedException_emptyCatch() { try { // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception expected) { } } public void catchAssert() { try { // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception e) { assertDummy(); } } public void catchVerify() { try { // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception e) { verifyDummy(); } } public void expectedException_throwOutsideTryTree() throws Exception { try { // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception expected) { } throw new Exception(); } public void expectedException_assertLastCall() throws Exception { try { dummyMethod(); // BUG: Diagnostic contains: fail() assertDummy(); } catch (Exception expected) { } throw new Exception(); } public void expectedException_fieldAssignmentInCatch() { try { // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception expected) { foo = true; } } public void catchAssert_noopAssertLastCall() { try { dummyMethod(); // BUG: Diagnostic contains: fail() Assert.assertTrue(true); } catch (Exception e) { assertDummy(); } } public void assertInCatch_verifyNotLastStatement() { try { Mockito.verify(new Dummy()).dummy(); // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception e) { assertDummy(); } } public void assertInCatch_verifyInCatch() { try { // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception e) { assertDummy(); Mockito.verify(new Dummy()).dummy(); } } public void expectedException_logInTry() { try { new Logger().log(); // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception expected) { foo = true; } } /** Sameple inner class. */ public static class Inner { public void expectedException_emptyCatch() { try { // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception expected) { } } } private static class Dummy { String dummy() { return ""; } } private static class Logger { void log() {} ; void info() {} ; } private static void dummyMethod() {} private static void assertDummy() {} private static void verifyDummy() {} }
3,423
21.090323
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/DeadExceptionPositiveCases.java
/* * Copyright 2011 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.testdata; public class DeadExceptionPositiveCases { public void runtimeException() { // BUG: Diagnostic contains: throw new RuntimeException new RuntimeException("Not thrown, and reference lost"); } public void error() { // BUG: Diagnostic contains: throw new AssertionError new AssertionError("Not thrown, and reference lost"); } public void fixIsToDeleteTheFirstStatement() { // BUG: Diagnostic contains: remove this line new IllegalArgumentException("why is this here?"); int i = 1; System.out.println("i = " + i); if (true) { // BUG: Diagnostic contains: remove this line new RuntimeException("oops"); System.out.println("another statement after exception"); } switch (0) { default: // BUG: Diagnostic contains: remove this line new RuntimeException("oops"); System.out.println("another statement after exception"); } } public void firstStatementWithNoSurroundingBlock() { if (true) // BUG: Diagnostic contains: throw new InterruptedException new InterruptedException("this should be thrown"); if (true) return; else // BUG: Diagnostic contains: throw new ArithmeticException new ArithmeticException("should also be thrown"); switch (4) { case 4: System.out.println("4"); break; default: // BUG: Diagnostic contains: throw new IllegalArgumentException new IllegalArgumentException("should be thrown"); } } public void testLooksLikeAJunitTestMethod() { // BUG: Diagnostic contains: throw new RuntimeException new RuntimeException("Not thrown, and reference lost"); } { // BUG: Diagnostic contains: throw new Exception new Exception(); } }
2,427
29.35
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NestedInstanceOfConditionsPositiveCases.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.testdata; /** * @author mariasam@google.com (Maria Sam) * @author sulku@google.com (Marsela Sulku) */ public class NestedInstanceOfConditionsPositiveCases { public static void nestedInstanceOfPost() { Object foo = new ClassA(); Object bar = new ClassB(); // BUG: Diagnostic contains: Nested instanceOf conditions of disjoint types if (foo instanceof ClassA) { if (foo instanceof ClassB) { System.out.println("test"); } } // BUG: Diagnostic contains: Nested instanceOf conditions of disjoint types if (foo instanceof ClassA) { System.out.println("test"); if (foo instanceof ClassB) { System.out.println("test"); } System.out.println("test"); } // BUG: Diagnostic contains: Nested instanceOf conditions of disjoint types if (foo instanceof ClassA) { // BUG: Diagnostic contains: Nested instanceOf conditions of disjoint types if (foo instanceof ClassA) { if (foo instanceof ClassB) { System.out.println("test"); } } } // BUG: Diagnostic contains: Nested instanceOf conditions of disjoint types if (foo instanceof ClassA) { // BUG: Diagnostic contains: Nested instanceOf conditions of disjoint types if (foo instanceof ClassB) { if (foo instanceof ClassC) { System.out.println("test"); } } } // BUG: Diagnostic contains: Nested instanceOf conditions if (foo instanceof ClassA) { if (bar instanceof ClassB) { if (foo instanceof ClassC) { System.out.println("test"); } } } if (foo instanceof ClassA) { System.out.println("yay"); // BUG: Diagnostic contains: Nested instanceOf conditions } else if (foo instanceof ClassB) { if (foo instanceof ClassC) { System.out.println("uh oh"); } } } static class ClassA {} static class ClassB {} static class ClassC {} }
2,615
28.393258
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UnnecessaryLongToIntConversionPositiveCases.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.testdata; import com.google.common.primitives.Ints; /** Positive cases for {@link com.google.errorprone.bugpatterns.UnnecessaryLongToIntConversion}. */ public class UnnecessaryLongToIntConversionPositiveCases { static void acceptsLong(long value) {} static void acceptsMultipleParams(int intValue, long longValue) {} public void longToIntForLongParam() { long x = 1; // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong((int) x); } public void longObjectToIntForLongParam() { Long x = Long.valueOf(1); // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(x.intValue()); } public void convertMultipleArgs() { long x = 1; // The method expects an int for the first parameter and a long for the second paremeter. // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsMultipleParams(Ints.checkedCast(x), Ints.checkedCast(x)); } // The following test cases test various conversion methods, including an unchecked cast. public void castToInt() { long x = 1; // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong((int) x); } public void checkedCast() { long x = 1; // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(Ints.checkedCast(x)); } public void toIntExact() { long x = 1; // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(Math.toIntExact(x)); } public void toIntExactWithLongObject() { Long x = Long.valueOf(1); // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(Math.toIntExact(x)); } public void intValue() { Long x = Long.valueOf(1); // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(x.intValue()); } }
2,462
30.576923
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverridesPositiveCase3.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.testdata; /** * This tests the case where there is a chain of method overrides where the varargs constraint is * not met, and the root has an array parameter. TODO(cushon): The original implementation tried to * be clever and make this consistent, but didn't handle multiple interface inheritance. * * @author cushon@google.com (Liam Miller-Cushon) */ public class OverridesPositiveCase3 { abstract class Base { abstract void arrayMethod(Object[] xs); } abstract class SubOne extends Base { @Override // BUG: Diagnostic contains: abstract void arrayMethod(Object... newNames); } abstract class SubTwo extends SubOne { @Override // BUG: Diagnostic contains: abstract void arrayMethod(Object[] xs); } abstract class SubThree extends SubTwo { @Override // BUG: Diagnostic contains: abstract void arrayMethod(Object... newNames); } }
1,537
31.723404
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MisusedWeekYearNegativeCases.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.testdata; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Locale; public class MisusedWeekYearNegativeCases { void testLiteralPattern() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); simpleDateFormat = new SimpleDateFormat("MM-dd"); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", DateFormatSymbols.getInstance()); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); // Don't flag if the pattern contains "ww", the week-in-year specifier. simpleDateFormat = new SimpleDateFormat("YYYY-ww"); simpleDateFormat = new SimpleDateFormat("YY-ww"); simpleDateFormat = new SimpleDateFormat("Y-ww"); simpleDateFormat = new SimpleDateFormat("Yw"); } void testLiteralPatternWithFolding() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy" + "-MM-dd"); } private static final String WEEK_YEAR_PATTERN = "yyyy-MM-dd"; void testConstantPattern() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WEEK_YEAR_PATTERN); } private static class MySimpleDateFormat extends SimpleDateFormat { public MySimpleDateFormat(String pattern) { super(pattern); } } // Don't match on subtypes, since we don't know what their applyPattern and // applyLocalizedPattern methods might do. void testSubtype() { MySimpleDateFormat mySdf = new MySimpleDateFormat("YYYY-MM-dd"); mySdf.applyPattern("YYYY-MM-dd"); mySdf.applyLocalizedPattern("YYYY-MM-dd"); } }
2,196
35.016393
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfEqualsGuavaNegativeCases.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.testdata; import com.google.common.base.Objects; /** * @author bhagwani@google.com (Sumit Bhagwani) */ public class SelfEqualsGuavaNegativeCases { private String field; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SelfEqualsGuavaNegativeCases other = (SelfEqualsGuavaNegativeCases) o; return Objects.equal(field, other.field); } @Override public int hashCode() { return field != null ? field.hashCode() : 0; } }
1,218
26.088889
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MultipleUnaryOperatorsInMethodCallPositiveCases.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.testdata; /** * @author sulku@google.com (Marsela Sulku) */ public class MultipleUnaryOperatorsInMethodCallPositiveCases { /** these cases do not have suggested fixes */ public static void tests(int a, int b) { // BUG: Diagnostic contains: Avoid having multiple unary operators acting twoArgs(a++, a--); // BUG: Diagnostic contains: Avoid having multiple unary operators acting twoArgs(a--, ++a); // BUG: Diagnostic contains: Avoid having multiple unary operators acting twoArgs(++a, a++); // BUG: Diagnostic contains: Avoid having multiple unary operators acting twoArgs(--a, --a); // BUG: Diagnostic contains: Avoid having multiple unary operators acting threeArgs(a++, b++, b++); // BUG: Diagnostic contains: Avoid having multiple unary operators acting threeArgs(a++, b, a++); // BUG: Diagnostic contains: Avoid having multiple unary operators acting threeArgs(++a, b++, --b); // BUG: Diagnostic contains: Avoid having multiple unary operators acting threeArgs(++a, a++, b); // BUG: Diagnostic contains: Avoid having multiple unary operators acting threeArgs(++a, a++, a); // BUG: Diagnostic contains: Avoid having multiple unary operators acting threeArgs(++a, a++, a--); } public static void twoArgs(int a, int b) {} public static void threeArgs(int a, int b, int c) {} public static int someFunction(int a) { return 0; } }
2,086
36.267857
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/AsyncFunctionReturnsNullPositiveCases.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.testdata; import static com.google.common.util.concurrent.Futures.immediateFuture; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.ListenableFuture; /** Positive cases for {@link AsyncFunctionReturnsNull}. */ public class AsyncFunctionReturnsNullPositiveCases { static void listenableFutures() { new AsyncFunction<String, Object>() { @Override public ListenableFuture<Object> apply(String input) throws Exception { // BUG: Diagnostic contains: immediateFuture(null) return null; } }; new AsyncFunction<Object, String>() { @Override public ListenableFuture<String> apply(Object o) { if (o instanceof String) { return immediateFuture((String) o); } // BUG: Diagnostic contains: immediateFuture(null) return null; } }; } static class MyAsyncFunction implements AsyncFunction<Object, String> { @Override public ListenableFuture<String> apply(Object input) throws Exception { return immediateFuture(input.toString()); } } }
1,750
32.673077
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayHashCodePositiveCases2.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.testdata; import java.util.Objects; /** * Java 7 specific tests * * @author eaftan@google.com (Eddie Aftandilian) */ public class ArrayHashCodePositiveCases2 { private Object[] objArray = {1, 2, 3}; private String[] stringArray = {"1", "2", "3"}; private int[] intArray = {1, 2, 3}; private byte[] byteArray = {1, 2, 3}; private int[][] multidimensionalIntArray = {{1, 2, 3}, {4, 5, 6}}; private String[][] multidimensionalStringArray = {{"1", "2", "3"}, {"4", "5", "6"}}; public void javaUtilObjectsHashCode() { int hashCode; // BUG: Diagnostic contains: Arrays.hashCode(objArray) hashCode = Objects.hashCode(objArray); // BUG: Diagnostic contains: Arrays.hashCode(stringArray) hashCode = Objects.hashCode(stringArray); // BUG: Diagnostic contains: Arrays.hashCode(intArray) hashCode = Objects.hashCode(intArray); // BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalIntArray) hashCode = Objects.hashCode(multidimensionalIntArray); // BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalStringArray) hashCode = Objects.hashCode(multidimensionalStringArray); } public void javaUtilObjectsHash() { int hashCode; // BUG: Diagnostic contains: Arrays.hashCode(intArray) hashCode = Objects.hash(intArray); // BUG: Diagnostic contains: Arrays.hashCode(byteArray) hashCode = Objects.hash(byteArray); // BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalIntArray) hashCode = Objects.hash(multidimensionalIntArray); // BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalStringArray) hashCode = Objects.hash(multidimensionalStringArray); } public void varargsHashCodeOnMoreThanOneArg() { int hashCode; // BUG: Diagnostic contains: Objects.hash(Arrays.hashCode(objArray), Arrays.hashCode(intArray)) hashCode = Objects.hash(objArray, intArray); // BUG: Diagnostic contains: Objects.hash(Arrays.hashCode(stringArray), // Arrays.hashCode(byteArray)) hashCode = Objects.hash(stringArray, byteArray); Object obj1 = new Object(); Object obj2 = new Object(); // BUG: Diagnostic contains: Objects.hash(obj1, obj2, Arrays.hashCode(intArray)) hashCode = Objects.hash(obj1, obj2, intArray); // BUG: Diagnostic contains: Objects.hash(obj1, Arrays.hashCode(intArray), obj2) hashCode = Objects.hash(obj1, intArray, obj2); // BUG: Diagnostic contains: Objects.hash(Arrays.hashCode(intArray), obj1, obj2) hashCode = Objects.hash(intArray, obj1, obj2); // BUG: Diagnostic contains: Objects.hash(obj1, obj2, // Arrays.deepHashCode(multidimensionalIntArray)) hashCode = Objects.hash(obj1, obj2, multidimensionalIntArray); // BUG: Diagnostic contains: Objects.hash(obj1, obj2, // Arrays.deepHashCode(multidimensionalStringArray)) hashCode = Objects.hash(obj1, obj2, multidimensionalStringArray); } }
3,562
39.954023
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsPositiveCasesSingle.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.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ public class UngroupedOverloadsPositiveCasesSingle { public void quux() { foo(); } // BUG: Diagnostic contains: ungrouped overloads of 'foo' public void foo() { foo(42); } // BUG: Diagnostic contains: ungrouped overloads of 'foo' public void foo(int x) { foo(x, x); } public void bar() { bar(42); } public void bar(int x) { foo(x); } // BUG: Diagnostic contains: ungrouped overloads of 'foo' public void foo(int x, int y) { System.out.println(x + y); } public void norf() {} }
1,263
22.849057
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsPositiveCasesInterleaved.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.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ public class UngroupedOverloadsPositiveCasesInterleaved { private int foo; // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x, String z, int y) { System.out.println(String.format("z: %s, x: %d, y: %d", z, x, y)); } public UngroupedOverloadsPositiveCasesInterleaved(int foo) { this.foo = foo; } // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x) { bar(foo, x); } // BUG: Diagnostic contains: ungrouped overloads of 'baz' public void baz(String x) { baz(x, FOO); } // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x, int y) { bar(y, FOO, x); } public static final String FOO = "foo"; // BUG: Diagnostic contains: ungrouped overloads of 'baz' public void baz(String x, String y) { bar(foo, x + y, foo); } public void foo(int x) {} public void foo() { foo(foo); } }
1,655
25.285714
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsNegativeCases.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.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ public class UngroupedOverloadsNegativeCases { private int foo; public UngroupedOverloadsNegativeCases(int foo) { this.foo = foo; } public void bar(int x) { bar(foo, x); } public void bar(int x, String z, int y) { System.out.println(String.format("z: %s, x: %d, y: %d", z, x, y)); } public void bar(int x, int y) { bar(y, FOO, x); } public static class Baz {} public static final String FOO = "foo"; public void baz(String x) { baz(x, FOO); } public void baz(String x, String y) { bar(foo, x + y, foo); } public int foo() { return this.foo; } }
1,340
22.12069
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BadImportPositiveCases.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.testdata; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import org.checkerframework.checker.nullness.qual.Nullable; /** * Tests for {@link BadImport}. * * @author awturner@google.com (Andy Turner) */ class BadImportPositiveCases { public void variableDeclarations() { // Only the first match is reported; but all occurrences are fixed. // BUG: Diagnostic contains: ImmutableList.Builder Builder<String> qualified; Builder raw; } public void variableDeclarationsNestedGenerics() { Builder<Builder<String>> builder1; Builder<Builder> builder1Raw; ImmutableList.Builder<Builder<String>> builder2; ImmutableList.Builder<Builder> builder2Raw; } @Nullable Builder<@Nullable Builder<@Nullable String>> parameterizedWithTypeUseAnnotationMethod() { return null; } public void variableDeclarationsNestedGenericsAndTypeUseAnnotations() { @Nullable Builder<@Nullable String> parameterizedWithTypeUseAnnotation1; @Nullable Builder<@Nullable Builder<@Nullable String>> parameterizedWithTypeUseAnnotation2; } public void newClass() { new Builder<String>(); new Builder<Builder<String>>(); } Builder<String> returnGenericExplicit() { return new Builder<String>(); } Builder<String> returnGenericDiamond() { return new Builder<>(); } Builder returnRaw() { return new Builder(); } void classLiteral() { System.out.println(Builder.class); } }
2,158
27.786667
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OptionalNotPresentNegativeCases.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.testdata; import java.util.Optional; import java.util.function.Predicate; /** Includes true-negative cases and false-positive cases. */ public class OptionalNotPresentNegativeCases { // Test this doesn't trigger NullPointerException private final Predicate<Optional<?>> asField = o -> !o.isPresent(); // False-positive public String getWhenTestedSafe_referenceEquality(Optional<String> optional) { if (!optional.isPresent()) { if (optional == Optional.of("OK")) { // always false // BUG: Diagnostic contains: Optional return optional.get(); } } return ""; } // False-positive public String getWhenTestedSafe_equals(Optional<String> optional) { if (!optional.isPresent()) { if (optional.equals(Optional.of("OK"))) { // always false // BUG: Diagnostic contains: Optional return optional.get(); } } return ""; } public String getWhenPresent_blockReassigned(Optional<String> optional) { if (!optional.isPresent()) { optional = Optional.of("value"); return optional.get(); } return ""; } public String getWhenPresent_localReassigned(Optional<String> optional) { if (!optional.isPresent()) { optional = Optional.of("value"); } return optional.get(); } public String getWhenPresent_nestedCheck(Optional<String> optional) { if (!optional.isPresent() || true) { return optional.isPresent() ? optional.get() : ""; } return ""; } }
2,147
29.253521
80
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TreeToStringNegativeCases.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. */ import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; public class TreeToStringNegativeCases { public static class InnerClass extends BugChecker { private static void foo(VisitorState state) { Tree tree = (Tree) new Object(); state.getSourceForNode(tree); state.getConstantExpression(tree); ((ClassTree) new Object()).getSimpleName().toString(); ASTHelpers.getSymbol(tree).getSimpleName().toString(); } } }
1,220
32.916667
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MultipleParallelOrSequentialCallsPositiveCases.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.testdata; import java.util.Collection; import java.util.List; import java.util.stream.Stream; /** * @author @mariasam (Maria Sam) on 7/6/17. */ class MultipleParallelOrSequentialCallsPositiveCases { public void basicCaseParallel(List<String> list) { // BUG: Diagnostic contains: Did you mean 'list.stream().parallel();'? list.stream().parallel().parallel(); } public void basicCaseParallelNotFirst(List<String> list) { // BUG: Diagnostic contains: Did you mean 'list.stream().parallel().map(m -> m);'? list.stream().map(m -> m).parallel().parallel(); } public void basicCollection(Collection<String> list) { // BUG: Diagnostic contains: Did you mean 'list.stream().parallel();'? list.stream().parallel().parallel(); } public void parallelStream(List<String> list) { // BUG: Diagnostic contains: Did you mean 'list.parallelStream();'? list.parallelStream().parallel().parallel(); } public void basicCaseParallelThisInMethodArg(List<String> list) { // BUG: Diagnostic contains: Did you mean 'this.hello(list.stream().parallel());'? this.hello(list.stream().parallel().parallel()); } public void onlyOneError(List<String> list) { this.hello( // BUG: Diagnostic contains: Multiple calls list.stream().parallel().parallel()); } public void mapMethod(List<String> list) { // BUG: Diagnostic contains: Did you mean 'hello(list.stream().parallel().map(m -> // this.hello(null)));'? hello(list.stream().map(m -> this.hello(null)).parallel().parallel()); } public void betweenMethods(List<String> list) { // BUG: Diagnostic contains: Did you mean 'list.stream().parallel().map(m -> m.toString());'? list.stream().parallel().map(m -> m.toString()).parallel(); } public void basicCaseParallelNotLast(List<String> list) { // BUG: Diagnostic contains: Did you mean 'list.stream().parallel().map(m -> // m.toString()).findFirst();'? list.stream().parallel().map(m -> m.toString()).parallel().findFirst(); } public void basicCaseSequential(List<String> list) { // BUG: Diagnostic contains: Did you mean 'list.stream().sequential().map(m -> m.toString());'? list.stream().sequential().map(m -> m.toString()).sequential(); } public void bothSequentialAndParallel(List<String> list) { // this case is unlikely (wrong, even) but just checking that this works // BUG: Diagnostic contains: Did you mean 'list.stream().sequential().parallel();'? list.stream().sequential().parallel().sequential(); } public void bothSequentialAndParallelMultiple(List<String> list) { // this is even more messed up, this test is here to make sure the checker doesn't throw an // exception // BUG: Diagnostic contains: Multiple calls list.stream().sequential().parallel().sequential().parallel(); } public void parallelMultipleLines(List<String> list) { // BUG: Diagnostic contains: Did you mean 'list.stream().parallel() list.stream().parallel().map(m -> m.toString()).parallel(); } public void multipleParallelCalls(List<String> list) { // BUG: Diagnostic contains: Did you mean 'list.parallelStream();'? list.parallelStream().sequential(); } public String hello(Stream st) { return ""; } public void streamWithinAStream(List<String> list, List<String> list2) { // BUG: Diagnostic contains: Did you mean list.stream() .flatMap(childDir -> list2.stream()) .parallel() .flatMap(a -> list2.stream()) .parallel(); } public void streamWithinAStreamImmediatelyAfterOtherParallel( List<String> list, List<String> list2) { // BUG: Diagnostic contains: Did you mean list.stream().parallel().map(m -> list2.stream().parallel()).parallel(); } public void parallelAndNestedStreams(List<String> list, List<String> list2) { // BUG: Diagnostic contains: Did you mean list.parallelStream() .flatMap(childDir -> list2.stream()) .parallel() .filter(m -> (new TestClass("test")).testClass()) .map( a -> { if (a == null) { return a; } return null; }) .filter(a -> a != null) .flatMap(a -> list2.stream()) .parallel(); } private class TestClass { public TestClass(String con) {} private boolean testClass() { return true; } } }
5,084
33.358108
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverridesPositiveCase5.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.testdata; /** * @author cushon@google.com (Liam Miller-Cushon) */ public class OverridesPositiveCase5 { abstract class Base { abstract void varargsMethod(Object[] xs, Object... ys); abstract void arrayMethod(Object[] xs, Object[] ys); } abstract class Child1 extends Base { @Override // BUG: Diagnostic contains: Did you mean 'abstract void arrayMethod(Object[] xs, Object[] ys);' abstract void arrayMethod(Object[] xs, Object... ys); @Override // BUG: Diagnostic contains: Did you mean 'abstract void varargsMethod(Object[] xs, Object... // ys);' abstract void varargsMethod(Object[] xs, Object[] ys); void foo(Base base) { base.varargsMethod(null, new Object[] {}, new Object[] {}, new Object[] {}, new Object[] {}); } } }
1,432
32.325581
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/HidingFieldNegativeCases.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.testdata; /** * @author sulku@google.com (Marsela Sulku) * @author mariasam@google.com (Maria Sam) */ public class HidingFieldNegativeCases { // base class static class ClassA { public int varOne; } // subclass with member variables of different names static class ClassB extends ClassA { private String varTwo; private int varThree; public static int varFour; public int varFive; } // subclass with initialized member variable of different name static class ClassC extends ClassB { // publicly-visible static members in superclasses are pretty uncommon, and generally // referred to by qualification, so this 'override' is OK private String varFour = "Test"; // The supertype's visibility is private, so this redeclaration is OK. private int varThree; // warning suppressed when overshadowing variable in parent @SuppressWarnings("HidingField") public int varFive; // warning suppressed when overshadowing variable in grandparent @SuppressWarnings("HidingField") public int varOne; } // subclass with member *methods* with the same name as superclass member variable -- this is ok static class ClassD extends ClassC { public void varThree() {} public void varTwo() {} } }
1,930
30.655738
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/URLEqualsHashCodeNegativeCases.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.testdata; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Negative test cases for URLEqualsHashCode check. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class URLEqualsHashCodeNegativeCases { private static class Url { private Url() { // no impl } } // Set and HashSet of non-URL class. public void setOfUrl() { Set<Url> urlSet; } public void hashsetOfUrl() { HashSet<Url> urlSet; } // Collection(s) of type URL public void collectionOfURL() { Collection<URL> urlSet; } public void listOfURL() { List<URL> urlSet; } public void arraylistOfURL() { ArrayList<URL> urlSet; } public void hashmapWithURLAsValue() { HashMap<String, java.net.URL> stringToUrlMap; } private static class ExtendedMap extends HashMap<String, java.net.URL> { // no impl. } public void hashMapExtendedClass() { ExtendedMap urlMap; } }
1,704
22.040541
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4SetUpNotRunPositiveCaseCustomBefore.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.testdata; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Slightly funky test case with a custom Before annotation */ @RunWith(JUnit4.class) public class JUnit4SetUpNotRunPositiveCaseCustomBefore { // This will compile-fail and suggest the import of org.junit.Before // BUG: Diagnostic contains: @Before @Before public void setUp() {} } @interface Before {}
1,042
31.59375
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/StaticQualifiedUsingExpressionNegativeCases.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.testdata; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class StaticQualifiedUsingExpressionNegativeCases { public static int staticVar1 = 1; public static void staticTestMethod() {} public void test1() { Integer i = Integer.MAX_VALUE; i = Integer.valueOf(10); } public void test2() { int i = staticVar1; i = StaticQualifiedUsingExpressionNegativeCases.staticVar1; } public void test3() { test1(); this.test1(); new StaticQualifiedUsingExpressionNegativeCases().test1(); staticTestMethod(); } public void test4() { Class<?> klass = String[].class; } @SuppressWarnings("static") public void testJavacAltname() { this.staticTestMethod(); } @SuppressWarnings("static-access") public void testEclipseAltname() { this.staticTestMethod(); } }
1,491
24.288136
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FuzzyEqualsShouldNotBeUsedInEqualsMethodNegativeCases.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.testdata; import com.google.common.math.DoubleMath; /** * @author sulku@google.com (Marsela Sulku) */ public class FuzzyEqualsShouldNotBeUsedInEqualsMethodNegativeCases { public boolean equals() { return true; } private static class TestClass { public void test() { boolean t = DoubleMath.fuzzyEquals(0, 2, 0.3); } public boolean equals(Object other) { return true; } public boolean equals(Object other, double a) { return DoubleMath.fuzzyEquals(0, 1, 0.2); } } }
1,175
27
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EqualsNaNNegativeCases.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.testdata; /** * @author lowasser@google.com (Louis Wasserman) */ public class EqualsNaNNegativeCases { static final boolean NAN_AFTER_MATH = (0.0 / 0.0) == 1.0; static final boolean NORMAL_COMPARISON = 1.0 == 2.0; }
874
32.653846
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ChainedAssertionLosesContextNegativeCases.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.testdata; import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertThat; import com.google.common.truth.FailureMetadata; import com.google.common.truth.Subject; /** * @author cpovirk@google.com (Chris Povirk) */ public class ChainedAssertionLosesContextNegativeCases { static final class FooSubject extends Subject { private final Foo actual; private FooSubject(FailureMetadata metadata, Foo actual) { super(metadata, actual); this.actual = actual; } static Factory<FooSubject, Foo> foos() { return FooSubject::new; } static FooSubject assertThat(Foo foo) { return assertAbout(foos()).that(foo); } } void someTestMethod() { assertThat("").isNotNull(); } private static final class Foo { final String string; final int integer; Foo(String string, int integer) { this.string = string; this.integer = integer; } String string() { return string; } int integer() { return integer; } Foo otherFoo() { return this; } } }
1,767
23.555556
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TestNotRunNegativeCase4.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.testdata; import junit.framework.TestCase; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * May be a JUnit 3 test -- has @RunWith annotation on the class but also extends TestCase. * * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class JUnit4TestNotRunNegativeCase4 extends TestCase { public void testThisIsATest() {} }
1,036
31.40625
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverrideThrowableToStringPositiveCases_expected.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.testdata; /** * @author mariasam@google.com (Maria Sam) */ class OverrideThrowableToStringPositiveCases { // BUG: Diagnostic contains: override class BasicTest extends Throwable { @Override public String getMessage() { return ""; } } class MultipleMethods extends Throwable { public MultipleMethods() { ; } @Override public String getMessage() { return ""; } } class NoOverride extends Throwable { public String getMessage() { return ""; } } }
1,182
22.196078
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/StaticGuardedByInstanceTest.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.threadsafety; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link StaticGuardedByInstance}Test */ @RunWith(JUnit4.class) public class StaticGuardedByInstanceTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(StaticGuardedByInstance.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "class Test {", " final Object lock = new Object();", " static boolean init = false;", " void m() {", " synchronized (lock) {", " // BUG: Diagnostic contains:", " // static variable should not be guarded by instance lock 'lock'", " init = true;", " }", " }", "}") .doTest(); } @Test public void positive_twoWrites() { compilationHelper .addSourceLines( "Test.java", "class Test {", " final Object lock = new Object();", " static int x = 0;", " void m() {", " synchronized (lock) {", " // BUG: Diagnostic contains:", " // static variable should not be guarded by instance lock 'lock'", " x++;", " // BUG: Diagnostic contains:", " // static variable should not be guarded by instance lock 'lock'", " x++;", " }", " }", "}") .doTest(); } @Test public void negative_staticLock() { compilationHelper .addSourceLines( "Test.java", "class Test {", " static final Object lock = new Object();", " static boolean init = false;", " void m() {", " synchronized (lock) {", " init = true;", " }", " }", "}") .doTest(); } @Test public void negative_instanceVar() { compilationHelper .addSourceLines( "Test.java", "class Test {", " final Object lock = new Object();", " boolean init = false;", " void m() {", " synchronized (lock) {", " init = true;", " }", " }", "}") .doTest(); } @Test public void negative_method() { compilationHelper .addSourceLines( "Test.java", "class Test {", " static boolean init = false;", " void m() {", " synchronized (getClass()) {", " init = true;", " }", " }", "}") .doTest(); } @Test public void negative_nested() { compilationHelper .addSourceLines( "Test.java", "class Test {", " final Object lock = new Object();", " static boolean init = false;", " void m() {", " synchronized (lock) {", " synchronized (Test.class) {", " init = true;", " }", " new Test() {{", " init = true;", " }};", " }", " }", "}") .doTest(); } }
4,145
27.791667
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLockingTest.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.threadsafety; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link DoubleCheckedLocking}Test */ @RunWith(JUnit4.class) public class DoubleCheckedLockingTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(DoubleCheckedLocking.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " public Object x;", " void m() {", " // BUG: Diagnostic contains: public volatile Object x", " if (x == null) {", " synchronized (this) {", " if (x == null) {", " x = new Object();", " }", " }", " }", " }", "}") .doTest(); } @Test public void positiveNoFix() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " static class Inner { static Object x; }", " void m() {", " // BUG: Diagnostic contains:", " if (Inner.x == null) {", " synchronized (this) {", " if (Inner.x == null) {", " Inner.x = new Object();", " }", " }", " }", " }", "}") .doTest(); } @Test public void positiveTmpVar() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " Object x;", " void m() {", " Object z = x;", " // BUG: Diagnostic contains: volatile Object", " if (z == null) {", " synchronized (this) {", " z = x;", " if (z == null) {", " x = z = new Object();", " }", " }", " }", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " volatile Object x;", " void m() {", " if (x == null) {", " synchronized (this) {", " if (x == null) {", " x = new Object();", " }", " }", " }", " }", "}") .doTest(); } @Test public void immutable_integer() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " public Integer x;", " void m() {", " if (x == null) {", " synchronized (this) {", " if (x == null) {", " x = 1;", " }", " }", " }", " }", "}") .doTest(); } @Test public void immutable_string() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " public String x;", " void m() {", " if (x == null) {", " synchronized (this) {", " if (x == null) {", " x = \"\";", " }", " }", " }", " }", "}") .doTest(); } @Test public void b37896333() { compilationHelper .addSourceLines( "tTest.java", "class Test {", " public String x;", " String m() {", " String result = x;", " if (result == null) {", " synchronized (this) {", " if (result == null) {", " x = result = \"\";", " }", " }", " }", " return result;", " }", "}") .doTest(); } }
5,153
27.163934
80
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByBinderTest.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.threadsafety; import static com.google.common.truth.Truth.assertThat; import static com.google.errorprone.FileObjects.forSourceLines; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.fail; import com.google.errorprone.FileManagers; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.CompilationUnitTree; import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.TreeScanner; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link GuardedByBinder}Test */ @RunWith(JUnit4.class) public class GuardedByBinderTest { @Test public void inherited() { assertThat( bind( "Test", "slock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Super {", " final Object slock = new Object();", "}", "class Test extends Super {", "}"))) .isEqualTo("(SELECT (THIS) slock)"); } @Test public void finalCase() { assertThat( bind( "Test", "lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " final Object lock = new Object();", "}"))) .isEqualTo("(SELECT (THIS) lock)"); } @Test public void method() { assertThat( bind( "Test", "s.f.g().f.g().lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Super {", " final Super f = null;", " Super g() { return null; }", " final Object lock = new Object();", "}", "class Test {", " final Super s = null;", "}"))) .isEqualTo( "(SELECT (SELECT (SELECT (SELECT (SELECT (SELECT " + "(THIS) s) f) g()) f) g()) lock)"); } @Test public void badSuperAccess() { bindFail( "Test", "Super.this.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Super {}", "class Test extends Super {", " final Object lock = new Object();", "}")); } @Test public void namedClass_this() { assertThat( bind( "Test", "Test.class", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", "}"))) .isEqualTo("(CLASS_LITERAL threadsafety.Test)"); } @Test public void namedClass_super() { assertThat( bind( "Test", "Super.class", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Super {}", "class Test extends Super {}"))) .isEqualTo("(CLASS_LITERAL threadsafety.Super)"); } @Test public void namedClass_nonLiteral() { bindFail( "Test", "t.class", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Super {}", "class Test extends Super {", " Test t;", "}")); } @Test public void namedClass_none() { bindFail( "Test", "Super.class", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {}")); } @Test public void namedThis_none() { bindFail( "Test", "Segment.this", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {}")); } @Test public void outer_lock() { assertThat( bind( "Test", "Outer.this.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Outer {", " final Object lock = new Object();", " class Test {}", "}"))) .isEqualTo("(SELECT (SELECT (THIS) outer$threadsafety.Outer) lock)"); } @Test public void outer_lock_simpleName() { assertThat( bind( "Test", "lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Outer {", " final Object lock = new Object();", " class Test {}", "}"))) .isEqualTo("(SELECT (SELECT (THIS) outer$threadsafety.Outer) lock)"); } @Test public void otherClass() { assertThat( bind( "Test", "Other.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Other {", " static final Object lock = new Object();", "}", "class Test {", "}"))) .isEqualTo("(SELECT (TYPE_LITERAL threadsafety.Other) lock)"); } @Test public void simpleName() { assertThat( bind( "Test", "Other.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Other {", " static final Object lock = new Object();", "}", "class Test {", " final Other Other = null;", "}"))) .isEqualTo("(SELECT (TYPE_LITERAL threadsafety.Other) lock)"); } @Test public void simpleNameClass() { assertThat( bind( "Test", "Other.class", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Other {", " static final Object lock = new Object();", "}", "class Test {", " Other Other = null;", "}"))) .isEqualTo("(CLASS_LITERAL threadsafety.Other)"); } @Test public void simpleFieldName() { assertThat( bind( "Test", "Other", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Other {", " static final Object lock = new Object();", "}", "class Test {", " final Object Other = null;", "}"))) .isEqualTo("(SELECT (THIS) Other)"); } @Test public void staticFieldGuard() { assertThat( bind( "Test", "lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " static final Object lock = new Object();", "}"))) .isEqualTo("(SELECT (TYPE_LITERAL threadsafety.Test) lock)"); } @Test public void staticMethodGuard() { assertThat( bind( "Test", "lock()", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " static Object lock() { return null; }", "}"))) .isEqualTo("(SELECT (TYPE_LITERAL threadsafety.Test) lock())"); } @Test public void staticOnStatic() { assertThat( bind( "Test", "Test.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " static final Object lock = new Object();", "}"))) .isEqualTo("(SELECT (TYPE_LITERAL threadsafety.Test) lock)"); } @Test public void instanceOnStatic() { bindFail( "Test", "Test.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " final Object lock = new Object();", "}")); } @Test public void instanceMethodOnStatic() { bindFail( "Test", "Test.lock()", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " final Object lock() { return null; }", "}")); } @Test public void explicitThisOuterClass() { assertThat( bind( "Inner", "this.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Outer {", " Object lock;", " class Inner {", " int x;", " }", "}"))) .isEqualTo("(SELECT (SELECT (THIS) outer$threadsafety.Outer) lock)"); } @Test public void implicitThisOuterClass() { assertThat( bind( "Inner", "lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Outer {", " Object lock;", " class Inner {", " int x;", " }", "}"))) .isEqualTo("(SELECT (SELECT (THIS) outer$threadsafety.Outer) lock)"); } @Test public void implicitThisOuterClassMethod() { assertThat( bind( "Inner", "endpoint().lock()", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Outer {", " class Endpoint {", " Object lock() { return null; }", " }", " Endpoint endpoint() { return null; }", " class Inner {", " int x;", " }", "}"))) .isEqualTo("(SELECT (SELECT (SELECT (THIS) outer$threadsafety.Outer) endpoint()) lock())"); } @Test public void explicitThisSameClass() { assertThat( bind( "Test", "Test.this", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", "}"))) .isEqualTo("(THIS)"); } // regression test for issue 387 @Test public void enclosingBlockScope() { assertThat( bind( "", "mu", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " public final Object mu = new Object();", " @GuardedBy(\"mu\") int x = 1;", " {", " new Object() {", " void f() {", " synchronized (mu) {", " x++;", " }", " }", " };", " }", "}"))) .isEqualTo("(SELECT (SELECT (THIS) outer$threadsafety.Test) mu)"); } // TODO(cushon): disallow non-final lock expressions @Ignore @Test public void nonFinalStatic() { bindFail( "Test", "Other.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Other {", " static Object lock = new Object();", "}", "class Test {", " final Other Other = null;", "}")); } // TODO(cushon): disallow non-final lock expressions @Ignore @Test public void nonFinal() { bindFail( "Test", "lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " Object lock = new Object();", "}")); } private static void bindFail(String className, String exprString, JavaFileObject fileObject) { try { bind(className, exprString, fileObject); fail("Expected binding to fail."); } catch (IllegalGuardedBy expected) { } } private static String bind(String className, String exprString, JavaFileObject fileObject) { JavaCompiler javaCompiler = JavacTool.create(); JavacTaskImpl task = (JavacTaskImpl) javaCompiler.getTask( new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.err, UTF_8)), true), FileManagers.testFileManager(), null, Collections.<String>emptyList(), null, Arrays.asList(fileObject)); Iterable<? extends CompilationUnitTree> compilationUnits = task.parse(); task.analyze(); for (CompilationUnitTree compilationUnit : compilationUnits) { FindClass finder = new FindClass(); finder.visitTopLevel((JCTree.JCCompilationUnit) compilationUnit); for (JCTree.JCClassDecl classDecl : finder.decls) { if (classDecl.getSimpleName().contentEquals(className)) { Optional<GuardedByExpression> guardExpression = GuardedByBinder.bindString( exprString, GuardedBySymbolResolver.from( ASTHelpers.getSymbol(classDecl), null, compilationUnit, task.getContext(), null, VisitorState.createForUtilityPurposes(task.getContext())), GuardedByFlags.allOn()); if (!guardExpression.isPresent()) { throw new IllegalGuardedBy(exprString); } return guardExpression.get().debugPrint(); } } } throw new AssertionError("Couldn't find a class with the given name: " + className); } private static class FindClass extends TreeScanner { private final List<JCTree.JCClassDecl> decls = new ArrayList<>(); @Override public void visitClassDef(JCTree.JCClassDecl classDecl) { decls.add(classDecl); super.visitClassDef(classDecl); } } }
16,797
29.765568
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.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.threadsafety; import static org.junit.Assume.assumeTrue; import com.google.common.collect.ImmutableList; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.errorprone.util.RuntimeVersion; import java.util.Arrays; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ImmutableChecker}Test */ @RunWith(JUnit4.class) public class ImmutableCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ImmutableChecker.class, getClass()); @Test public void basicFields() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class Test {", " final int a = 42;", " final String b = null;", " final java.lang.String c = null;", " final com.google.common.collect.ImmutableList<String> d = null;", " final ImmutableList<Integer> e = null;", " final Deprecated dep = null;", " final Class<?> clazz = Class.class;", "}") .doTest(); } @Test public void interfacesMutableByDefault() { compilationHelper .addSourceLines("I.java", "interface I {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains:" + " 'I' is not annotated with @com.google.errorprone.annotations.Immutable", " private final I i = new I() {};", "}") .doTest(); } @Test public void annotationsAreImmutable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable @interface Test {}") .doTest(); } @Test public void customAnnotationsMightBeMutable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable @interface Test {}") .addSourceLines( "MyTest.java", "import com.google.errorprone.annotations.Immutable;", "import java.lang.annotation.Annotation;", "@Immutable final class MyTest implements Test {", " // BUG: Diagnostic contains: non-final", " public Object[] xs = {};", " public Class<? extends Annotation> annotationType() {", " return null;", " }", "}") .doTest(); } @Ignore("b/25630189") // don't check annotations for immutability yet @Test public void customImplementionsOfImplicitlyImmutableAnnotationsMustBeImmutable() { compilationHelper .addSourceLines("Anno.java", "@interface Anno {}") .addSourceLines( "MyAnno.java", "import java.lang.annotation.Annotation;", "final class MyAnno implements Anno {", " // BUG: Diagnostic contains:", " public Object[] xs = {};", " public Class<? extends Annotation> annotationType() {", " return null;", " }", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " private final Anno anno = new MyAnno();", "}") .doTest(); } @Test public void customAnnotationsSubtype() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable @interface Test {}") .addSourceLines( "MyTest.java", "import java.lang.annotation.Annotation;", "final class MyTest implements Test {", " // BUG: Diagnostic contains: non-final field 'xs'", " public Object[] xs = {};", " public Class<? extends Annotation> annotationType() {", " return null;", " }", "}") .doTest(); } @Test public void annotationsDefaultToImmutable() { compilationHelper .addSourceLines( "Test.java", "import javax.lang.model.element.ElementKind;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " private final Override override = null;", "}") .doTest(); } @Test public void enumsDefaultToImmutable() { compilationHelper .addSourceLines( "Test.java", "import javax.lang.model.element.ElementKind;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " private final ElementKind ek = null;", "}") .doTest(); } @Test public void enumsMayBeImmutable() { compilationHelper .addSourceLines( "Kind.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable enum Kind { A, B, C; }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " private final Kind k = null;", "}") .doTest(); } @Test public void mutableArray() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains:", " final int[] xs = {42};", "}") .doTest(); } @Test public void annotatedImmutableInterfaces() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface Test {}") .doTest(); } @Test public void immutableInterfaceField() { compilationHelper .addSourceLines( "MyInterface.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface MyInterface {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " final MyInterface i = null;", "}") .doTest(); } @Test public void deeplyImmutableArguments() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class Test {", " final ImmutableList<ImmutableList<ImmutableList<String>>> l = null;", "}") .doTest(); } @Test public void mutableNonFinalField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains: non-final", " int a = 42;", "}") .doTest(); } @Test public void ignoreStaticFields() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " static int a = 42;", "}") .doTest(); } @Test public void mutableField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.Map;", "@Immutable class Test {", " // BUG: Diagnostic contains:", " final Map<String, String> a = null;", "}") .doTest(); } @Test public void deeplyMutableTypeArguments() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.Map;", "import com.google.common.collect.ImmutableList;", "@Immutable class Test {", " // BUG: Diagnostic contains: instantiated with mutable type for 'E'", " final ImmutableList<ImmutableList<ImmutableList<Map<String, String>>>> l = null;", "}") .doTest(); } @Test public void rawImpliesImmutable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class Test {", " // BUG: Diagnostic contains:", " final ImmutableList l = null;", "}") .doTest(); } @Test public void extendsImmutable() { compilationHelper .addSourceLines( "Super.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable public class Super {", " public final int x = 42;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test extends Super {", "}") .doTest(); } @Test public void extendsMutable() { compilationHelper .addSourceLines("Super.java", "public class Super {", " public int x = 42;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "// BUG: Diagnostic contains: 'Super' has non-final field 'x'", "@Immutable class Test extends Super {", "}") .doTest(); } @Test public void extendsImmutableAnnotated_substBounds() { compilationHelper .addSourceLines( "SuperMost.java", "import com.google.errorprone.annotations.Immutable;", "public class SuperMost<B> {", " public final B x = null;", "}") .addSourceLines( "Super.java", "import java.util.List;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf={\"A\"}) public class Super<A, B> extends SuperMost<A> {", " public final int x = 42;", "}") .doTest(); } @Test public void extendsImmutableAnnotated_mutableBounds() { compilationHelper .addSourceLines( "SuperMost.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf={\"A\"})", "public class SuperMost<A> {", " public final A x = null;", "}") .addSourceLines( "SubClass.java", "import java.util.List;", "import com.google.errorprone.annotations.Immutable;", " // BUG: Diagnostic contains: instantiated with mutable type for 'A'", "@Immutable public class SubClass extends SuperMost<List<String>> {}") .doTest(); } @Test public void withinMutableClass() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.ArrayList;", "import java.util.List;", "class A {", " List<Integer> xs = new ArrayList<>();", " // BUG: Diagnostic contains: has mutable enclosing instance", " @Immutable class B {", " int get() {", " return xs.get(0);", " }", " }", "}") .doTest(); } @Test public void localClassCapturingMutableState() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.ArrayList;", "import java.util.List;", "@Immutable", "class A {", " @Immutable interface B { int get(); }", " void test() {", " List<Integer> xs = new ArrayList<>();", " @Immutable", " // BUG: Diagnostic contains: This anonymous class implements @Immutable interface" + " 'B', but closes over 'xs', which is not @Immutable because 'List' is mutable", " class C implements B {", " @Override", " public int get() {", " return xs.get(0);", " }", " }", " }", "}") .doTest(); } @Test public void typeParameterWithImmutableBound() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable(containerOf=\"T\") class Test<T extends ImmutableList<String>> {", " final T t = null;", "}") .doTest(); } @Test public void immutableTypeArgumentInstantiation() { compilationHelper .addSourceLines( "Holder.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public class Holder<T> {", " public final T t = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " final Holder<String> h = null;", "}") .doTest(); } @Test public void mutableTypeArgumentInstantiation() { compilationHelper .addSourceLines( "Holder.java", "import com.google.errorprone.annotations.Immutable;", "public class Holder<T> {", " public final T t = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains:", " final Holder<Object> h = null;", "}") .doTest(); } @Test public void instantiationWithMutableType() { compilationHelper .addSourceLines( "Holder.java", "import com.google.errorprone.annotations.Immutable;", "public class Holder<T> {", " public final T t = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains: not annotated", " final Holder<Object> h = null;", "}") .doTest(); } @Test public void transitiveSuperSubstitutionImmutable() { compilationHelper .addSourceLines( "SuperMostType.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"N\") public class SuperMostType<N> {", " public final N f = null;", "}") .addSourceLines( "MiddleClass.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"M\") public class MiddleClass<M> extends SuperMostType<M> {", " // Empty", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test extends MiddleClass<String> {", " final MiddleClass<String> f = null;", "}") .doTest(); } @Ignore("http://b/72495910") @Test public void containerOf_extendsImmutable() { compilationHelper .addSourceLines( "X.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class X<V> {", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", " // BUG: Diagnostic contains: 'V' is a mutable type variable", "@Immutable(containerOf=\"V\") class Test<V> extends X<V> {", " private final V t = null;", "}") .addSourceLines( "MutableLeak.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class MutableLeak {", " private static class Mutable {", " int mutableInt;", " }", " private final X<Mutable> bad = new Test<Mutable>();", "}") .doTest(); } @Test public void containerOf_mutableInstantiation() { compilationHelper .addSourceLines( "X.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"V\") class X<V> {", " private final V t = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test<T> {", " // BUG: Diagnostic contains:", " // 'X' was instantiated with mutable type for 'V'", " // 'T' is a mutable type variable", " private final X<T> t = null;", "}") .doTest(); } @Test public void missingContainerOf() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "@Immutable class Test<T> {", " // BUG: Diagnostic contains: 'T' is a mutable type variable", " private final T t = null;", "}") .doTest(); } @Test public void transitiveSuperSubstitutionMutable() { compilationHelper .addSourceLines( "SuperMostType.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"N\") public class SuperMostType<N> {", " public final N f = null;", "}") .addSourceLines( "MiddleClass.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"M\") public class MiddleClass<M> extends SuperMostType<M> {", " // Empty", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "// BUG: Diagnostic contains: instantiated with mutable type for 'M'", "@Immutable class Test extends MiddleClass<List> {", "}") .doTest(); } @Test public void immutableInstantiation() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public class X<T> {", " final ImmutableList<T> xs = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "@Immutable class Test {", " final X<String> x = null;", "}") .doTest(); } @Test public void mutableInstantiation() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "public class X<T> { final ImmutableList<T> xs = null; }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", "// BUG: Diagnostic contains:", " final X<Object> x = null;", "}") .doTest(); } @Test public void immutableInstantiation_superBound() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "public class X<T> { final ImmutableList<? super T> xs = null; }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "@Immutable class Test {", " // BUG: Diagnostic contains:", " final X<String> x = null;", "}") .doTest(); } @Test public void mutableInstantiation_superBound() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "public class X<T> { final ImmutableList<? super T> xs = null; }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "@Immutable class Test {", " // BUG: Diagnostic contains: is not annotated", " final X<String> x = null;", "}") .doTest(); } @Test public void immutableInstantiation_extendsBound() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public class X<T> {", " final ImmutableList<? extends T> xs = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "@Immutable class Test {", " final X<String> x = null;", "}") .doTest(); } @Test public void mutableInstantiation_wildcard() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public class X<T> {", " // BUG: Diagnostic contains: mutable type for 'E', 'Object' is mutable", " final ImmutableList<?> xs = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "@Immutable class Test {", " final X<String> x = null;", "}") .doTest(); } @Test public void mutableInstantiation_extendsBound() { compilationHelper .addSourceLines( "X.java", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable(containerOf=\"T\") public class X<T> {", " final ImmutableList<? extends T> xs = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "@Immutable class Test {", " // BUG: Diagnostic contains: instantiated with mutable type", " final X<Object> x = null;", "}") .doTest(); } @Test public void containerOf_noSuchType() { compilationHelper .addSourceLines( "X.java", "import com.google.errorprone.annotations.Immutable;", "// BUG: Diagnostic contains: could not find type(s) referenced by containerOf: Z", "@Immutable(containerOf=\"Z\") public class X<T> {", " final int xs = 1;", "}") .doTest(); } @Test public void immutableInstantiation_inferredImmutableType() { compilationHelper .addSourceLines( "X.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public class X<T> {", " final T xs = null;", "}") .addSourceLines( "Y.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public class Y<T> {", " final X<? extends T> xs = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " final Y<String> x = null;", "}") .doTest(); } @Test public void mutableInstantiation_inferredImmutableType() { compilationHelper .addSourceLines("X.java", "public class X<T> {", " final T xs = null;", "}") .addSourceLines("Y.java", "public class Y<T> {", " final X<? extends T> xs = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains:", " final Y<Object> x = null;", "}") .doTest(); } @Test public void mutableWildInstantiation() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public class X<T> {", " final ImmutableList<T> xs = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains: instantiated", " final X<?> x = null;", "}") .doTest(); } @Test public void mutableWildcardInstantiation_immutableTypeParameter() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.Immutable;", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "@Immutable", "class A<@ImmutableTypeParameter T> {}") .addSourceLines( "B.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable", "class B {", " private final A<?> a;", " public B(A<?> a) { this.a = a; }", "}") .doTest(); } @Test public void mutableRawType() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public class X<T> {", " final ImmutableList<T> xs = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains: raw", " final X x = null;", "}") .doTest(); } @Test public void immutableListImplementation() { compilationHelper .addSourceLines( "com/google/common/collect/ImmutableList.java", "package com.google.common.collect;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class ImmutableList<E> {", " public Object[] veryMutable = null;", "}") .doTest(); } @Test public void positiveAnonymous() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "class Test {{", " new Super() {", " // BUG: Diagnostic contains: non-final", " int x = 0;", " {", " x++;", " }", " };", "}}") .doTest(); } @Test public void positiveAnonymousInterface() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "class Test {{", " new Super() {", " // BUG: Diagnostic contains: non-final", " int x = 0;", " {", " x++;", " }", " };", "}}") .doTest(); } @Test public void negativeParametricAnonymous() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") class Super<T> {", " private final T t = null;", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "class Test {", " static <T> Super<T> get() {", " return new Super<T>() {};", " }", "}") .doTest(); } @Test public void interface_containerOf_immutable() { compilationHelper .addSourceLines( "MyList.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public interface MyList<T> {", " T get(int i);", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "public class Test {", " private final MyList<Integer> l = null;", "}") .doTest(); } @Test public void interface_containerOf_mutable() { compilationHelper .addSourceLines( "MyList.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public interface MyList<T> {", " T get(int i);", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable public class Test<X> {", " // BUG: Diagnostic contains: mutable type for 'T'", " private final MyList<X> l = null;", "}") .doTest(); } @Test public void implementsInterface_containerOf() { compilationHelper .addSourceLines( "MyList.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") public interface MyList<T> {", " T get(int i);", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "// BUG: Diagnostic contains: 'X' is a mutable type", "@Immutable public class Test<X> implements MyList<X> {", " public X get(int i) { return null; }", "}") .doTest(); } // sub-type tests @Test public void positive() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test extends Super {", " // BUG: Diagnostic contains:" + " Class extends @Immutable type threadsafety.Super, but is not immutable: 'Test'" + " has non-final field 'x'", " public int x = 0;", "}") .doTest(); } @Test public void positiveContainerOf() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf={\"T\"}) class Super<T> {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test extends Super<Integer> {", " // BUG: Diagnostic contains: non-final", " public int x = 0;", "}") .doTest(); } @Test public void positiveImplicitContainerOf() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf={\"T\"}) class Super<T> {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test<U> extends Super<U> {", " // BUG: Diagnostic contains: mutable type for 'U'", " public final Test<Object> x = null;", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test extends Super {", "}") .doTest(); } // Report errors in compilation order, and detect transitive errors even if immediate // supertype is unannotated. @Test public void transitive() { compilationHelper .addSourceLines( "threadsafety/I.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface I {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test implements J {", " // BUG: Diagnostic contains: non-final field 'x'", " public int x = 0;", "}") .addSourceLines( "threadsafety/J.java", // "package threadsafety;", "interface J extends I {", "}") .doTest(); } // the type arguments are checked everywhere the super type is used @Test public void negativeAnonymousMutableBound() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") class Super<T> {", " private final T t = null;", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "class Test {{", " new Super<Object>() {};", "}}") .doTest(); } @Test public void immutableAnonymousTypeScope() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"X\") class Super<X> {", " private final X t = null;", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") class Test<T> {{", " new Super<T>() {};", "}}") .doTest(); } @Test public void immutableClassSuperTypeScope() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"Y\") class Super<Y> {", " @Immutable(containerOf=\"X\") class Inner1<X> {", " private final X x = null;", " private final Y y = null;", " }", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"U\") class Test<U> extends Super<U> {", " @Immutable class Inner2 extends Inner1<U> {}", "}") .doTest(); } @Test public void immutableClassTypeScope() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"X\") class Super<X> {", " private final X t = null;", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") class Test<T> {", " @Immutable class Inner extends Super<T> {}", "}") .doTest(); } @Test public void negativeAnonymousBound() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\") class Super<T> {", " private final T t = null;", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "class Test {{", " new Super<String>() {};", "}}") .doTest(); } @Test public void negativeAnonymous() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "class Test {{", " new Super() {};", "}}") .doTest(); } @Test public void positiveEnumConstant() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface Super {", " int f();", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable enum Test implements Super {", " INSTANCE {", " // BUG: Diagnostic contains: non-final", " public int x = 0;", " public int f() {", " return x++;", " }", " }", "}") .doTest(); } @Test public void negativeEnumConstant() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface Super {", " void f();", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable enum Test implements Super {", " INSTANCE {", " public void f() {", " }", " }", "}") .doTest(); } // any final null reference constant is immutable, but do we actually care? // // javac makes it annoying to figure this out - since null isn't a compile-time constant, // none of that machinery can be used. Instead, we need to look at the actual AST node // for the member declaration to see that it's initialized to null. @Ignore @Test public void immutableNull() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " final int[] xs = null;", "}") .doTest(); } @Test public void suppressOnField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " @SuppressWarnings(\"Immutable\")", " final int[] xs = {1};", "}") .doTest(); } @Test public void suppressOnOneField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " @SuppressWarnings(\"Immutable\")", " final int[] xs = {1};", " // BUG: Diagnostic contains: arrays are mutable", " final int[] ys = {1};", "}") .doTest(); } @Test public void twoFieldsInSource() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains: arrays are mutable", " final int[] xs = {1};", " // BUG: Diagnostic contains: arrays are mutable", " final int[] ys = {1};", "}") .doTest(); } @Test public void protosNotOnClasspath() { compilationHelper .addSourceLines( "com/google/errorprone/annotations/Immutable.java", "package com.google.errorprone.annotations;", "import static java.lang.annotation.ElementType.TYPE;", "import static java.lang.annotation.RetentionPolicy.RUNTIME;", "import java.lang.annotation.Retention;", "import java.lang.annotation.Target;", "@Target(TYPE)", "@Retention(RUNTIME)", "public @interface Immutable {", " String[] containerOf() default {};", "}") .addSourceLines("Foo.java", "class Foo {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains:" + " 'Foo' is not annotated with @com.google.errorprone.annotations.Immutable", " final Foo f = null;", "}") .setArgs(Arrays.asList("-cp", "NOSUCH")) .doTest(); } @Ignore("b/25630186") // don't check enums for immutability yet @Test public void mutableEnum() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "enum Test {", " ;", " // BUG: Diagnostic contains: @Immutable class has mutable field", " private final Object o = null;", "}") .doTest(); } @Ignore("b/25630186") // don't check enums for immutability yet @Test public void mutableEnumMember() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "enum Test {", " ONE {", " // BUG: Diagnostic contains: @Immutable class has mutable field", " private final Object o = null;", " }", "}") .doTest(); } @Ignore("b/25630189") // don't check annotations for immutability yet @Test public void mutableExtendsAnnotation() { compilationHelper .addSourceLines( "Anno.java", // "@interface Anno {}") .addSourceLines( "Test.java", "abstract class Test implements Anno {", " // BUG: Diagnostic contains: @Immutable class has mutable field", " final Object o = null;", "}") .doTest(); } @Test public void mutableEnclosing() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "public class Test {", " int x = 0;", " // BUG: Diagnostic contains: 'Inner' has mutable enclosing instance 'Test'", " @Immutable public class Inner {", " public int count() {", " return x++;", " }", " }", "}") .doTest(); } /** A sample superclass with a mutable field. */ public static class SuperFieldSuppressionTest { @LazyInit public int x = 0; public int count() { return x++; } } @Test public void superFieldSuppression() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import " + SuperFieldSuppressionTest.class.getCanonicalName() + ";", "@Immutable public class Test extends SuperFieldSuppressionTest {}") .doTest(); } @Test public void rawClass() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " final Class clazz = Test.class;", "}") .doTest(); } /** Test class annotated with @Immutable. */ @Immutable(containerOf = {"T"}) public static class ClassPathTest<T> {} @Test public void incompleteClassPath() { compilationHelper .addSourceLines( "Test.java", "import " + ClassPathTest.class.getCanonicalName() + ";", "class Test extends ClassPathTest<String> {", " // BUG: Diagnostic contains: 'Test' has non-final field 'x'", " int x;", "}") .withClasspath(ImmutableCheckerTest.ClassPathTest.class, ImmutableCheckerTest.class) .doTest(); } @Test public void knownImmutableFlag() { CompilationTestHelper.newInstance(ImmutableChecker.class, getClass()) .setArgs(ImmutableList.of("-XepOpt:Immutable:KnownImmutable=threadsafety.SomeImmutable")) .addSourceLines( "threadsafety/SomeImmutable.java", "package threadsafety;", "class SomeImmutable {}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " public final SomeImmutable s = new SomeImmutable();", "}") .doTest(); } @Test public void knownUnsafeFlag() { CompilationTestHelper.newInstance(ImmutableChecker.class, getClass()) .setArgs(ImmutableList.of("-XepOpt:Immutable:KnownMutable=threadsafety.SomeUnsafe")) .addSourceLines( "threadsafety/SomeUnsafe.java", "package threadsafety;", "class SomeUnsafe {}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " // BUG: Diagnostic contains: 'SomeUnsafe' is mutable", " public final SomeUnsafe s = new SomeUnsafe();", "}") .doTest(); } @Test public void lazyInit() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import com.google.errorprone.annotations.concurrent.LazyInit;", "@Immutable class Test {", " @LazyInit int a = 42;", "}") .doTest(); } @Test public void lazyInitMutable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import com.google.errorprone.annotations.concurrent.LazyInit;", "import java.util.List;", "@Immutable class Test {", " // BUG: Diagnostic contains: 'List' is mutable", " @LazyInit List<Integer> a = null;", "}") .doTest(); } @Test public void immutableTypeParameter() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class Test<@ImmutableTypeParameter T> {", " final T t = null;", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_immutableGenericFromContext_noViolation() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class Test<@ImmutableTypeParameter T> {", " A<T> n() {", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_mutableGenericFromContext_violation() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "class Test<T> {", " A<T> n() {", " // BUG: Diagnostic contains: instantiation of 'T' is mutable, 'T' is a mutable" + " type variable", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_staticMethod_genericParamNotAnnotated_violation() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "class Test {", " static <T> A<T> m() {", " // BUG: Diagnostic contains: instantiation of 'T' is mutable, 'T' is a mutable" + " type variable", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_staticMethod_genericParamAnnotated_noViolation() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class Test {", " static <@ImmutableTypeParameter T> A<T> l() {", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_genericParamNotAnnotated_violation() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "class Test {", " <T> A<T> k() {", " // BUG: Diagnostic contains: instantiation of 'T' is mutable, 'T' is a mutable" + " type variable", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_genericParamAnnotated_noViolation() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class Test {", " <@ImmutableTypeParameter T> A<T> k() {", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_genericParamExtendsMutable_violation() { compilationHelper .addSourceLines( "MyMutableType.java", "import com.google.errorprone.annotations.Immutable;", "class MyMutableType {}") .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "class Test {", " <T extends MyMutableType> A<T> i() {", " // BUG: Diagnostic contains: instantiation of 'T' is mutable, 'T' is a mutable" + " type variable", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_genericParamExtendsImmutable_noViolation() { compilationHelper .addSourceLines( "MyImmutableType.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class MyImmutableType {}") .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "class Test {", " <T extends MyImmutableType> A<T> h() {", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_violation() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "class Test {", " A<Object> g() {", " // BUG: Diagnostic contains: instantiation of 'T' is mutable, 'Object' is mutable", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterInstantiation_noViolation() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class A<@ImmutableTypeParameter T> {}") .addSourceLines( "Test.java", "class Test {", " A<String> f() {", " return new A<>();", " }", "}") .doTest(); } @Test public void immutableTypeParameterUsage() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class T {", " static <@ImmutableTypeParameter T> void f() {}", "}") .doTest(); } @Test public void immutableTypeParameterUsage_interface() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "@Immutable interface T<@ImmutableTypeParameter T> {", "}") .doTest(); } @Test public void immutableTypeParameterMutableClass() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class A<@ImmutableTypeParameter T> {}") .doTest(); } @Test public void immutableTypeParameter_notAllTypeVarsInstantiated() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import java.util.function.Function;", "class Test {", " public final <A> void f1(A transform) {}", " public <B, @ImmutableTypeParameter C> C f2(Function<B, C> fn) {", " return null;", " }", " public final <D, E> void f3(Function<D, E> fn) {", " // BUG: Diagnostic contains: instantiation of 'C' is mutable", " // 'E' is a mutable type variable", " f1(f2(fn));", " }", "}") .doTest(); } // javac does not instantiate type variables when they are not used, so we cannot check whether // their instantiations are immutable. @Ignore @Test public void immutableTypeParameter_notAllTypeVarsInstantiated_shouldFail() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import java.util.function.Function;", "class Test {", " public final <A> void f1(A transform) {}", " public <@ImmutableTypeParameter B, C> C f2(Function<B, C> fn) {", " return null;", " }", " public final <D, E> void f3(Function<D, E> fn) {", " // BUG: Diagnostic contains: instantiation of 'B' is mutable", " // 'D' is a mutable type variable", " f1(f2(fn));", " }", "}") .doTest(); } @Test public void containerOf_extendsThreadSafe() { compilationHelper .addSourceLines( "X.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class X<V> {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "// BUG: Diagnostic contains: 'X' is not a container of 'V'", "@Immutable(containerOf = {\"Y\"}) class Test<Y> extends X<Y> {", " private final Y t = null;", "}") .doTest(); } @Test public void containerOf_extendsThreadSafeContainerOf() { compilationHelper .addSourceLines( "X.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf = {\"V\"}) class X<V> {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf = {\"Y\"}) class Test<Y> extends X<Y> {", " private final Y t = null;", "}") .doTest(); } @Test public void containerOf_extendsThreadSafe_nonContainer() { compilationHelper .addSourceLines( "X.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf = {\"V\"}) class X<U, V> {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf = {\"Y\"}) class Test<Y> extends X<Object, Y> {", " private final Y t = null;", "}") .doTest(); } @Test public void containerOf_extendsThreadSafe_interface() { compilationHelper .addSourceLines( "X.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface X<V> {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "// BUG: Diagnostic contains: 'X' is not a container of 'V'", "@Immutable(containerOf = {\"Y\"}) class Test<Y> implements X<Y> {", " private final Y t = null;", "}") .doTest(); } @Test public void containerOf_field() { compilationHelper .addSourceLines( "X.java", // "import com.google.errorprone.annotations.Immutable;", "@Immutable interface X<Y> {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"V\") class Test<V> {", " private final X<V> t = null;", "}") .doTest(); } @Test public void annotatedClassType() { compilationHelper .addSourceLines( "Test.java", "import static java.lang.annotation.ElementType.TYPE_USE;", "import java.lang.annotation.Target;", "@Target(TYPE_USE) @interface A {}", "class Test {", " Object o = new @A Object();", "}") .doTest(); } @Ignore("b/77333859") @Test public void immutableInterfaceImplementationCapturesMutableState() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface I {", " int f();", "}", "class Test {", " int x;", " I one = new I() {", " public int f() {", " return x++;", " }", " };", " I two = () -> x++;", "}") .doTest(); } @Test public void immutableUpperBound() { compilationHelper .addSourceLines( "MyImmutableType.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class MyImmutableType {}") .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test<T extends MyImmutableType, U extends T> {", " final T t = null;", " final U u = null;", " final ImmutableList<? extends U> v = null;", "}") .doTest(); } @Test public void immutableRecursiveUpperBound() { compilationHelper .addSourceLines( "Recursive.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable", "abstract class Recursive<T extends Recursive<T>> {", " final T x = null;", "}") .doTest(); } @Test public void immutableRecursiveUpperBound_notImmutable() { compilationHelper .addSourceLines( "Recursive.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "@Immutable", "abstract class Recursive<T extends Recursive<T>> {", " final T x = null;", " // BUG: Diagnostic contains: 'Recursive' has field 'y' of type 'java.util.List<T>'", " final List<T> y = null;", "}") .doTest(); } @Test public void immutableUpperBoundAndContainerOfInconsistency() { compilationHelper .addSourceLines( "ImmutableInterface.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface ImmutableInterface {}") .addSourceLines( "MutableImpl.java", "import com.google.errorprone.annotations.Immutable;", "@SuppressWarnings(\"Immutable\") class MutableImpl implements ImmutableInterface {", " int mutableField;", "}") .addSourceLines( "WithContainerOf.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf=\"T\")", "class WithContainerOf<T extends ImmutableInterface> { final T x = null; }") .addSourceLines( "WithoutContainerOf.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable", "class WithoutContainerOf<T extends ImmutableInterface> { final T x = null; }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " final WithContainerOf<ImmutableInterface> a = null;", " final WithoutContainerOf<ImmutableInterface> b = null;", " // BUG: Diagnostic contains: field 'c' of type 'WithContainerOf<MutableImpl>'", " final WithContainerOf<MutableImpl> c = null;", " final WithoutContainerOf<MutableImpl> d = null;", "}") .doTest(); } // regression test for b/77781008 @Test public void immutableTypeParameter_twoInstantiations() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "import com.google.common.collect.ImmutableList;", "@Immutable class Test<@ImmutableTypeParameter T> {", " <@ImmutableTypeParameter T> T f(T t) { return t; }", " <@ImmutableTypeParameter T> void g(T a, T b) {}", " @Immutable interface I {}", " void test(I i) {", " g(f(i), f(i));", " }", "}") .doTest(); } // regression test for b/148734874 @Test public void immutableTypeParameter_instantiations_negative() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "abstract class T {", " interface S<T> {}", " interface L<T> {}", " interface A {}", " @Immutable interface B extends A {}", " @Immutable interface C extends B {}", " abstract <X, Y, Z> void h(S<X> firstType, S<Y> secondType, S<Z> thirdType);", " abstract <@ImmutableTypeParameter E extends A> S<E> f(Class<E> entityClass);", " abstract <T> S<L<T>> g(S<T> element);", " void test() {", " // BUG: Diagnostic contains: the declaration of type 'T.A' is not annotated", " h(f(A.class), g(f(B.class)), g(f(C.class)));", " }", "}") .doTest(); } // regression test for b/181262633 @Test public void immutableTypeParameter_rawSuper() { compilationHelper .addSourceLines( "A.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "@Immutable class S<@ImmutableTypeParameter X> {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import com.google.errorprone.annotations.Immutable;", "// BUG: Diagnostic contains: 'S' required instantiation of 'X' with type parameters," + " but was raw", "@Immutable class T<@ImmutableTypeParameter X> extends S {}") .doTest(); } @Test public void mutable_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines("MutableClass.java", "class MutableClass { }") .addSourceLines( "Test.class", "class Test {", " private GenericWithImmutableParam<MutableClass> field;", "}") .doTest(); } @Test public void containerOf_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "ImmutableContainer.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf = \"T\") class ImmutableContainer<T> { }") .addSourceLines( "Test.class", "class Test {", " private GenericWithImmutableParam<ImmutableContainer<Object>> field;", "}") .doTest(); } @Test public void nestedImmutableTypeParameter_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Test.class", "class Test<T> {", " private GenericWithImmutableParam<T> field;", "}") .doTest(); } @Test public void localVariable_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines("MutableClass.java", "class MutableClass { }") .addSourceLines( "Test.class", "class Test {", " public void method() {", " GenericWithImmutableParam<MutableClass> value = null;", " }", "}") .doTest(); } @Test public void parameter_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines("MutableClass.java", "class MutableClass { }") .addSourceLines( "Test.class", "class Test {", " public void method(GenericWithImmutableParam<MutableClass> value) {}", "}") .doTest(); } @Test public void returnValue_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines("MutableClass.java", "class MutableClass { }") .addSourceLines( "Test.class", "class Test {", " public GenericWithImmutableParam<MutableClass> method() { return null; }", "}") .doTest(); } @Test public void genericStaticMethodParam_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Test.class", "class Test {", " public static <T> void method(GenericWithImmutableParam<T> value) { }", "}") .doTest(); } @Test public void genericStaticMethodReturnValue_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Test.class", "class Test {", " public static <T> GenericWithImmutableParam<T> method() { return null; }", "}") .doTest(); } @Test public void methodParameter_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Test.class", "class Test<T> {", " public void method(GenericWithImmutableParam<T> value) {}", "}") .doTest(); } @Test public void methodReturnValue_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Test.class", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class Test<T> {", " public GenericWithImmutableParam<T> method() { return null; }", "}") .doTest(); } @Test public void constructorParam_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Test.class", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class Test<T> {", " public Test(GenericWithImmutableParam<T> param) { }", "}") .doTest(); } @Test public void typecast_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines("MutableClass.java", "class MutableClass { }") .addSourceLines( "Test.class", "class Test {", " public void method() {", " Object obj = (GenericWithImmutableParam<MutableClass>) null;", " }", "}") .doTest(); } @Test public void new_violation() { withImmutableTypeParameterGeneric() .addSourceLines("MutableClass.java", "class MutableClass { }") .addSourceLines( "Test.class", "class Test {", " public Object method() {", " // BUG: Diagnostic contains: instantiation of 'T' is mutable, the declaration of" + " type 'MutableClass' is not annotated with" + " @com.google.errorprone.annotations.Immutable", " return new GenericWithImmutableParam<MutableClass>();", " }", "}") .doTest(); } @Test public void typeParameterExtendsMutable_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines("MutableClass.java", "class MutableClass { }") .addSourceLines( "Test.class", "class Test {", " public void method() {", " GenericWithImmutableParam<? extends MutableClass> value = null;", " }", "}") .doTest(); } @Test public void typeParameterExtendsImmutable_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "ImmutableClass.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class ImmutableClass { }") .addSourceLines( "Test.class", "class Test {", " public void method() {", " GenericWithImmutableParam<? extends ImmutableClass> value = null;", " }", "}") .doTest(); } @Test public void typeParameterSuper_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "ImmutableClass.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class ImmutableClass { }") .addSourceLines( "Test.class", "class Test {", " public void method() {", " GenericWithImmutableParam<? super ImmutableClass> value = null;", " }", "}") .doTest(); } @Test public void extendsImmutable_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "ImmutableClass.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class ImmutableClass { }") .addSourceLines( "ChildGenericWithImmutableParam.java", "class ChildGenericWithImmutableParam<T extends ImmutableClass> extends" + " GenericWithImmutableParam<T> { }") .doTest(); } @Test public void methodInvocation_violation() { compilationHelper .addSourceLines("MutableClass.java", "class MutableClass { }") .addSourceLines( "Clazz.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class Clazz {", " public <@ImmutableTypeParameter T> void method(int m, T v) { }", "}") .addSourceLines( "Invoker.java", "class Invoker {", " public void method() {", " // BUG: Diagnostic contains: instantiation of 'T' is mutable, the declaration of" + " type 'MutableClass' is not annotated with" + " @com.google.errorprone.annotations.Immutable", " new Clazz().method(78, new MutableClass());", " }", "}") .doTest(); } @Test public void containerOfAsImmutableTypeParameter_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Container.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf = {\"T\"}) class Container<T> {}") .addSourceLines( "Clazz.java", "class Clazz<T> { private GenericWithImmutableParam<Container<T>> container; }") .doTest(); } @Test public void containerOfAsImmutableTypeParameterInSameClass_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Container.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable(containerOf = {\"T\"}) class Container<T> { ", " GenericWithImmutableParam<T> method() { return null; }", "}") .doTest(); } @Test public void immutableTypeParameter_recursiveUpperBound() { compilationHelper .addSourceLines( "B.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable", "abstract class B<T extends B<T>> {}") .doTest(); } @Test public void immutableTypeParameter_recursiveUpperBoundUsage() { compilationHelper .addSourceLines( "B.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable", "interface B<T extends B<T>> {}") .addSourceLines( "A.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class A implements B<A> { final B<A> value = null; }") .doTest(); } @Test public void wildcard_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Test.class", "class Test {", " private final GenericWithImmutableParam<?> value = null;", "}") .doTest(); } @Test public void immutableTypeParameter_anonymousInstantiation_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Clazz.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class Clazz {", " private static final GenericWithImmutableParam<String> value = new" + " GenericWithImmutableParam<String>() {};", "}") .doTest(); } @Test public void immutableTypeParameter_anonymousInstantiation_violation() { withImmutableTypeParameterGeneric() .addSourceLines( "Clazz.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class Clazz {", " // BUG: Diagnostic contains: instantiation of 'T' is mutable, the declaration of" + " type 'Clazz.MutableClass' is not annotated with" + " @com.google.errorprone.annotations.Immutable", " private static final GenericWithImmutableParam<MutableClass> value = new" + " GenericWithImmutableParam<MutableClass>() {};", " private static class MutableClass {}", "}") .doTest(); } @Test public void nonGeneric_inheritanceClass_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "ChildGenericWithImmutableParam.java", "class ChildGenericWithImmutableParam extends GenericWithImmutableParam<String> { }") .doTest(); } @Test public void nonGeneric_inheritanceClass_violation() { withImmutableTypeParameterGeneric() .addSourceLines("MutableClass.java", "class MutableClass {}") .addSourceLines( "ChildGenericWithImmutableParam.java", "// BUG: Diagnostic contains: instantiation of 'T' is mutable, the declaration of type" + " 'MutableClass' is not annotated with" + " @com.google.errorprone.annotations.Immutable", "class ChildGenericWithImmutableParam extends GenericWithImmutableParam<MutableClass> {" + " }") .doTest(); } @Test public void nonGeneric_inheritanceInterface_noViolation() { compilationHelper .addSourceLines( "GenericWithImmutableParamIface.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "interface GenericWithImmutableParamIface<@ImmutableTypeParameter T> {}") .addSourceLines( "ChildGenericWithImmutableParam.java", "class ChildGenericWithImmutableParam implements GenericWithImmutableParamIface<String>" + " { }") .doTest(); } @Test public void nonGeneric_inheritanceInterface_violation() { compilationHelper .addSourceLines( "GenericWithImmutableParamIface.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "interface GenericWithImmutableParamIface<@ImmutableTypeParameter T> {}") .addSourceLines("MutableClass.java", "class MutableClass {}") .addSourceLines( "ChildGenericWithImmutableParam.java", "// BUG: Diagnostic contains: instantiation of 'T' is mutable, the declaration of type" + " 'MutableClass' is not annotated with" + " @com.google.errorprone.annotations.Immutable", "class ChildGenericWithImmutableParam implements" + " GenericWithImmutableParamIface<MutableClass> { }") .doTest(); } @Test public void inheritanceClass_violation() { withImmutableTypeParameterGeneric() .addSourceLines( "ChildGenericWithImmutableParam.java", "// BUG: Diagnostic contains: instantiation of 'T' is mutable, 'T' is a mutable type" + " variable", "class ChildGenericWithImmutableParam<T> extends GenericWithImmutableParam<T> { }") .doTest(); } @Test public void inheritanceClass_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "ChildGenericWithImmutableParam.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class ChildGenericWithImmutableParam<@ImmutableTypeParameter T> extends" + " GenericWithImmutableParam<T> { }") .doTest(); } @Test public void inheritanceInterface_violation() { compilationHelper .addSourceLines( "GenericWithImmutableParamIface.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "interface GenericWithImmutableParamIface<@ImmutableTypeParameter T> {}") .addSourceLines( "ChildGenericWithImmutableParam.java", "// BUG: Diagnostic contains: instantiation of 'T' is mutable, 'T' is a mutable type" + " variable", "class ChildGenericWithImmutableParam<T> implements GenericWithImmutableParamIface<T> {" + " }") .doTest(); } @Test public void inheritanceInterface_noViolation() { compilationHelper .addSourceLines( "GenericWithImmutableParamIface.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "interface GenericWithImmutableParamIface<@ImmutableTypeParameter T> {}") .addSourceLines( "ChildGenericWithImmutableParam.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class ChildGenericWithImmutableParam<@ImmutableTypeParameter T> implements" + " GenericWithImmutableParamIface<T> { }") .doTest(); } @CanIgnoreReturnValue private CompilationTestHelper withImmutableTypeParameterGeneric() { return compilationHelper.addSourceLines( "GenericWithImmutableParam.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "class GenericWithImmutableParam<@ImmutableTypeParameter T> {}"); } @Test public void lambda_cannotCloseAroundMutableField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " private int a = 0;", " void test(ImmutableFunction<Integer, Integer> f) {", " // BUG: Diagnostic contains:", " test(x -> ++a);", " }", "}") .doTest(); } @Test public void lambda_canCloseAroundImmutableField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " private final int b = 1;", " void test(ImmutableFunction<Integer, Integer> f) {", " test(x -> b);", " test(x -> this.b);", " }", "}") .doTest(); } @Test public void lambda_cannotCloseAroundMutableFieldQualifiedWithThis() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " private int b = 1;", " void test(ImmutableFunction<Integer, Integer> f) {", " // BUG: Diagnostic contains:", " test(x -> this.b);", " }", "}") .doTest(); } @Test public void lambda_cannotCloseAroundMutableLocal() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "import java.util.ArrayList;", "class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " void test(ImmutableFunction<Integer, Integer> f) {", " List<Integer> xs = new ArrayList<>();", " // BUG: Diagnostic contains:", " test(x -> xs.get(x));", " }", "}") .doTest(); } @Test public void notImmutableAnnotatedLambda_noFinding() { compilationHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "import java.util.function.Function;", "class Test {", " void test(Function<Integer, Integer> f) {", " List<Integer> xs = new ArrayList<>();", " test(x -> xs.get(x));", " }", "}") .doTest(); } @Test public void lambda_canHaveMutableVariablesWithin() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " void test(ImmutableFunction<Integer, Integer> f) {", " test(x -> { List<Integer> xs = new ArrayList<>(); return xs.get(x); });", " }", "}") .doTest(); } @Test public void lambda_canAccessStaticField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " static class A {", " public static int FOO = 1;", " }", " void test(ImmutableFunction<Integer, Integer> f) {", " test(x -> A.FOO);", " }", "}") .doTest(); } @Test public void lambda_cannotCallMethodOnMutableClass() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "abstract class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " abstract int mutable(int a);", " void test(ImmutableFunction<Integer, Integer> f) {", " // BUG: Diagnostic contains: This lambda implements @Immutable interface" + " 'ImmutableFunction', but accesses instance method(s) 'mutable' on 'Test' which" + " is not @Immutable", " test(x -> mutable(x));", " // BUG: Diagnostic contains: This lambda implements @Immutable interface" + " 'ImmutableFunction', but closes over 'this', which is not @Immutable because" + " 'Test' has field 'this' of type 'Test', the declaration of type 'Test' is not" + " annotated with @com.google.errorprone.annotations.Immutable", " test(x -> this.mutable(x));", " }", "}") .doTest(); } @Test public void lambda_canCallMethodOnImmutableClass() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable", "abstract class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " abstract int mutable(int a);", " void test(ImmutableFunction<Integer, Integer> f) {", " test(x -> mutable(x));", " test(x -> this.mutable(x));", " }", "}") .doTest(); } @Test public void checksEffectiveTypeOfReceiver() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.function.Function;", "@Immutable", "abstract class Test {", " @Immutable interface ImmutableFunction<A, B> extends Function<A, B> {", " default <C> ImmutableFunction<A, C> andThen(ImmutableFunction<B, C> fn) {", " return x -> fn.apply(apply(x));", " }", " }", "}") .doTest(); } @Test public void checksEffectiveTypeOfReceiver_whenNotDirectOuterClass() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.function.Function;", "@Immutable", "abstract class Test implements Function<String, String> {", " @Immutable interface ImmutableFunction { String apply(String a); }", " class A {", " ImmutableFunction asImmutable() {", " return x -> apply(x);", " }", " }", "}") .doTest(); } @Test public void methodReference_onImmutableType() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "import com.google.errorprone.annotations.Immutable;", "abstract class Test {", " @Immutable interface ImmutableFunction { String apply(String b); }", " void test(ImmutableFunction f) {", " ImmutableMap<String, String> map = ImmutableMap.of();", " test(map::get);", " }", "}") .doTest(); } @Test public void methodReference_onMutableType() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.HashMap;", "import java.util.Map;", "abstract class Test {", " @Immutable interface ImmutableFunction { String apply(String b); }", " void test(ImmutableFunction f) {", " Map<String, String> map = new HashMap<>();", " // BUG: Diagnostic contains:", " test(map::get);", " }", "}") .doTest(); } @Test public void methodReference_onExpressionWithMutableType() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.Maps;", "import com.google.errorprone.annotations.Immutable;", "abstract class Test {", " @Immutable interface ImmutableFunction { String apply(String b); }", " void test(ImmutableFunction f) {", " // BUG: Diagnostic contains:", " test(Maps.<String, String>newHashMap()::get);", " }", "}") .doTest(); } @Test public void methodReference_toStaticMethod() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.Lists;", "import com.google.errorprone.annotations.Immutable;", "abstract class Test {", " @Immutable interface ImmutableProvider { Object get(); }", " void test(ImmutableProvider f) {", " test(Lists::newArrayList);", " }", "}") .doTest(); } @Test public void methodReference_toUnboundMethodReference() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.Set;", "abstract class Test {", " @Immutable interface ImmutableBiConsumer { void accept(Set<String> xs, String x); }", " void test(ImmutableBiConsumer c) {", " test(Set::add);", " }", "}") .doTest(); } @Test public void methodReference_toConstructor() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.ArrayList;", "abstract class Test {", " @Immutable interface ImmutableProvider { Object get(); }", " void test(ImmutableProvider f) {", " test(ArrayList::new);", " }", "}") .doTest(); } @Test public void methodReference_immutableTypeParam() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import java.util.ArrayList;", "abstract class Test {", " interface ImmutableProvider<@ImmutableTypeParameter T> { T get(); }", " void test(ImmutableProvider<?> f) {", " // BUG: Diagnostic contains:", " test(ArrayList::new);", " }", "}") .doTest(); } @Test public void lambda_immutableTypeParam() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ImmutableTypeParameter;", "import java.util.ArrayList;", "abstract class Test {", " interface ImmutableProvider<@ImmutableTypeParameter T> { T get(); }", " void test(ImmutableProvider<?> f) {", " // BUG: Diagnostic contains:", " test(() -> new ArrayList<>());", " }", "}") .doTest(); } @Test public void chainedGettersAreAcceptable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " final Test t = null;", " final List<String> xs = new ArrayList<>();", " final List<String> getXs() {", " return xs;", " }", " @Immutable interface ImmutableFunction { String apply(String b); }", " void test(ImmutableFunction f) {", " test(x -> {", " Test t = new Test();", " return t.xs.get(0) + t.getXs().get(0) + t.t.t.xs.get(0);", " });", " }", "}") .doTest(); } @Test public void anonymousClass_cannotCloseAroundMutableLocal() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "import java.util.ArrayList;", "class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " void test(ImmutableFunction<Integer, Integer> f) {", " List<Integer> xs = new ArrayList<>();", " // BUG: Diagnostic contains:", " test(new ImmutableFunction<>() {", " @Override public Integer apply(Integer x) {", " return xs.get(x);", " }", " });", " }", "}") .doTest(); } @Test public void anonymousClass_hasMutableFieldSuppressed_noWarningAtUsageSite() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "import java.util.ArrayList;", "class Test {", " @Immutable interface ImmutableFunction<A, B> { A apply(B b); }", " void test(ImmutableFunction<Integer, Integer> f) {", " test(new ImmutableFunction<>() {", " @Override public Integer apply(Integer x) {", " return xs.get(x);", " }", " @SuppressWarnings(\"Immutable\")", " List<Integer> xs = new ArrayList<>();", " });", " }", "}") .doTest(); } @Test public void anonymousClass_canCallSuperMethodOnNonImmutableSuperClass() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "import java.util.List;", "import java.util.ArrayList;", "class Test {", " interface Function<A, B> { default void foo() {} }", " @Immutable interface ImmutableFunction<A, B> extends Function<A, B> { A apply(B b);" + " }", " void test(ImmutableFunction<Integer, Integer> f) {", " test(new ImmutableFunction<>() {", " @Override public Integer apply(Integer x) {", " foo();", " return 0;", " }", " });", " }", "}") .doTest(); } @Test public void switchExpressionsResultingInGenericTypes_doesNotThrow() { assumeTrue(RuntimeVersion.isAtLeast14()); compilationHelper .addSourceLines( "Kind.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable enum Kind { A, B; }") .addSourceLines( "Test.java", "import java.util.Optional;", "import java.util.function.Supplier;", "class Test {", " Supplier<Optional<String>> test(Kind kind) {", " return switch (kind) {", " case A -> Optional::empty;", " case B -> () -> Optional.of(\"\");", " };", " }", "}") .doTest(); } @Test public void switchExpressionsYieldStatement_doesNotThrow() { assumeTrue(RuntimeVersion.isAtLeast14()); compilationHelper .addSourceLines( "Test.java", "import java.util.function.Supplier;", "class Test {", " String test(String mode) {", " return switch (mode) {", " case \"random\" -> {", " yield \"foo\";", " }", " default -> throw new IllegalArgumentException();", " };", " }", "}") .doTest(); } @Test public void switchExpressionsMethodReference_doesNotThrow() { assumeTrue(RuntimeVersion.isAtLeast14()); compilationHelper .addSourceLines( "Test.java", "import java.util.function.Supplier;", "class Test {", " Supplier<Double> test(String mode) {", " return switch (mode) {", " case \"random\" -> Math::random;", " default -> throw new IllegalArgumentException();", " };", " }", "}") .doTest(); } @Test public void switchExpressionsYieldStatementMethodReference_doesNotThrow() { assumeTrue(RuntimeVersion.isAtLeast14()); compilationHelper .addSourceLines( "Test.java", "import java.util.function.Supplier;", "class Test {", " Supplier<Double> test(String mode) {", " return switch (mode) {", " case \"random\" -> {", " yield Math::random;", " }", " default -> throw new IllegalArgumentException();", " };", " }", "}") .doTest(); } @Test public void enumBound() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test<E extends Enum<E>> {", " private final E e;", " Test(E e) { this.e = e; }", "}") .doTest(); } }
105,565
33.174814
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.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.threadsafety; import com.google.errorprone.CompilationTestHelper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link GuardedByChecker}Test */ @RunWith(JUnit4.class) public class GuardedByCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(GuardedByChecker.class, getClass()); @Test public void locked() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " final Lock lock = null;", " @GuardedBy(\"lock\")", " int x;", " void m() {", " lock.lock();", " // BUG: Diagnostic contains:", " // access should be guarded by 'this.lock'", " x++;", " try {", " x++;", " } catch (Exception e) {", " x--;", " } finally {", " lock.unlock();", " }", " // BUG: Diagnostic contains:", " // access should be guarded by 'this.lock'", " x++;", " }", "}") .doTest(); } /** "static synchronized method() { ... }" == "synchronized (MyClass.class) { ... }" */ @Test public void staticLocked() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " @GuardedBy(\"Test.class\")", " static int x;", " static synchronized void m() {", " x++;", " }", "}") .doTest(); } @Test public void monitor() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import com.google.common.util.concurrent.Monitor;", "class Test {", " final Monitor monitor = null;", " @GuardedBy(\"monitor\")", " int x;", " void m() {", " monitor.enter();", " // BUG: Diagnostic contains:", " // access should be guarded by 'this.monitor'", " x++;", " try {", " x++;", " } finally {", " monitor.leave();", " }", " // BUG: Diagnostic contains:", " // access should be guarded by 'this.monitor'", " x++;", " }", "}") .doTest(); } @Test public void wrongLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " final Lock lock1 = null;", " final Lock lock2 = null;", " @GuardedBy(\"lock1\")", " int x;", " void m() {", " lock2.lock();", " try {", " // BUG: Diagnostic contains:", " // access should be guarded by 'this.lock1'", " x++;", " } finally {", " lock2.unlock();", " }", " }", "}") .doTest(); } @Test public void guardedStaticFieldAccess_1() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " public static final Object lock = new Object();", " @GuardedBy(\"lock\")", " public static int x;", " void m() {", " synchronized (Test.lock) {", " Test.x++;", " }", " }", "}") .doTest(); } @Test public void guardedStaticFieldAccess_2() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " public static final Object lock = new Object();", " @GuardedBy(\"lock\")", " public static int x;", " void m() {", " synchronized (lock) {", " Test.x++;", " }", " }", "}") .doTest(); } @Test public void guardedStaticFieldAccess_3() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " public static final Object lock = new Object();", " @GuardedBy(\"lock\")", " public static int x;", " void m() {", " synchronized (Test.lock) {", " x++;", " }", " }", "}") .doTest(); } @Test public void guardedStaticFieldAccess_enclosingClass() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " @GuardedBy(\"Test.class\")", " public static int x;", " synchronized static void n() {", " Test.x++;", " }", "}") .doTest(); } @Test public void badStaticFieldAccess() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " public static final Object lock = new Object();", " @GuardedBy(\"lock\")", " public static int x;", " void m() {", " // BUG: Diagnostic contains:", " // access should be guarded by 'Test.lock'", " Test.x++;", " }", "}") .doTest(); } @Test public void badGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " // BUG: Diagnostic contains: Invalid @GuardedBy expression", " @GuardedBy(\"foo\") int y;", "}") .doTest(); } @Test public void errorProneAnnotation() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.concurrent.GuardedBy;", "class Test {", " // BUG: Diagnostic contains: Invalid @GuardedBy expression", " @GuardedBy(\"foo\") int y;", "}") .doTest(); } @Test public void unheldInstanceGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " final Object mu = new Object();", " @GuardedBy(\"mu\") int y;", "}", "class Main {", " void m(Test t) {", " // BUG: Diagnostic contains:", " // should be guarded by 't.mu'", " t.y++;", " }", "}") .doTest(); } @Test public void unheldItselfGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Itself {", " @GuardedBy(\"itself\")", " int x;", " void incrementX() {", " // BUG: Diagnostic contains:", " // should be guarded by 'this.x'", " x++;", " }", "}") .doTest(); } @Test public void i541() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import java.util.List;", "import javax.annotation.concurrent.GuardedBy;", "class Itself {", " @GuardedBy(\"itself\")", " List<String> xs;", " void f() {", " // BUG: Diagnostic contains:", " // should be guarded by 'this.xs'", " this.xs.add(\"\");", " synchronized (this.xs) { this.xs.add(\"\"); }", " synchronized (this.xs) { xs.add(\"\"); }", " synchronized (xs) { this.xs.add(\"\"); }", " synchronized (xs) { xs.add(\"\"); }", " }", "}") .doTest(); } @Test public void methodQualifiedWithThis() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import java.util.List;", "import javax.annotation.concurrent.GuardedBy;", "class Itself {", " @GuardedBy(\"this\")", " void f() {};", " void g() {", " // BUG: Diagnostic contains:", " // should be guarded by 'this'", " this.f();", " synchronized (this) { f(); }", " synchronized (this) { this.f(); }", " }", "}") .doTest(); } @Test public void ctor() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " @GuardedBy(\"this\") int x;", " public Test() {", " this.x = 42;", " }", "}") .doTest(); } @Test public void badGuardMethodAccess() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " @GuardedBy(\"this\") void x() {}", " void m() {", " // BUG: Diagnostic contains: this", " x();", " }", "}") .doTest(); } @Test public void transitiveGuardMethodAccess() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " @GuardedBy(\"this\") void x() {}", " @GuardedBy(\"this\") void m() {", " x();", " }", "}") .doTest(); } @Ignore // TODO(cushon): support read/write lock copies @Test public void readWriteLockCopy() { compilationHelper .addSourceLines( "threadsafety.Test", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.ReentrantReadWriteLock;", "import java.util.concurrent.locks.Lock;", "class Test {", " final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();", " final Lock readLock = lock.readLock();", " final Lock writeLock = lock.writeLock();", " @GuardedBy(\"lock\") boolean b = false;", " void m() {", " readLock.lock();", " try {", " b = true;", " } finally {", " readLock.unlock();", " }", " }", " void n() {", " writeLock.lock();", " try {", " b = true;", " } finally {", " writeLock.unlock();", " }", " }", "}") .doTest(); } @Test public void readWriteLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.ReentrantReadWriteLock;", "class Test {", " final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();", " @GuardedBy(\"lock\") boolean b = false;", " void m() {", " lock.readLock().lock();", " try {", " b = true;", " } finally {", " lock.readLock().unlock();", " }", " }", " void n() {", " lock.writeLock().lock();", " try {", " b = true;", " } finally {", " lock.writeLock().unlock();", " }", " }", "}") .doTest(); } // Test that ReadWriteLocks are currently ignored. @Test public void readWriteLockIsIgnored() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.ReentrantReadWriteLock;", "class Test {", " final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();", " @GuardedBy(\"lock\") boolean b = false;", " void m() {", " try {", " b = true;", " } finally {", " }", " }", "}") .doTest(); } @Test public void innerClass_enclosingClassLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " final Object mu = new Object();", " @GuardedBy(\"mu\") boolean b = false;", " private final class Baz {", " public void m() {", " synchronized (mu) {", " n();", " }", " }", " @GuardedBy(\"Test.this.mu\")", " private void n() {", " b = true;", " }", " }", "}") .doTest(); } // notice lexically enclosing owner, use NamedThis! @Test public void innerClass_thisLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " @GuardedBy(\"this\") boolean b = false;", " private final class Baz {", " private synchronized void n() {", " // BUG: Diagnostic contains:", " // should be guarded by 'Test.this'", " b = true;", " }", " }", "}") .doTest(); } @Test public void anonymousClass() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " @GuardedBy(\"this\") boolean b = false;", " private synchronized void n() {", " b = true;", " new Object() {", " void m() {", " // BUG: Diagnostic contains:", " // should be guarded by 'Test.this'", " b = true;", " }", " };", " }", "}") .doTest(); } @Test public void inheritedLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class A {", " final Object lock = new Object();", "}", "class B extends A {", " @GuardedBy(\"lock\") boolean b = false;", " void m() {", " synchronized (lock) {", " b = true;", " };", " }", "}") .doTest(); } @Test public void enclosingSuperAccess() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class A {", " final Object lock = new Object();", " @GuardedBy(\"lock\") boolean flag = false;", "}", "class B extends A {", " void m() {", " new Object() {", " @GuardedBy(\"lock\")", " void n() {", " flag = true;", " }", " };", " }", "}") .doTest(); } @Test public void superAccess_this() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class A {", " final Object lock = new Object();", " @GuardedBy(\"this\") boolean flag = false;", "}", "class B extends A {", " synchronized void m() {", " flag = true;", " }", "}") .doTest(); } @Test public void superAccess_lock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class A {", " final Object lock = new Object();", " @GuardedBy(\"lock\") boolean flag = false;", "}", "class B extends A {", " void m() {", " synchronized (lock) {", " flag = true;", " }", " synchronized (this.lock) {", " flag = true;", " }", " }", "}") .doTest(); } @Test public void superAccess_staticLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class A {", " static final Object lock = new Object();", " @GuardedBy(\"lock\") static boolean flag = false;", "}", "class B extends A {", " void m() {", " synchronized (A.lock) {", " flag = true;", " }", " synchronized (B.lock) {", " flag = true;", " }", " }", "}") .doTest(); } @Test public void otherClass_bad_staticLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class A {", " static final Object lock = new Object();", " @GuardedBy(\"lock\") static boolean flag = false;", "}", "class B {", " static final Object lock = new Object();", " @GuardedBy(\"lock\") static boolean flag = false;", " void m() {", " synchronized (B.lock) {", " // BUG: Diagnostic contains:", " // should be guarded by 'A.lock'", " A.flag = true;", " }", " synchronized (A.lock) {", " // BUG: Diagnostic contains:", " // should be guarded by 'B.lock'", " B.flag = true;", " }", " }", "}") .doTest(); } @Test public void otherClass_bad_staticLock_alsoSub() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class A {", " static final Object lock = new Object();", " @GuardedBy(\"lock\") static boolean flag = false;", "}", "class B extends A {", " static final Object lock = new Object();", " @GuardedBy(\"lock\") static boolean flag = false;", " void m() {", " synchronized (B.lock) {", " // BUG: Diagnostic contains:", " // should be guarded by 'A.lock'", " A.flag = true;", " }", " synchronized (A.lock) {", " // BUG: Diagnostic contains:", " // should be guarded by 'B.lock'", " B.flag = true;", " }", " }", "}") .doTest(); } @Test public void otherClass_staticLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class A {", " static final Object lock = new Object();", " @GuardedBy(\"lock\") static boolean flag = false;", "}", "class B {", " void m() {", " synchronized (A.lock) {", " A.flag = true;", " }", " }", "}") .doTest(); } @Test public void instanceAccess_instanceGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class InstanceAccess_InstanceGuard {", " class A {", " final Object lock = new Object();", " @GuardedBy(\"lock\")", " int x;", " }", "", "class B extends A {", " void m() {", " synchronized (this.lock) {", " this.x++;", " }", " // BUG: Diagnostic contains:", " // should be guarded by 'this.lock'", " this.x++;", " }", "}", "}") .doTest(); } @Test public void instanceAccess_lexicalGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class InstanceAccess_LexicalGuard {", " class Outer {", " final Object lock = new Object();", " class Inner {", " @GuardedBy(\"lock\")", " int x;", " void m() {", " synchronized (Outer.this.lock) {", " this.x++;", " }", " // BUG: Diagnostic contains:", " // should be guarded by 'Outer.this.lock'", " this.x++;", " }", " }", " }", "}") .doTest(); } @Test public void lexicalAccess_instanceGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class LexicalAccess_InstanceGuard {", " class Outer {", " final Object lock = new Object();", " @GuardedBy(\"lock\")", " int x;", " class Inner {", " void m() {", " synchronized (Outer.this.lock) {", " Outer.this.x++;", " }", " // BUG: Diagnostic contains:", " // should be guarded by 'Outer.this.lock'", " Outer.this.x++;", " }", " }", " }", "}") .doTest(); } @Test public void lexicalAccess_lexicalGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class LexicalAccess_LexicalGuard {", " class Outer {", " final Object lock = new Object();", " class Inner {", " @GuardedBy(\"lock\")", " int x;", " class InnerMost {", " void m() {", " synchronized (Outer.this.lock) {", " Inner.this.x++;", " }", " // BUG: Diagnostic contains:", " // should be guarded by 'Outer.this.lock'", " Inner.this.x++;", " }", " }", " }", " }", "}") .doTest(); } @Test public void instanceAccess_thisGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class InstanceAccess_ThisGuard {", " class A {", " @GuardedBy(\"this\")", " int x;", " }", " class B extends A {", " void m() {", " synchronized (this) {", " this.x++;", " }", " // BUG: Diagnostic contains:", " // should be guarded by 'this'", " this.x++;", " }", " }", "}") .doTest(); } @Test public void instanceAccess_namedThisGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class InstanceAccess_NamedThisGuard {", " class Outer {", " class Inner {", " @GuardedBy(\"Outer.this\")", " int x;", " void m() {", " synchronized (Outer.this) {", " x++;", " }", " // BUG: Diagnostic contains:", " // should be guarded by 'Outer.this'", " x++;", " }", " }", " }", "}") .doTest(); } @Test public void lexicalAccess_thisGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class LexicalAccess_ThisGuard {", " class Outer {", " @GuardedBy(\"this\")", " int x;", " class Inner {", " void m() {", " synchronized (Outer.this) {", " Outer.this.x++;", " }", " // BUG: Diagnostic contains:", " // should be guarded by 'Outer.this'", " Outer.this.x++;", " }", " }", " }", "}") .doTest(); } @Test public void lexicalAccess_namedThisGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class LexicalAccess_NamedThisGuard {", " class Outer {", " class Inner {", " @GuardedBy(\"Outer.this\")", " int x;", " class InnerMost {", " void m() {", " synchronized (Outer.this) {", " Inner.this.x++;", " }", " // BUG: Diagnostic contains:", " // should be guarded by 'Outer.this'", " Inner.this.x++;", " }", " }", " }", " }", "}") .doTest(); } // Test that the analysis doesn't crash on lock expressions it doesn't recognize. // Note: there's currently no way to use @GuardedBy to specify that the guard is a specific array // element. @Test public void complexLockExpression() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class ComplexLockExpression {", " final Object[] xs = {};", " final int[] ys = {};", " void m(int i) {", " synchronized (xs[i]) {", " ys[i]++;", " }", " }", "}") .doTest(); } @Test public void wrongInnerClassInstance() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class WrongInnerClassInstance {", " final Object lock = new Object();", " class Inner {", " @GuardedBy(\"lock\") int x = 0;", " void m(Inner i) {", " synchronized (WrongInnerClassInstance.this.lock) {", " // BUG: Diagnostic contains:", " // guarded by 'lock' in enclosing instance" + " 'threadsafety.WrongInnerClassInstance' of 'i'", " i.x++;", " }", " }", " }", "}") .doTest(); } // (This currently passes because the analysis ignores try-with-resources, not because it // understands why this example is safe.) @Ignore // TODO(cushon): support try-with-resources @Test public void tryWithResources() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " Lock lock;", " @GuardedBy(\"lock\")", " int x;", " static class LockCloser implements AutoCloseable {", " Lock lock;", " LockCloser(Lock lock) {", " this.lock = lock;", " this.lock.lock();", " }", " @Override", " public void close() throws Exception {", " lock.unlock();", " }", " }", " void m() throws Exception {", " try (LockCloser _ = new LockCloser(lock)) {", " x++;", " }", " }", "}") .doTest(); } @Test public void tryWithResources_resourceVariables() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " Lock lock;", " @GuardedBy(\"lock\")", " int x;", " void m(AutoCloseable c) throws Exception {", " try (AutoCloseable unused = c) {", " // BUG: Diagnostic contains:", " x++;", " } catch (Exception e) {", " // BUG: Diagnostic contains:", " // should be guarded by 'this.lock'", " x++;", " throw e;", " } finally {", " // BUG: Diagnostic contains:", " // should be guarded by 'this.lock'", " x++;", " }", " }", "", " void n(AutoCloseable c) throws Exception {", " lock.lock();", " try (AutoCloseable unused = c) {", " } catch (Exception e) {", " x++;", " } finally {", " lock.unlock();", " }", " }", "}") .doTest(); } @Test public void lexicalScopingExampleOne() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Transaction {", " @GuardedBy(\"this\")", " int x;", " interface Handler {", " void apply();", " }", " public void handle() {", " runHandler(new Handler() {", " public void apply() {", " // BUG: Diagnostic contains:", " // should be guarded by 'Transaction.this'", " x++;", " }", " });", " }", " private synchronized void runHandler(Handler handler) {", " handler.apply();", " }", "}") .doTest(); } // TODO(cushon): allowing @GuardedBy on overridden methods is unsound. @Test public void lexicalScopingExampleTwo() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Transaction {", " @GuardedBy(\"this\")", " int x;", " interface Handler {", " void apply();", " }", " public void handle() {", " runHandler(new Handler() {", " @GuardedBy(\"Transaction.this\")", " public void apply() {", " x++;", " }", " });", " }", " private synchronized void runHandler(Handler handler) {", " // This isn't safe...", " handler.apply();", " }", "}") .doTest(); } @Test public void aliasing() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.List;", "import java.util.ArrayList;", "class Names {", " @GuardedBy(\"this\")", " List<String> names = new ArrayList<>();", " public void addName(String name) {", " List<String> copyOfNames;", " synchronized (this) {", " copyOfNames = names; // OK: access of 'names' guarded by 'this'", " }", " copyOfNames.add(name); // should be an error: this access is not thread-safe!", " }", "}") .doTest(); } @Test public void monitorGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import com.google.common.util.concurrent.Monitor;", "import java.util.List;", "import java.util.ArrayList;", "class Test {", " final Monitor monitor = new Monitor();", " @GuardedBy(\"monitor\") int x;", " final Monitor.Guard guard = new Monitor.Guard(monitor) {", " @Override public boolean isSatisfied() {", " x++;", " return true;", " }", " };", "}") .doTest(); } @Test public void semaphore() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.Semaphore;", "class Test {", " final Semaphore semaphore = null;", " @GuardedBy(\"semaphore\")", " int x;", " void m() throws InterruptedException {", " semaphore.acquire();", " // BUG: Diagnostic contains:", " // access should be guarded by 'this.semaphore'", " x++;", " try {", " x++;", " } finally {", " semaphore.release();", " }", " // BUG: Diagnostic contains:", " // access should be guarded by 'this.semaphore'", " x++;", " }", "}") .doTest(); } @Test public void synchronizedOnLockMethod_negative() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", // do not remove, regression test for a bug when RWL is on the classpath "import java.util.concurrent.locks.ReadWriteLock;", "class Test {", " Object lock() { return null; }", " @GuardedBy(\"lock()\")", " int x;", " void m() {", " synchronized (lock()) {", " x++;", " }", " }", "}") .doTest(); } @Test public void suppressLocalVariable() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " final Lock lock = null;", " @GuardedBy(\"lock\")", " int x;", " void m() {", " @SuppressWarnings(\"GuardedBy\")", " int z = x++;", " }", "}") .doTest(); } // regression test for issue 387 @Test public void enclosingBlockScope() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " public final Object mu = new Object();", " @GuardedBy(\"mu\") int x = 1;", " {", " new Object() {", " void f() {", " synchronized (mu) {", " x++;", " }", " }", " };", " }", "}") .doTest(); } @Ignore("b/26834754") // fix resolution of qualified type names @Test public void qualifiedType() { compilationHelper .addSourceLines( "lib/Lib.java", "package lib;", "public class Lib {", " public static class Inner {", " public static final Object mu = new Object();", " }", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " public final Object mu = new Object();", " @GuardedBy(\"lib.Lib.Inner.mu\") int x = 1;", " void f() {", " synchronized (lib.Lib.Inner.mu) {", " x++;", " }", " }", "}") .doTest(); } @Ignore("b/26834754") // fix resolution of qualified type names @Test public void innerClassTypeQualifier() { compilationHelper .addSourceLines( "lib/Lib.java", "package lib;", "public class Lib {", " public static class Inner {", " public static final Object mu = new Object();", " }", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import lib.Lib;", "public class Test {", " public final Object mu = new Object();", " @GuardedBy(\"Lib.Inner.mu\") int x = 1;", " void f() {", " synchronized (Lib.Inner.mu) {", " x++;", " }", " }", "}") .doTest(); } @Test public void instanceInitializersAreUnchecked() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " public final Object mu1 = new Object();", " public final Object mu2 = new Object();", " @GuardedBy(\"mu1\") int x = 1;", " {", " synchronized (mu2) {", " x++;", " }", " synchronized (mu1) {", " x++;", " }", " }", "}") .doTest(); } @Test public void classInitializersAreUnchecked() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " public static final Object mu1 = new Object();", " public static final Object mu2 = new Object();", " @GuardedBy(\"mu1\") static int x = 1;", " static {", " synchronized (mu2) {", " x++;", " }", " synchronized (mu1) {", " x++;", " }", " }", "}") .doTest(); } @Test public void staticFieldInitializersAreUnchecked() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " public static final Object mu = new Object();", " @GuardedBy(\"mu\") static int x0 = 1;", " static int x1 = x0++;", "}") .doTest(); } @Test public void instanceFieldInitializersAreUnchecked() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " public final Object mu = new Object();", " @GuardedBy(\"mu\") int x0 = 1;", " int x1 = x0++;", "}") .doTest(); } @Test public void innerClassMethod() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " public final Object mu = new Object();", " class Inner {", " @GuardedBy(\"mu\") int x;", " @GuardedBy(\"Test.this\") int y;", " }", " void f(Inner i) {", " synchronized (mu) {", " // BUG: Diagnostic contains:", " // guarded by 'mu' in enclosing instance 'threadsafety.Test' of 'i'", " i.x++;", " }", " }", " synchronized void g(Inner i) {", " // BUG: Diagnostic contains:", " // guarded by enclosing instance 'threadsafety.Test' of 'i'", " i.y++;", " }", "}") .doTest(); } @Ignore("b/128641856") @Test public void innerClassInMethod() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " public final Object mu = new Object();", " @GuardedBy(\"mu\") int i = 0;", " void f() {", " class Inner {", " @GuardedBy(\"mu\") void m() {i++;}", " }", " Inner i = new Inner();", " synchronized (mu) {", " i.m();", " }", " }", "}") .doTest(); } @Test public void innerClassMethod_classBoundary() { compilationHelper .addSourceLines( "threadsafety/Outer.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Outer {", " public final Object mu = new Object();", " class Inner {", " @GuardedBy(\"mu\") int x;", " @GuardedBy(\"Outer.this\") int y;", " }", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " void f() {", " Outer a = new Outer();", " Outer b = new Outer();", " Outer.Inner ai = a.new Inner();", " synchronized (b.mu) {", " // BUG: Diagnostic contains:", " // Access should be guarded by 'mu' in enclosing instance 'threadsafety.Outer'" + " of 'ai', which is not accessible in this scope; instead found: 'b.mu'", " ai.x++;", " }", " synchronized (b) {", " // BUG: Diagnostic contains:", " // Access should be guarded by enclosing instance 'threadsafety.Outer' of 'ai'," + " which is not accessible in this scope; instead found: 'b'", " ai.y++;", " }", " }", "}") .doTest(); } @Test public void regression_b27686620() { compilationHelper .addSourceLines( "A.java", // "class A extends One {", " void g() {}", "}") .addSourceLines( "B.java", "import javax.annotation.concurrent.GuardedBy;", "class One {", " @GuardedBy(\"One.class\") static int x = 1;", " static void f() { synchronized (One.class) { x++; } }", "}", "class Two {", " @GuardedBy(\"Two.class\") static int x = 1;", " static void f() { synchronized (Two.class) { x++; } }", "}") .addSourceLines( "C.java", // "class B extends Two {", " void g() {}", "}") .doTest(); } @Test public void qualifiedMethod() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " @GuardedBy(\"this\") void f() {}", " void main() {", " // BUG: Diagnostic contains: 'this', which could not be resolved", " new Test().f();", " Test t = new Test();", " // BUG: Diagnostic contains: guarded by 't'", " t.f();", " }", "}") .doTest(); } @Test public void qualifiedMethodWrongThis_causesFinding_whenMatchOnErrorsFlagNotSet() { CompilationTestHelper.newInstance(GuardedByChecker.class, getClass()) .addSourceLines( "MemoryAllocatedInfoJava.java", "import javax.annotation.concurrent.GuardedBy;", "public class MemoryAllocatedInfoJava {", " private static final class AllocationStats {", " @GuardedBy(\"MemoryAllocatedInfoJava.this\")", " void addAllocation(long size) {}", " }", " public void addStackTrace(long size) {", " synchronized (this) {", " AllocationStats stat = new AllocationStats();", " // BUG: Diagnostic contains: Access should be guarded by enclosing instance " + "'MemoryAllocatedInfoJava' of 'stat', which is not accessible in this scope; " + "instead found: 'this'", " stat.addAllocation(size);", " }", " }", "}") .doTest(); } // regression test for #426 @Test public void noSuchMethod() { compilationHelper .addSourceLines( "Foo.java", // "public class Foo {}") .addSourceLines( "Test.java", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " Foo foo;", " // BUG: Diagnostic contains: could not resolve guard", " @GuardedBy(\"foo.get()\") Object o = null;", "}") .doTest(); } // regression test for b/34251959 @Test public void lambda() { compilationHelper .addSourceLines( "Test.java", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " @GuardedBy(\"this\") int x;", " synchronized void f() {", " Runnable r = () -> {", " // BUG: Diagnostic contains: should be guarded by 'this',", " x++;", " };", " }", "}") .doTest(); } @Test public void multipleLocks() { compilationHelper .addSourceLines( "GuardedBy.java", // "@interface GuardedBy {", " String[] value() default {};", "}") .addSourceLines( "Test.java", "public class Test {", " private final Object mu = new Object();", " @GuardedBy({\"this\", \"mu\"}) int x;", " void f() {", " synchronized (this) {", " synchronized (mu) {", " x++;", " }", " }", " synchronized (this) {", " // BUG: Diagnostic contains: should be guarded by 'this.mu'", " x++;", " }", " synchronized (mu) {", " // BUG: Diagnostic contains: should be guarded by 'this'", " x++;", " }", " }", "}") .doTest(); } // Ensure sure outer instance handling doesn't accidentally include enclosing classes of // static member classes. @Test public void staticMemberClass_enclosingInstanceLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " final Object mu = new Object();", " private static final class Baz {", " // BUG: Diagnostic contains: could not resolve guard", " @GuardedBy(\"mu\") int x;", " }", " public void m(Baz b) {", " synchronized (mu) {", " // BUG: Diagnostic contains: 'mu', which could not be resolved", " b.x++;", " }", " }", "}") .doTest(); } // Ensure sure outer instance handling doesn't accidentally include enclosing classes of // static member classes. @Test public void staticMemberClass_staticOuterClassLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "public class Test {", " static final Object mu = new Object();", " private static final class Baz {", " @GuardedBy(\"mu\") int x;", " }", " public void m(Baz b) {", " synchronized (mu) {", " b.x++;", " }", " }", "}") .doTest(); } @Test public void newClassBase() { compilationHelper .addSourceLines( "Foo.java", "import javax.annotation.concurrent.GuardedBy;", "public class Foo {", " private final Object mu = new Object();", " @GuardedBy(\"mu\") int x;", "}") .addSourceLines( "Bar.java", "public class Bar {", " void bar (Foo f) {", " // BUG: Diagnostic contains: should be guarded by 'f.mu'", " f.x = 10;", " }", " void bar () {", " // BUG: Diagnostic contains: should be guarded by 'mu'", " new Foo().x = 11;", " }", "}") .doTest(); } @Test public void suppressionOnMethod() { compilationHelper .addSourceLines( "Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " final Object lock = null;", " void foo() {", " class Foo extends Object {", " @GuardedBy(\"lock\") int x;", " @SuppressWarnings(\"GuardedBy\")", " void m() {", " synchronized (lock) {", " int z = x++;", " }", " }", " }", " }", "}") .doTest(); } @Test public void missingGuard() { compilationHelper .addSourceLines( "threadsafety/Lib.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "@SuppressWarnings(\"GuardedBy\")", "class Lib {", " @GuardedBy(\"lock\")", " public void doSomething() {}", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " void m(Lib lib) {", " // BUG: Diagnostic contains: 'lock', which could not be resolved", " lib.doSomething();", " }", "}") .doTest(); } @Test public void parameterGuard() { compilationHelper .addSourceLines( "threadsafety/Test.java", "import javax.annotation.concurrent.GuardedBy;", "class Work {", " final Object lock = new Object();", " Object getLock() {", " return lock;", " }", " @GuardedBy(\"getLock()\")", " void workStarted() {", " }", "}", "class Worker {", " @GuardedBy(\"work.getLock()\")", " void f(Work work) {", " work.workStarted(); // ok", " }", " // BUG: Diagnostic contains: could not resolve guard", " @GuardedBy(\"work2.getLock()\") void g() {}", " @GuardedBy(\"a.getLock()\")", " void g(Work a, Work b) {", " a.workStarted(); // ok", " // BUG: Diagnostic contains: should be guarded by 'b.getLock()'; instead found:" + " 'a.getLock()'", " b.workStarted();", " }", "}", "abstract class Test {", " abstract Work getWork();", " void t(Worker worker, Work work) {", " synchronized(work.getLock()) {", " worker.f(work);", " }", " synchronized(getWork().getLock()) {", " // BUG: Diagnostic contains: guarded by 'work.getLock()'", " worker.f(getWork());", " }", " // BUG: Diagnostic contains: guarded by 'work.getLock()'", " worker.f(work);", " }", "}") .doTest(); } @Test public void parameterGuardNegative() { compilationHelper .addSourceLines( "threadsafety/Test.java", "import javax.annotation.concurrent.GuardedBy;", "class Work {", " final Object lock = new Object();", " Object getLock() {", " return lock;", " }", "}", "class Worker {", " @GuardedBy(\"work.getLock()\")", " void f(Work work) {", " }", "}", "class Test {", " void t(Worker worker, Work work) {", " synchronized(work.getLock()) {", " worker.f(work);", " }", " }", "}") .doTest(); } @Test public void parameterGuardNegativeSimpleName() { compilationHelper .addSourceLines( "threadsafety/Test.java", "import javax.annotation.concurrent.GuardedBy;", "class Work {", " final Object lock = new Object();", " Object getLock() {", " return lock;", " }", "}", "class Worker {", " @GuardedBy(\"work.getLock()\")", " void f(Work work) {", " }", " void g() {", " Work work = new Work();", " synchronized(work.getLock()) {", " f(work);", " }", " }", "}") .doTest(); } @Test public void varargsArity() { compilationHelper .addSourceLines( "threadsafety/Test.java", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " @GuardedBy(\"xs.toString()\")", " void f(int x, Object... xs) {", " }", " void g() {", " Object[] xs = null;", " synchronized(xs.toString()) {", " f(0, xs);", " }", " // BUG: Diagnostic contains:", " f(0);", " }", "}") .doTest(); } @Test public void immediateLambdas() { compilationHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "import java.util.Optional;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " @GuardedBy(\"this\") private final List<String> xs = new ArrayList<>();", " @GuardedBy(\"ys\") private final List<String> ys = new ArrayList<>();", " public synchronized void add(Optional<String> x) {", " x.ifPresent(y -> xs.add(y));", " x.ifPresent(xs::add);", " // BUG: Diagnostic contains:", " x.ifPresent(y -> ys.add(y));", " // BUG: Diagnostic contains:", " x.ifPresent(ys::add);", " }", "}") .doTest(); } @Test public void methodReferences_shouldBeFlagged() { compilationHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "import java.util.Optional;", "import java.util.function.Predicate;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " @GuardedBy(\"this\") private final List<String> xs = new ArrayList<>();", " private final List<Predicate<String>> preds = new ArrayList<>();", " public synchronized void test() {", " // BUG: Diagnostic contains:", " preds.add(xs::contains);", " }", "}") .doTest(); } @Test public void methodReference_referencedMethodIsFlagged() { compilationHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "import java.util.Optional;", "import java.util.function.Predicate;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " private final List<Predicate<String>> preds = new ArrayList<>();", " public synchronized void test() {", " Optional.of(\"foo\").ifPresent(this::frobnicate);", " // BUG: Diagnostic contains: should be guarded by", " preds.add(this::frobnicate);", " }", " @GuardedBy(\"this\")", " public boolean frobnicate(String x) {", " return true;", " }", "}") .doTest(); } }
63,164
31.112354
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/SynchronizeOnNonFinalFieldTest.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.threadsafety; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link SynchronizeOnNonFinalFieldTest}Test */ @RunWith(JUnit4.class) public class SynchronizeOnNonFinalFieldTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(SynchronizeOnNonFinalField.class, getClass()); @Test public void positive1() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "class Test {", " Object lock = new Object();", " void m() {", " // BUG: Diagnostic contains: Synchronizing on non-final fields is not safe", " synchronized (lock) {}", " }", "}") .doTest(); } @Test public void positive2() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "class Test {", " Object lock = new Object();", " Test[] tx = null;", " void m(int i) {", " // BUG: Diagnostic contains: Synchronizing on non-final fields is not safe", " synchronized (this.tx[i].lock) {}", " }", "}") .doTest(); } @Test public void positive3() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "class Test {", " Object lock = new Object();", " void m(Test t) {", " // BUG: Diagnostic contains: Synchronizing on non-final fields is not safe", " synchronized (t.lock) {}", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "class Test {", " final Object lock = new Object();", " void m() {", " synchronized (lock) {}", " }", "}") .doTest(); } @Test public void negative_lazyInit() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import com.google.errorprone.annotations.concurrent.LazyInit;", "class Test {", " @LazyInit transient Object lock = new Object();", " void m() {", " synchronized (lock) {}", " }", "}") .doTest(); } @Test public void negative_writer() { compilationHelper .addSourceLines( "Test.java", "import java.io.Writer;", "abstract class Test extends Writer {", " void m() {", " synchronized (lock) {}", " }", "}") .doTest(); } }
3,689
28.758065
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByValidatorTest.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.threadsafety; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link GuardedByChecker} annotation syntax GuardedByValidationResult test */ @RunWith(JUnit4.class) public class GuardedByValidatorTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(GuardedByChecker.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: could not resolve guard", " @GuardedBy(\"This thread\") int x;", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: could not resolve guard", " @GuardedBy(\"This thread\") void m() {}", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " final Object mu = new Object();", " class Inner {", " @GuardedBy(\"this\") int x;", " @GuardedBy(\"Test.this\") int p;", " @GuardedBy(\"Test.this.mu\") int z;", " @GuardedBy(\"this\") void m() {}", " @GuardedBy(\"mu\") int v;", " @GuardedBy(\"itself\") Object s_;", " }", " final Object o = new Object() {", " @GuardedBy(\"mu\") int x;", " };", "}") .doTest(); } @Test public void itself() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " @GuardedBy(\"itself\") Object s_;", "}") .doTest(); } @Test public void badInstanceAccess() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " final Object instanceField = new Object();", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: could not resolve guard", " @GuardedBy(\"Test.instanceField\") Object s_;", "}") .doTest(); } @Test public void className() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: could not resolve guard", " @GuardedBy(\"Test\") Object s_;", "}") .doTest(); } @Test public void anonymousClassTypo() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " static class Endpoint {", " Object getLock() { return null; }", " }", " abstract static class Runnable {", " private Endpoint endpoint;", " Runnable(Endpoint endpoint) {", " this.endpoint = endpoint;", " }", " abstract void run();", " }", " static void m(Endpoint endpoint) {", " Runnable runnable =", " new Runnable(endpoint) {", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: could not resolve guard", " @GuardedBy(\"endpoint_.getLock()\") void run() {}", " };", " }", "}") .doTest(); } @Test public void anonymousClassPrivateAccess() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " static class Endpoint {", " Object getLock() { return null; }", " }", " abstract static class Runnable {", " private Endpoint endpoint;", " Runnable(Endpoint endpoint) {", " this.endpoint = endpoint;", " }", " abstract void run();", " }", " static void m(Endpoint endpoint) {", " Runnable runnable =", " new Runnable(endpoint) {", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: could not resolve guard", " @GuardedBy(\"endpoint.getLock()\") void run() {}", " };", " }", "}") .doTest(); } @Test public void staticGuardedByInstance() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: static member guarded by instance", " @GuardedBy(\"this\") static int x;", "}") .doTest(); } @Test public void staticGuardedByInstanceMethod() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " final Object mu_ = new Object();", " Object lock() { return mu_; }", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: static member guarded by instance", " @GuardedBy(\"lock()\") static int x;", "}") .doTest(); } @Test public void staticGuardedByStatic() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " @GuardedBy(\"Test.class\") static int x;", "}") .doTest(); } @Test public void nonExistantMethod() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety.Test;", "import javax.annotation.concurrent.GuardedBy;", "class Test {", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: could not resolve guard", " @GuardedBy(\"lock()\") int x;", " // BUG: Diagnostic contains:", " // Invalid @GuardedBy expression: could not resolve guard", " @GuardedBy(\"lock()\") void m() {}", "}") .doTest(); } }
8,118
32.970711
84
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableAnnotationCheckerTest.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.threadsafety; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ImmutableAnnotationChecker}Test */ @RunWith(JUnit4.class) public class ImmutableAnnotationCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ImmutableAnnotationChecker.class, getClass()); @Test public void nonFinalField() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "class Test implements Deprecated {", " public Class<? extends Annotation> annotationType() { return Deprecated.class; }", " // BUG: Diagnostic contains: final int x;'", " int x;", " private Test(int x) {", " this.x = x;", " }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", "}") .doTest(); } @Test public void immutable() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import com.google.common.collect.ImmutableSet;", "class Test implements Deprecated {", " public Class<? extends Annotation> annotationType() { return Deprecated.class; }", " final Annotation annotation;", " private Test(Annotation annotation) {", " this.annotation = annotation;", " }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", "}") .doTest(); } @Test public void finalMutableField() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import java.util.Arrays;", "import java.util.HashSet;", "import java.util.Set;", "class Test implements Deprecated {", " public Class<? extends Annotation> annotationType() { return Deprecated.class; }", " // BUG: Diagnostic contains: annotations should be immutable: 'Test' has field 'xs'" + " of type 'java.util.Set<java.lang.Integer>', 'Set' is mutable", " final Set<Integer> xs;", " private Test(Integer... xs) {", " this.xs = new HashSet<>(Arrays.asList(xs));", " }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", "}") .doTest(); } @Test public void annotated() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import com.google.errorprone.annotations.Immutable;", "// BUG: Diagnostic contains: annotations are immutable by default", "@Immutable", "class Test implements Deprecated {", " public Class<? extends Annotation> annotationType() { return Deprecated.class; }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", "}") .doTest(); } @Test public void mutableFieldType() { compilationHelper .addSourceLines("Foo.java", "class Foo {", "}") .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import java.util.Arrays;", "import java.util.HashSet;", "import java.util.Set;", "class Test implements Deprecated {", " public Class<? extends Annotation> annotationType() { return Deprecated.class; }", " // BUG: Diagnostic contains:" + " the declaration of type 'Foo' is not annotated with" + " @com.google.errorprone.annotations.Immutable", " final Foo f;", " private Test(Foo f) {", " this.f = f;", " }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", "}") .doTest(); } @Test public void anonymous() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import com.google.common.collect.ImmutableSet;", "class Test {{", " new Deprecated() {", " public Class<? extends Annotation> annotationType() { return Deprecated.class; }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", " };", "}}") .doTest(); } @Test public void anonymousReferencesEnclosing() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import java.util.Objects;", "import com.google.common.collect.ImmutableSet;", "class Test {{", " // BUG: Diagnostic contains: 'Deprecated' has mutable enclosing instance", " new Deprecated() {", " {", " Objects.requireNonNull(Test.this);", " }", " public Class<? extends Annotation> annotationType() { return Deprecated.class; }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", " };", "}}") .doTest(); } @Test public void anonymousReferencesEnum() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import java.util.Objects;", "import com.google.common.collect.ImmutableSet;", "enum Test {", " ;", " {", " new Deprecated() {", " {", " Objects.requireNonNull(Test.this);", " }", " public Class<? extends Annotation> annotationType() {", " return Deprecated.class;", " }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", " };", " }", "}") .doTest(); } @Test public void anonymousCapturesLocal() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import java.util.Objects;", "import com.google.common.collect.ImmutableSet;", "class Test {", " int x;", // Test is mutable " void f(int y) {", " new Deprecated() {", " void g() {", " System.err.println(y);", // capture a local (but not the enclosing instance) " }", " public Class<? extends Annotation> annotationType() {", " return Deprecated.class;", " }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", " };", " }", "}") .doTest(); } @Test public void otherAnnotation() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import java.util.Objects;", "import com.google.common.collect.ImmutableSet;", "class Test {", " @SuppressWarnings(\"Immutable\")", " class A implements Annotation {", " private int i = 0;", " public int count() {", " return i++;", " }", " public Class<? extends Annotation> annotationType() {", " return Deprecated.class;", " }", " }", " class B implements Annotation {", " final A a = null;", " public Class<? extends Annotation> annotationType() {", " return Deprecated.class;", " }", " }", "}") .doTest(); } @Test public void annotationSuper() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import java.util.Objects;", "import com.google.common.collect.ImmutableSet;", "class Test {", " class MyAnno implements Annotation {", " public Class<? extends Annotation> annotationType() {", " return Deprecated.class;", " }", " }", " {", " new MyAnno() {", " };", " }", "}") .doTest(); } @Test public void jucImmutable() { compilationHelper .addSourceLines( "Lib.java", // "import javax.annotation.concurrent.Immutable;", "@Immutable", "class Lib {", "}") .addSourceLines( "Test.java", // "import java.lang.annotation.Annotation;", "class MyAnno implements Annotation {", " // BUG: Diagnostic contains:" + " not annotated with @com.google.errorprone.annotations.Immutable", " final Lib l = new Lib();", " public Class<? extends Annotation> annotationType() {", " return Deprecated.class;", " }", "}") .doTest(); } @Test public void generated() { compilationHelper .addSourceLines( "Test.java", "import java.lang.annotation.Annotation;", "import javax.annotation.processing.Generated;", "@Generated(\"com.google.auto.value.processor.AutoAnnotationProcessor\")", "class Test implements Deprecated {", " public Class<? extends Annotation> annotationType() { return Deprecated.class; }", " int x;", " private Test(int x) {", " this.x = x;", " }", " public boolean forRemoval() {", " return false;", " }", " public String since() {", " return \"\";", " }", "}") .doTest(); } }
12,016
32.473538
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ThreadPriorityCheckTest.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.threadsafety; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * {@link ThreadPriorityCheck}Test * * @author siyuanl@google.com (Siyuan Liu) * @author eleanorh@google.com (Eleanor Harris) */ @RunWith(JUnit4.class) public final class ThreadPriorityCheckTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ThreadPriorityCheck.class, getClass()); @Test public void yieldThread() { compilationHelper .addSourceLines( "Test.java", "class Test {", " public void foo() {", " Thread myThread = new Thread(new Runnable() {", " @Override", " public void run() {", " System.out.println(\"Run, thread, run!\");", " }", " });", " myThread.start();", " // BUG: Diagnostic contains: ThreadPriorityCheck", " Thread.yield();", " }", "}") .doTest(); } @Test public void setPriority() { compilationHelper .addSourceLines( "Test.java", "class Test {", " public void foo() {", " Thread thread = new Thread(new Runnable() {", " @Override", " public void run() {", " System.out.println(\"Run, thread, run!\");", " }", " });", " thread.start();", " // BUG: Diagnostic contains: ThreadPriorityCheck", " thread.setPriority(Thread.MAX_PRIORITY);", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "class Test {", " public void foo() {", " Thread thread = new Thread(new Runnable() {", " @Override", " public void run() {", " System.out.println(\"Run, thread, run!\");", " }", " });", " thread.start();", " }", "}") .doTest(); } }
2,937
29.28866
79
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockAnalyzerTest.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.threadsafety; 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.matchers.Description; import com.sun.source.tree.Tree; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link GuardedByLockSetAnalyzer}Test */ @RunWith(JUnit4.class) public class HeldLockAnalyzerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(GuardedByLockSetAnalyzer.class, getClass()); @Test public void instance() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " final Lock lock = null;", " @GuardedBy(\"lock\")", " int x;", " void m() {", " lock.lock();", " try {", " // BUG: Diagnostic contains:", " // [(SELECT (THIS) lock)]", " x++;", " } finally { lock.unlock(); }", " }", "}") .doTest(); } @Test public void twoInstances() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " final Lock lock = null;", " @GuardedBy(\"lock\")", " int x;", " void m(Lock lock2) {", " lock.lock();", " lock2.lock();", " try {", " // BUG: Diagnostic contains:", " // [(LOCAL_VARIABLE lock2), (SELECT (THIS) lock)]", " x++;", " } finally { lock.unlock(); lock2.unlock(); }", " }", "}") .doTest(); } @Test public void synchronizedMethod() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " @GuardedBy(\"this\")", " int x;", " synchronized void m() {", " // BUG: Diagnostic contains: [(THIS)]", " x++;", " }", "}") .doTest(); } @Test public void synchronizedThis() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " @GuardedBy(\"this\")", " int x;", " void m() {", " synchronized (this) {", " // BUG: Diagnostic contains: [(THIS)]", " x++;", " }", " }", "}") .doTest(); } @Test public void synchronizedField() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Lock { final Object lock = null; }", "class Test {", " final Lock mu = new Lock();", " @GuardedBy(\"this\")", " int x;", " void m() {", " synchronized (mu.lock) {", " // BUG: Diagnostic contains:", " // [(SELECT (SELECT (THIS) mu) lock)]", " x++;", " }", " }", "}") .doTest(); } @Test public void synchronizedClass() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "class Lock {}", "class Test {", " final Lock mu = new Lock();", " @GuardedBy(\"this\")", " int x;", " void m() {", " synchronized (Lock.class) {", " // BUG: Diagnostic contains: [(CLASS_LITERAL threadsafety.Lock)]", " x++;", " }", " }", "}") .doTest(); } @Test public void locked() { compilationHelper .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", "import java.util.concurrent.locks.Lock;", "class Test {", " final Lock mu = null;", " final Lock lock = null;", " @GuardedBy(\"lock\")", " int x;", " void m() {", " mu.lock();", " // BUG: Diagnostic contains: []", " x++;", " try {", " // BUG: Diagnostic contains:", " // [(SELECT (THIS) mu)]", " x++;", " } finally {", " mu.unlock();", " }", " // BUG: Diagnostic contains: []", " x++;", " }", "}") .doTest(); } /** A customized {@link GuardedByChecker} that prints more test-friendly diagnostics. */ @BugPattern(name = "GuardedByLockSet", summary = "", explanation = "", severity = ERROR) public static class GuardedByLockSetAnalyzer extends GuardedByChecker { @Override protected Description checkGuardedAccess( Tree tree, GuardedByExpression guard, HeldLockSet live, VisitorState state) { List<String> toSort = new ArrayList<>(); for (GuardedByExpression node : live.allLocks()) { toSort.add(node.debugPrint()); } Collections.sort(toSort); return buildDescription(tree).setMessage("Holding: " + toSort).build(); } } }
7,041
31.155251
90
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableRefactoringTest.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.threadsafety; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ImmutableRefactoring}Test */ @RunWith(JUnit4.class) public final class ImmutableRefactoringTest { private final BugCheckerRefactoringTestHelper compilationHelper = BugCheckerRefactoringTestHelper.newInstance(ImmutableRefactoring.class, getClass()); @Test public void positive() { compilationHelper .addInputLines( "Test.java", "import javax.annotation.concurrent.Immutable;", "@Immutable class Test {", " final int a = 42;", " final String b = null;", "}") .addOutputLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " final int a = 42;", " final String b = null;", "}") .doTest(); } @Test public void someImmutableSomeNot() { compilationHelper .addInputLines( "Test.java", "import javax.annotation.concurrent.Immutable;", "@Immutable class Test {", " int a = 42;", " @Immutable static class Inner {", " final int a = 43;", " }", "}") .addOutputLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "// This class was annotated with javax.annotation.concurrent.Immutable, but didn't" + " seem to be provably immutable.", "class Test {", " int a = 42;", " @Immutable ", " static class Inner {", " final int a = 43;", " }", "}") .doTest(TEXT_MATCH); } @Test public void negative() { compilationHelper .addInputLines( "Test.java", "import javax.annotation.concurrent.Immutable;", "@Immutable class Test {", " int a = 42;", "}") .addOutputLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "// This class was annotated with javax.annotation.concurrent.Immutable, but didn't" + " seem to be provably immutable.", "class Test {", " int a = 42;", "}") .doTest(TEXT_MATCH); } @Test public void negative_multipleClasses() { compilationHelper .addInputLines( "Test.java", "import javax.annotation.concurrent.Immutable;", "@Immutable class Test {", " int a = 42;", " @Immutable static class Inner {", " int a = 43;", " }", "}") .addOutputLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "// This class was annotated with javax.annotation.concurrent.Immutable, but didn't" + " seem to be provably immutable.", "class Test {", " int a = 42;", " // This class was annotated with javax.annotation.concurrent.Immutable, but didn't" + " seem to be provably immutable.", " static class Inner {", " int a = 43;", " }", "}") .doTest(TEXT_MATCH); } }
4,224
32.267717
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeCheckerTest.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.threadsafety; import com.google.common.collect.ImmutableList; import com.google.common.io.ByteStreams; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.annotations.ThreadSafe; import com.google.errorprone.annotations.concurrent.LazyInit; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ThreadSafeChecker}Test */ @RunWith(JUnit4.class) public class ThreadSafeCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ThreadSafeChecker.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(ThreadSafeChecker.class, getClass()); @Test public void basicFields() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.concurrent.ConcurrentMap;", "import java.util.concurrent.atomic.AtomicLong;", "@ThreadSafe class Test {", " final int a = 42;", " final String b = null;", " final java.lang.String c = null;", " final com.google.common.collect.ImmutableList<String> d = null;", " final ImmutableList<Integer> e = null;", " final Deprecated dep = null;", " final Class<?> clazz = Class.class;", " final ConcurrentMap<Long, AtomicLong> concurrentMap = null;", "}") .doTest(); } @Test public void interfacesMutableByDefault() { compilationHelper .addSourceLines("I.java", "interface I {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: 'I' is not annotated with @" + ThreadSafe.class.getName(), " private final I i = new I() {};", "}") .doTest(); } @Test public void refactoringWithNameClash() { refactoringHelper .addInputLines( "I.java", // "@com.google.errorprone.annotations.ThreadSafe interface I {}") .expectUnchanged() .addInputLines( "ThreadSafe.java", // "class ThreadSafe implements I {", "}") .addOutputLines( "ThreadSafe.java", "@com.google.errorprone.annotations.ThreadSafe class ThreadSafe implements I {", "}") .doTest(); } @Test public void annotationsCanBeAnnotatedWithThreadSafe() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe @interface Test {}") .doTest(); } @Test public void customAnnotationsMightBeMutable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe @interface Test {}") .addSourceLines( "MyTest.java", "import com.google.errorprone.annotations.ThreadSafe;", "import java.lang.annotation.Annotation;", "@ThreadSafe final class MyTest implements Test {", " // BUG: Diagnostic contains: should be final or annotated", " public Object[] xs = {};", " public Class<? extends Annotation> annotationType() {", " return null;", " }", "}") .doTest(); } @Test public void customAnnotationsSubtype() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe @interface Test {}") .addSourceLines( "MyTest.java", "import java.lang.annotation.Annotation;", "// BUG: Diagnostic contains:", "// extends @ThreadSafe type Test, but is not annotated as threadsafe", "final class MyTest implements Test {", " public Object[] xs = {};", " public Class<? extends Annotation> annotationType() {", " return null;", " }", "}") .doTest(); } @Test public void annotationsDefaultToImmutable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import javax.lang.model.element.ElementKind;", "@ThreadSafe class Test {", " private final Override override = null;", "}") .doTest(); } @Test public void enumsDefaultToImmutable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import javax.lang.model.element.ElementKind;", "@ThreadSafe class Test {", " private final ElementKind ek = null;", "}") .doTest(); } @Test public void enumsMayBeImmutable() { compilationHelper .addSourceLines( "Kind.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe enum Kind { A, B, C; }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " private final Kind k = null;", "}") .doTest(); } @Test public void mutableArray() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains:", " final int[] xs = {42};", "}") .doTest(); } @Test public void immutableAnnotatedNotTested() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test {", " final int[] xs = {42};", "}") .doTest(); } @Test public void immutableAnnotatedNotTested_inheritance() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface Test {}") .addSourceLines( "MyTest.java", "final class MyTest implements Test {", " public Object[] xs = {};", "}") .doTest(); } @Test public void annotatedThreadSafeInterfaces() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe interface Test {}") .doTest(); } @Test public void threadSafeInterfaceField() { compilationHelper .addSourceLines( "MyInterface.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe interface MyInterface {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " final MyInterface i = null;", "}") .doTest(); } @Test public void immutableInterfaceField() { compilationHelper .addSourceLines( "MyInterface.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface MyInterface {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " final MyInterface i = null;", "}") .doTest(); } @Test public void deeplyImmutableArguments() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " final ImmutableList<ImmutableList<ImmutableList<String>>> l = null;", "}") .doTest(); } @Test public void deeplyThreadsafeArguments() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.concurrent.ConcurrentMap;", "import java.util.concurrent.atomic.AtomicInteger;", "@ThreadSafe class Test {", " final ConcurrentMap<String, ConcurrentMap<Long,", " ImmutableList<AtomicInteger>>> l = null;", "}") .doTest(); } @Test public void mutableNonFinalField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: should be final or annotated", " int a = 42;", "}") .doTest(); } @Test public void mutableStaticFields() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.List;", "import java.util.Map;", "@ThreadSafe class Test {", " static int a = 42;", " static final Map<Long, List<Long>> b = null;", "}") .doTest(); } @Test public void mutableFieldGuardedByJsr305Annotation() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.List;", "import java.util.Map;", "import javax.annotation.concurrent.GuardedBy;", "@ThreadSafe class Test {", " @GuardedBy(\"this\") int a = 42;", " @GuardedBy(\"this\") final Map<Long, List<Long>> b = null;", " @GuardedBy(\"this\") volatile int c = 42;", "}") .doTest(); } @Test public void mutableFieldGuardedByErrorProneAnnotation() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import com.google.errorprone.annotations.concurrent.GuardedBy;", "import java.util.List;", "import java.util.Map;", "@ThreadSafe class Test {", " @GuardedBy(\"this\") int a = 42;", " @GuardedBy(\"this\") final Map<Long, List<Long>> b = null;", " @GuardedBy(\"this\") volatile int c = 42;", "}") .doTest(); } @Test public void mutableFieldNotGuarded() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import javax.annotation.concurrent.GuardedBy;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: @GuardedBy", " volatile int a = 42;", "}") .doTest(); } @Test public void mutableField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.Map;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains:", " final Map<String, String> a = null;", "}") .doTest(); } @Test public void deeplyMutableTypeArguments() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.Map;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: instantiated with non-thread-safe type for 'E'", " final ImmutableList<ImmutableList<ImmutableList<Map<String, String>>>> l = null;", "}") .doTest(); } @Test public void rawImpliesImmutable() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: was raw", " final ImmutableList l = null;", "}") .doTest(); } @Test public void extendsThreadSafe() { compilationHelper .addSourceLines( "Super.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe public class Super {", " public final int x = 42;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test extends Super {", "}") .doTest(); } @Test public void extendsThreadSafe_annotatedWithImmutable() { compilationHelper .addSourceLines( "Super.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe public class Super {", " public final int x = 42;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable class Test extends Super {", "}") .doTest(); } @Test public void extendsMutable() { compilationHelper .addSourceLines( "Super.java", // "public class Super {", " public int x = 42;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "// BUG: Diagnostic contains: 'Super' has non-final field 'x'", "@ThreadSafe class Test extends Super {", "}") .doTest(); } @Test public void mutableTypeArgumentInstantiation() { compilationHelper .addSourceLines( "Holder.java", "import com.google.errorprone.annotations.ThreadSafe;", "public class Holder<T> {", " public final T t = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains:", " final Holder<Object> h = null;", "}") .doTest(); } @Test public void instantiationWithMutableType() { compilationHelper .addSourceLines( "Holder.java", "import com.google.errorprone.annotations.ThreadSafe;", "public class Holder<T> {", " public final T t = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: not annotated", " final Holder<Object> h = null;", "}") .doTest(); } @Test public void missingContainerOf() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.List;", "@ThreadSafe class Test<T> {", " // BUG: Diagnostic contains: 'T' is a non-thread-safe type variable", " private final T t = null;", "}") .doTest(); } @Test public void mutableInstantiation() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "public class X<T> { final ImmutableList<T> xs = null; }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", "// BUG: Diagnostic contains:", " final X<Object> x = null;", "}") .doTest(); } @Test public void immutableInstantiation_superBound() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "public class X<T> { final ImmutableList<? super T> xs = null; }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.List;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains:", " final X<String> x = null;", "}") .doTest(); } @Test public void mutableInstantiation_superBound() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "public class X<T> { final ImmutableList<? super T> xs = null; }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.List;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: is not annotated", " final X<String> x = null;", "}") .doTest(); } @Test public void mutableInstantiation_inferredImmutableType() { compilationHelper .addSourceLines( "X.java", // "public class X<T> {", " final T xs = null;", "}") .addSourceLines( "Y.java", // "public class Y<T> {", " final X<? extends T> xs = null;", "}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains:", " final Y<Object> x = null;", "}") .doTest(); } @Test public void testImmutableListImplementation() { compilationHelper .addSourceLines( "com/google/common/collect/ImmutableList.java", "package com.google.common.collect;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class ImmutableList<E> {", " public Object[] veryMutable = null;", "}") .doTest(); } @Test public void positiveAnonymous() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "class Test {{", " new Super() {", " // BUG: Diagnostic contains: should be final or annotated", " int x = 0;", " {", " x++;", " }", " };", "}}") .doTest(); } @Test public void positiveAnonymousInterface() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe interface Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "class Test {{", " new Super() {", " // BUG: Diagnostic contains: should be final or annotated", " int x = 0;", " {", " x++;", " }", " };", "}}") .doTest(); } // sub-type tests @Test public void positive() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test extends Super {", " // BUG: Diagnostic contains: should be final or annotated", " public int x = 0;", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test extends Super {", "}") .doTest(); } // Report errors in compilation order, and detect transitive errors even if immediate // supertype is unannotated. @Test public void transitive() { compilationHelper .addSourceLines( "threadsafety/I.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe interface I {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "// BUG: Diagnostic contains: extends @ThreadSafe", "class Test implements J {", " public int x = 0;", "}") .addSourceLines( "threadsafety/J.java", "package threadsafety;", "// BUG: Diagnostic contains: extends @ThreadSafe", "interface J extends I {", "}") .doTest(); } // the type arguments are checked everywhere the super type is used @Test public void negativeAnonymous() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Super {", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "class Test {{", " new Super() {};", "}}") .doTest(); } @Test public void positiveEnumConstant() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe interface Super {", " int f();", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe enum Test implements Super {", " INSTANCE {", " // BUG: Diagnostic contains: should be final or annotated", " public int x = 0;", " public int f() {", " return x++;", " }", " }", "}") .doTest(); } @Test public void negativeEnumConstant() { compilationHelper .addSourceLines( "threadsafety/Super.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe interface Super {", " void f();", "}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe enum Test implements Super {", " INSTANCE {", " public void f() {", " }", " }", "}") .doTest(); } // TODO(cushon): we could probably run this externally, but we'd have to // build protos with maven. private String jarPath(Class<?> clazz) throws Exception { URI uri = clazz.getProtectionDomain().getCodeSource().getLocation().toURI(); return new File(uri).toString(); } // any final null reference constant is immutable, but do we actually care? // // javac makes it annoying to figure this out - since null isn't a compile-time constant, // none of that machinery can be used. Instead, we need to look at the actual AST node // for the member declaration to see that it's initialized to null. @Ignore @Test public void immutableNull() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " final int[] xs = null;", "}") .doTest(); } @Test public void twoFieldsInSource() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: arrays are not thread-safe", " final int[] xs = {1};", " // BUG: Diagnostic contains: arrays are not thread-safe", " final int[] ys = {1};", "}") .doTest(); } @Test public void protosNotOnClasspath() { compilationHelper .addSourceLines( "com/google/errorprone/annotations/ThreadSafe.java", "package com.google.errorprone.annotations;", "import static java.lang.annotation.ElementType.TYPE;", "import static java.lang.annotation.RetentionPolicy.RUNTIME;", "import java.lang.annotation.Retention;", "import java.lang.annotation.Target;", "@Target(TYPE)", "@Retention(RUNTIME)", "public @interface ThreadSafe {", "}") .addSourceLines("Foo.java", "class Foo {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: 'Foo' is not annotated with @" + ThreadSafe.class.getName(), " final Foo f = null;", "}") .setArgs(Arrays.asList("-cp", "NOSUCH")) .doTest(); } @Test public void mutableEnclosing() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "public class Test {", " int x = 0;", " // BUG: Diagnostic contains: 'Inner' has non-thread-safe " + "enclosing instance 'Test'", " @ThreadSafe public class Inner {", " public int count() {", " return x++;", " }", " }", "}") .doTest(); } /** A sample superclass with a mutable field. */ public static class SuperFieldSuppressionTest { @LazyInit public int x = 0; public int count() { return x++; } } @Test public void superFieldSuppression() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import " + SuperFieldSuppressionTest.class.getCanonicalName() + ";", "@ThreadSafe public class Test extends SuperFieldSuppressionTest {}") .doTest(); } @Test public void lazyInit() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import com.google.errorprone.annotations.concurrent.LazyInit;", "@ThreadSafe class Test {", " @LazyInit int a = 42;", "}") .doTest(); } @Test public void lazyInitMutable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "import com.google.errorprone.annotations.concurrent.LazyInit;", "import java.util.List;", "@ThreadSafe class Test {", " // BUG: Diagnostic contains: 'List' is not thread-safe", " @LazyInit List<Integer> a = null;", "}") .doTest(); } @Test public void rawClass() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " final Class clazz = Test.class;", "}") .doTest(); } @Ignore("b/26797524 - add tests for generic arguments") @Test public void mutableTypeParam() { compilationHelper .addSourceLines( "X.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.ThreadSafe;", "public class X {", " final ImmutableList<@ThreadSafe ?> unknownSafeType;", " X (ImmutableList<@ThreadSafe ?> unknownSafeType) {", " this.unknownSafeType = unknownSafeType;", " }", "}") .addSourceLines( "Test.java", "import java.util.ArrayList;", "import com.google.common.collect.ImmutableList;", "class Test {", "// BUG: Diagnostic contains:", " final X badX = new X(ImmutableList.of(new ArrayList<String>()));", "}") .doTest(); } @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); static void addClassToJar(JarOutputStream jos, Class<?> clazz) throws IOException { String entryPath = clazz.getName().replace('.', '/') + ".class"; try (InputStream is = clazz.getClassLoader().getResourceAsStream(entryPath)) { jos.putNextEntry(new JarEntry(entryPath)); ByteStreams.copy(is, jos); } } @Test public void knownThreadSafeFlag() { CompilationTestHelper.newInstance(ThreadSafeChecker.class, getClass()) .setArgs(ImmutableList.of("-XepOpt:ThreadSafe:KnownThreadSafe=threadsafety.SomeImmutable")) .addSourceLines( "threadsafety/SomeImmutable.java", "package threadsafety;", "class SomeImmutable {}") .addSourceLines( "threadsafety/Test.java", "package threadsafety;", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test {", " public final SomeImmutable s = new SomeImmutable();", "}") .doTest(); } @Test public void annotatedClassType() { compilationHelper .addSourceLines( "Test.java", "import static java.lang.annotation.ElementType.TYPE_USE;", "import java.lang.annotation.Target;", "@Target(TYPE_USE) @interface A {}", "class Test {", " Object o = new @A Object();", "}") .doTest(); } // Regression test for b/117937500 // javac does not instantiate type variables when they are not used for target typing, so we // cannot check whether their instantiations are thread-safe. @Test public void threadSafeUpperBound() { compilationHelper .addSourceLines( "MyThreadSafeType.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class MyThreadSafeType {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe class Test<T extends MyThreadSafeType> {", " final T x = null;", "}") .doTest(); } @Test public void threadSafeRecursiveUpperBound() { compilationHelper .addSourceLines( "Recursive.java", "import com.google.errorprone.annotations.ThreadSafe;", "@ThreadSafe", "abstract class Recursive<T extends Recursive<T>> {", " final T x = null;", "}") .doTest(); } @Test public void threadSafeRecursiveUpperBound_notThreadsafe() { compilationHelper .addSourceLines( "Recursive.java", "import com.google.errorprone.annotations.ThreadSafe;", "import java.util.List;", "@ThreadSafe", "abstract class Recursive<T extends Recursive<T>> {", " final T x = null;", " // BUG: Diagnostic contains: @ThreadSafe class has " + "non-thread-safe field, 'List' is not thread-safe", " final List<T> y = null;", "}") .doTest(); } }
34,504
31.27783
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableEnumCheckerTest.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.threadsafety; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ImmutableEnumChecker}Test */ @RunWith(JUnit4.class) public class ImmutableEnumCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ImmutableEnumChecker.class, getClass()); @Test public void nonFinalField() { compilationHelper .addSourceLines( "Test.java", "enum Enum {", " ONE(1), TWO(2);", " // BUG: Diagnostic contains: final int x;'", " int x;", " private Enum(int x) {", " this.x = x;", " }", "}") .doTest(); } @Test public void immutableEnum() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "enum Enum {", " ONE(1), TWO(2);", " final ImmutableSet<Integer> xs;", " private Enum(Integer... xs) {", " this.xs = ImmutableSet.copyOf(xs);", " }", "}") .doTest(); } @Test public void finalMutableField() { compilationHelper .addSourceLines( "Test.java", "import java.util.Arrays;", "import java.util.HashSet;", "import java.util.Set;", "enum Enum {", " ONE(1), TWO(2);", " // BUG: Diagnostic contains: enums should be immutable: 'Enum' has field 'xs' of" + " type 'java.util.Set<java.lang.Integer>', 'Set' is mutable", " final Set<Integer> xs;", " private Enum(Integer... xs) {", " this.xs = new HashSet<>(Arrays.asList(xs));", " }", "}") .doTest(); } @Test public void annotatedEnum() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "// BUG: Diagnostic contains: enums are immutable by default", "@Immutable", "enum Enum {", " ONE, TWO", "}") .doTest(); } @Test public void annotatedEnumThatImplementsImmutableInterface() { compilationHelper .addSourceLines( "MyInterface.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface MyInterface {}") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable", "enum Enum implements MyInterface {", " ONE, TWO", "}") .doTest(); } @Test public void annotatedEnumThatImplementsImmutableInterfaceWithOverrides() { compilationHelper .addSourceLines( "MyInterface.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable interface MyInterface { void bar(); }") .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "@Immutable", "enum Enum implements MyInterface {", " ONE { public void bar() {} },", " TWO { public void bar() {} }", "}") .doTest(); } @Test public void mutableFieldType() { compilationHelper .addSourceLines("Foo.java", "class Foo {", "}") .addSourceLines( "Test.java", "import java.util.Arrays;", "import java.util.HashSet;", "import java.util.Set;", "enum Enum {", " ONE(new Foo()), TWO(new Foo());", " // BUG: Diagnostic contains:" + " the declaration of type 'Foo' is not annotated with" + " @com.google.errorprone.annotations.Immutable", " final Foo f;", " private Enum(Foo f) {", " this.f = f;", " }", "}") .doTest(); } @Test public void suppressOnEnumField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Immutable;", "enum Test {", " ONE;", " @SuppressWarnings(\"Immutable\")", " final int[] xs = {1};", "}") .doTest(); } @Test public void enumInstanceSuperMutable() { compilationHelper .addSourceLines( "Test.java", // "enum Test {", " ONE {", " int incr() {", " return x++;", " }", " };", " abstract int incr();", " // BUG: Diagnostic contains: non-final", " int x;", "}") .doTest(); } @Test public void enumInstanceMutable() { compilationHelper .addSourceLines( "Test.java", // "enum Test {", " ONE {", " // BUG: Diagnostic contains: non-final", " int x;", " int incr() {", " return x++;", " }", " };", " abstract int incr();", "}") .doTest(); } @Test public void jucImmutable() { compilationHelper .addSourceLines( "Lib.java", // "import javax.annotation.concurrent.Immutable;", "@Immutable", "class Lib {", "}") .addSourceLines( "Test.java", // "enum Test {", " ONE;", " // BUG: Diagnostic contains:" + " not annotated with @com.google.errorprone.annotations.Immutable", " final Lib l = new Lib();", "}") .doTest(); } }
6,605
28.491071
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/BuilderReturnThisTest.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.checkreturnvalue; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class BuilderReturnThisTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(BuilderReturnThis.class, getClass()); @Test public void negative() { testHelper .addInputLines( "Test.java", "class Test {", " static class TestBuilder {", " static TestBuilder builder() {", " return new TestBuilder();", " }", " Test build() {", " return new Test();", " }", " TestBuilder setFoo(String foo) {", " return this;", " }", " TestBuilder setBar(String bar) {", " return this;", " }", " TestBuilder setBaz(String baz) {", " return setFoo(baz).setBar(baz);", " }", " TestBuilder setTernary(String baz) {", " return true ? setFoo(baz) : this;", " }", " TestBuilder setCast(String baz) {", " return (TestBuilder) this;", " }", " TestBuilder setParens(String bar) {", " return (this);", " }", " }", "}") .expectUnchanged() .doTest(); } @Test public void positive() { testHelper .addInputLines( "Test.java", "class Test {", " static class TestBuilder {", " TestBuilder setBar(String bar) {", " return new TestBuilder();", " }", " TestBuilder setTernary(String baz) {", " return true ? new TestBuilder() : this;", " }", " }", "}") .addOutputLines( "Test.java", "import com.google.errorprone.annotations.CheckReturnValue;", "class Test {", " static class TestBuilder {", " @CheckReturnValue", " TestBuilder setBar(String bar) {", " return new TestBuilder();", " }", " @CheckReturnValue", " TestBuilder setTernary(String baz) {", " return true ? new TestBuilder() : this;", " }", " }", "}") .doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH); } }
3,315
32.16
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/ApiTest.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.checkreturnvalue; import static com.google.common.base.CharMatcher.whitespace; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableSet; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link Api}. */ @RunWith(JUnit4.class) public final class ApiTest { private static final ImmutableSet<String> UNPARSEABLE_APIS = ImmutableSet.of( "", "#()", "#(java.lang.String)", "#foo()", "#foo(java.lang.String)", "java.lang.String", "java.lang.String##foo()", "java.lang.String#fo#o()", "java.lang.String#()", "java.lang.String#foo)()", "java.lang.String#foo)(", "java.lang.String#<init>(,)", "java.lang.String#get(int[][)", "java.lang.String#get(int[[])", "java.lang.String#get(int[]])", "java.lang.String#get(int])", "java.lang.String#get(int[)", "java.lang.String#get(int[]a)", "java.lang.String#<>()", "java.lang.String#hi<>()", "java.lang.String#<>hi()", "java.lang.String#hi<init>()", "java.lang.String#<init>hi()", "java.lang.String#<iniT>()", "java.lang.String#<init>((java.lang.String)", "java.lang.String#<init>(java.lang.String", "java.lang.String#<init>(java.lang.String,)", "java.lang.String#<init>(,java.lang.String)", "java.lang.String#<init>(java.lang.String))"); @Test public void parseApi_badInputs() { // TODO(b/223670489): would be nice to use expectThrows() here for (String badApi : UNPARSEABLE_APIS) { assertThrows( "Api.parse(\"" + badApi + "\")", IllegalArgumentException.class, () -> Api.parse(badApi)); } } @Test public void parseApi_constructorWithoutParams() { String string = "com.google.async.promisegraph.testing.TestPromiseGraphModule#<init>()"; Api api = Api.parse(string); assertThat(api.className()) .isEqualTo("com.google.async.promisegraph.testing.TestPromiseGraphModule"); assertThat(api.methodName()).isEqualTo("<init>"); assertThat(api.parameterTypes()).isEmpty(); assertThat(api.isConstructor()).isTrue(); assertThat(api.toString()).isEqualTo(string); } @Test public void parseApi_constructorWithParams() { String string = "com.google.api.client.http.GenericUrl#<init>(java.lang.String)"; Api api = Api.parse(string); assertThat(api.className()).isEqualTo("com.google.api.client.http.GenericUrl"); assertThat(api.methodName()).isEqualTo("<init>"); assertThat(api.parameterTypes()).containsExactly("java.lang.String").inOrder(); assertThat(api.isConstructor()).isTrue(); assertThat(api.toString()).isEqualTo(string); } @Test public void parseApi_methodWithoutParams() { String string = "com.google.api.services.drive.model.File#getId()"; Api api = Api.parse(string); assertThat(api.className()).isEqualTo("com.google.api.services.drive.model.File"); assertThat(api.methodName()).isEqualTo("getId"); assertThat(api.parameterTypes()).isEmpty(); assertThat(api.isConstructor()).isFalse(); assertThat(api.toString()).isEqualTo(string); } @Test public void parseApi_methodWithParamsAndSpaces() { String string = " com.google.android.libraries.stitch.binder.Binder" + "#get(android.content.Context , java.lang.Class) "; Api api = Api.parse(string); assertThat(api.className()).isEqualTo("com.google.android.libraries.stitch.binder.Binder"); assertThat(api.methodName()).isEqualTo("get"); assertThat(api.parameterTypes()) .containsExactly("android.content.Context", "java.lang.Class") .inOrder(); assertThat(api.isConstructor()).isFalse(); assertThat(api.toString()).isEqualTo(whitespace().removeFrom(string)); assertThrows( IllegalArgumentException.class, () -> Api.parseFromStringWithoutWhitespace(string)); } @Test public void parseApi_methodWithArray() { String string = "com.google.inject.util.Modules.OverriddenModuleBuilder#with(com.google.inject.Module[],int[][][])"; Api api = Api.parse(string); assertThat(api.className()).isEqualTo("com.google.inject.util.Modules.OverriddenModuleBuilder"); assertThat(api.methodName()).isEqualTo("with"); assertThat(api.parameterTypes()) .containsExactly("com.google.inject.Module[]", "int[][][]") .inOrder(); assertThat(api.isConstructor()).isFalse(); assertThat(api.toString()).isEqualTo(string); } @Test public void parseApi_methodWithVarargs_b231250004() { String string = "com.beust.jcommander.JCommander#<init>(java.lang.Object,java.lang.String...)"; Api api = Api.parse(string); assertThat(api.className()).isEqualTo("com.beust.jcommander.JCommander"); assertThat(api.methodName()).isEqualTo("<init>"); assertThat(api.parameterTypes()) .containsExactly("java.lang.Object", "java.lang.String...") .inOrder(); assertThat(api.isConstructor()).isTrue(); assertThat(api.toString()).isEqualTo(string); } @Test public void parseApi_kotlinClassWithJvmName() { String string = "com.google.inject.-GuiceExtensions#bind(com.google.inject.AbstractModule)"; Api api = Api.parse(string); assertThat(api.className()).isEqualTo("com.google.inject.-GuiceExtensions"); assertThat(api.methodName()).isEqualTo("bind"); assertThat(api.parameterTypes()).containsExactly("com.google.inject.AbstractModule"); assertThat(api.isConstructor()).isFalse(); assertThat(api.toString()).isEqualTo(string); } }
6,429
38.207317
108
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggesterTest.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.checkreturnvalue; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for the {@link CanIgnoreReturnValueSuggester}. */ @RunWith(JUnit4.class) public class CanIgnoreReturnValueSuggesterTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(CanIgnoreReturnValueSuggester.class, getClass()); @Test public void simpleCase() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public Client setName(String name) {", " this.name = name;", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " private String name;", " @CanIgnoreReturnValue", " public Client setName(String name) {", " this.name = name;", " return this;", " }", "}") .doTest(); } @Test public void parenthesizedCastThis() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public Client setName(String name) {", " this.name = name;", " return ((Client) (this));", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " private String name;", " @CanIgnoreReturnValue", " public Client setName(String name) {", " this.name = name;", " return ((Client) (this));", " }", "}") .doTest(); } @Test public void returnsInputParam() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public String method(String name) {", " return name;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " @CanIgnoreReturnValue", " public String method(String name) {", " return name;", " }", "}") .doTest(); } @Test public void returnsInputParam_intParam() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public int method(int value) {", " value = 42;", " return value;", " }", "}") // make sure we don't fire if the value has been re-assigned! .expectUnchanged() .doTest(); } @Test public void returnsInputParam_withParens() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public String method(String name) {", " return (name);", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " @CanIgnoreReturnValue", " public String method(String name) {", " return (name);", " }", "}") .doTest(); } @Test public void returnInputParams_multipleParams() { helper .addInputLines( "ReturnInputParam.java", "package com.google.frobber;", "public final class ReturnInputParam {", " public static StringBuilder append(StringBuilder input, String name) {", " return input;", " }", "}") .addOutputLines( "ReturnInputParam.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class ReturnInputParam {", " @CanIgnoreReturnValue", " public static StringBuilder append(StringBuilder input, String name) {", " return input;", " }", "}") .doTest(); } @Test public void returnInputParams_moreComplex() { helper .addInputLines( "ReturnInputParam.java", "package com.google.frobber;", "public final class ReturnInputParam {", " public static StringBuilder append(StringBuilder input, String name) {", " input.append(\"name = \").append(name);", " return input;", " }", "}") .addOutputLines( "ReturnInputParam.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class ReturnInputParam {", " @CanIgnoreReturnValue", " public static StringBuilder append(StringBuilder input, String name) {", " input.append(\"name = \").append(name);", " return input;", " }", "}") .doTest(); } @Test public void returnsInputParamWithMultipleReturns() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public String method(String a, String b) {", " if (System.currentTimeMillis() > 0) { return a; }", " return b;", " }", "}") .expectUnchanged() .doTest(); } @Test public void returnsInputParamWithMultipleReturns_oneReturnIsConstant() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public String method(String a, String b) {", " if (System.currentTimeMillis() > 0) { return a; }", " return \"hi\";", " }", "}") .expectUnchanged() .doTest(); } @Test public void returnsInputParamWithTernary() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public String method(String a, String b) {", " return (System.currentTimeMillis() > 0) ? a : b;", " }", "}") .expectUnchanged() .doTest(); } @Test public void builder_abstractClass() { helper .addInputLines( "Builder.java", "package com.google.frobber;", "public abstract class Builder {", " public abstract Builder setName(String name);", " public abstract Builder enableDeathStar();", " public abstract Builder clone();", " public abstract Builder copy();", " public abstract Builder getCopy();", " public abstract Builder newBuilder();", "}") .addOutputLines( "Builder.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public abstract class Builder {", " @CanIgnoreReturnValue", " public abstract Builder setName(String name);", " @CanIgnoreReturnValue", " public abstract Builder enableDeathStar();", " public abstract Builder clone();", " public abstract Builder copy();", " public abstract Builder getCopy();", " public abstract Builder newBuilder();", "}") .doTest(); } @Test public void builder_interface() { helper .addInputLines( "Builder.java", "package com.google.frobber;", "public interface Builder {", " Builder setName(String name);", " Builder enableDeathStar();", " Builder copy();", " Builder clone();", " Builder newBuilder();", "}") .addOutputLines( "Builder.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public interface Builder {", " @CanIgnoreReturnValue", " Builder setName(String name);", " @CanIgnoreReturnValue", " Builder enableDeathStar();", " Builder copy();", " Builder clone();", " Builder newBuilder();", "}") .doTest(); } @Test public void autoValueBuilder() { helper .addInputLines( "Animal.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "@AutoValue", "abstract class Animal {", " abstract String name();", " abstract int numberOfLegs();", " static Builder builder() {", " return null;", " }", " @AutoValue.Builder", " abstract static class Builder {", " abstract Builder setName(String value);", " abstract Builder setNumberOfLegs(int value);", " abstract Animal build();", " }", "}") .expectUnchanged() .doTest(); } @Test public void returnSelf_b234875737() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public Client setName(String name) {", " this.name = name;", " return self();", " }", " private Client self() {", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " private String name;", " @CanIgnoreReturnValue", " public Client setName(String name) {", " this.name = name;", " return self();", " }", " private Client self() {", " return this;", " }", "}") .doTest(); } @Test public void returnGetThis() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public Client setName(String name) {", " this.name = name;", " return getThis();", " }", " private Client getThis() {", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " private String name;", " @CanIgnoreReturnValue", " public Client setName(String name) {", " this.name = name;", " return getThis();", " }", " private Client getThis() {", " return this;", " }", "}") .doTest(); } @Test public void simpleCaseAlreadyAnnotatedWithCirv() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " private String name;", " @CanIgnoreReturnValue", " public Client setName(String name) {", " this.name = name;", " return this;", " }", "}") .expectUnchanged() .doTest(); } @Test public void simpleCaseAlreadyAnnotatedWithCrv() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CheckReturnValue;", "public final class Client {", " private String name;", " @CheckReturnValue", // this is "wrong" -- the checker could fix it though! " public Client setName(String name) {", " this.name = name;", " return this;", " }", "}") .expectUnchanged() .doTest(); } @Test public void simpleCaseWithNestedLambda() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import java.util.function.Function;", "public final class Client {", " private String name;", " public Client setName(String name) {", " new Function<String, String>() {", " @Override", " public String apply(String in) {", " return \"kurt\";", " }", " };", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "import java.util.function.Function;", "public final class Client {", " private String name;", " @CanIgnoreReturnValue", " public Client setName(String name) {", " new Function<String, String>() {", " @Override", " public String apply(String in) {", " return \"kurt\";", " }", " };", " return this;", " }", "}") .doTest(); } @Test public void anotherMethodDoesntReturnThis() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public Client setName(String name) {", " this.name = name;", " return this;", " }", " public Client getValue2() {", " return new Client();", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " private String name;", " @CanIgnoreReturnValue", " public Client setName(String name) {", " this.name = name;", " return this;", " }", " public Client getValue2() {", " return new Client();", " }", "}") .doTest(); } @Test public void nestedCase() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public Client setName(String name) {", " this.name = name;", " if (true) {", " return new Client();", " }", " return this;", " }", "}") .expectUnchanged() .doTest(); } @Test public void nestedCaseBothReturningThis() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public Client setName(String name) {", " this.name = name;", " if (true) {", " return this;", " }", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " private String name;", " @CanIgnoreReturnValue", " public Client setName(String name) {", " this.name = name;", " if (true) {", " return this;", " }", " return this;", " }", "}") .doTest(); } @Test public void capitalVoidReturnType() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public Void getValue() {", " return null;", " }", "}") .expectUnchanged() .doTest(); } @Test public void lowerVoidReturnType() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public Void getValue() {", " return null;", " }", "}") .expectUnchanged() .doTest(); } @Test public void constructor() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public Client() {", " }", "}") .expectUnchanged() .doTest(); } @Test public void sometimesThrows() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public Client setName(String name) {", " this.name = name;", " if (true) throw new UnsupportedOperationException();", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " private String name;", " @CanIgnoreReturnValue", " public Client setName(String name) {", " this.name = name;", " if (true) throw new UnsupportedOperationException();", " return this;", " }", "}") .doTest(); } @Test public void alwaysThrows() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public Client setName(String name) {", " throw new UnsupportedOperationException();", " }", "}") .expectUnchanged() .doTest(); } @Test public void simpleCaseWithSimpleNameConflict() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public @interface CanIgnoreReturnValue {}", " public Client setName(String name) {", " this.name = name;", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " private String name;", " public @interface CanIgnoreReturnValue {}", " @com.google.errorprone.annotations.CanIgnoreReturnValue", " public Client setName(String name) {", " this.name = name;", " return this;", " }", "}") .doTest(); } @Test public void onlyReturnsThis_b236423646() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public Client getFoo() {", " return this;", " }", "}") .expectUnchanged() .doTest(); } @Test public void onlyReturnsSelf_b236423646() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public Client getFoo() {", " return self();", " }", " public Client self() {", " return this;", " }", "}") .expectUnchanged() .doTest(); } @Test public void delegateToCirvMethod() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "import java.util.Arrays;", "import java.util.List;", "public final class Client {", " public Client setFoo(String... args) {", " return setFoo(Arrays.asList(args));", " }", " public Client setFoos(String... args) {", " return this.setFoo(Arrays.asList(args));", " }", " @CanIgnoreReturnValue", " public Client setFoo(List<String> args) {", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "import java.util.Arrays;", "import java.util.List;", "public final class Client {", " @CanIgnoreReturnValue", " public Client setFoo(String... args) {", " return setFoo(Arrays.asList(args));", " }", " @CanIgnoreReturnValue", " public Client setFoos(String... args) {", " return this.setFoo(Arrays.asList(args));", " }", " @CanIgnoreReturnValue", " public Client setFoo(List<String> args) {", " return this;", " }", "}") .doTest(); } @Test public void converter_b240039465() { helper .addInputLines( "Parent.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "abstract class Parent<X> {", " @CanIgnoreReturnValue", " X doFrom(String in) { return from(in); }", " abstract X from(String value);", "}") .expectUnchanged() .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client extends Parent<Integer> {", // While doFrom(String) is @CIRV, since it returns Integer, and not Client, we don't add // @CIRV here. " public Integer badMethod(String value) {", " return doFrom(value);", " }", " @Override", " public Integer from(String value) {", " return Integer.parseInt(value);", " }", "}") .expectUnchanged() .doTest(); } @Test public void immutableBuilder_b265049495() { helper .addInputLines( "Animal.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "@AutoValue", "abstract class AnimalBuilder {", " abstract String name();", " public AnimalBuilder withName(String name) {", " return builder().setName(name).build();", " }", " static Builder builder() {", " return null;", " }", " @AutoValue.Builder", " abstract static class Builder {", " abstract Builder setName(String value);", " abstract AnimalBuilder build();", " }", "}") .expectUnchanged() .doTest(); } @Test public void providesMethod_b267362954() { helper .addInputLines( "Example.java", "package com.google.frobber;", "public final class Example {", " static CharSequence provideName(String name) {", " return name;", " }", "}") .expectUnchanged() .doTest(); } }
26,340
30.508373
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/UsingJsr305CheckReturnValueTest.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.checkreturnvalue; 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 the {@link UsingJsr305CheckReturnValue}. */ @RunWith(JUnit4.class) public class UsingJsr305CheckReturnValueTest { @Test public void jsr305Imported() { BugCheckerRefactoringTestHelper.newInstance(UsingJsr305CheckReturnValue.class, getClass()) .addInputLines( "Client.java", "package com.google.frobber;", "import javax.annotation.CheckReturnValue;", "public final class Client {", " @CheckReturnValue", " public int getValue() {", " return 42;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CheckReturnValue;", "public final class Client {", " @CheckReturnValue", " public int getValue() {", " return 42;", " }", "}") .doTest(); } @Test public void jsr305FullyQualified() { CompilationTestHelper.newInstance(UsingJsr305CheckReturnValue.class, getClass()) .addSourceLines( "Client.java", "package com.google.frobber;", "public final class Client {", // NOTE: fully-qualified annotations are not currently re-written " @javax.annotation.CheckReturnValue", " public int getValue() {", " return 42;", " }", "}") .doTest(); } @Test public void jsr305ImportStar() { CompilationTestHelper.newInstance(UsingJsr305CheckReturnValue.class, getClass()) .addSourceLines( "Client.java", "package com.google.frobber;", "import javax.annotation.*;", "public final class Client {", // NOTE: wildcard-imported annotations are not currently re-written " @CheckReturnValue", " public int getValue() {", " return 42;", " }", "}") .doTest(); } }
2,939
32.409091
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/UnnecessarilyUsedValueTest.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.checkreturnvalue; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class UnnecessarilyUsedValueTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(UnnecessarilyUsedValue.class, getClass()); @Test public void methods() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public void varNotUnused() {", " var notUnused = ignorable();", " }", " public void varUnused() {", " var unused = ignorable();", " }", " public void varUnusedFoo() {", " var unusedFoo = ignorable();", " }", " public void varUnused0() {", " var unused0 = ignorable();", " }", " public void varUnused1() {", " var unused1 = ignorable();", " }", " public void varUnused10() {", " var unused10 = ignorable();", " }", " public void objectUnused() {", " Object unused = ignorable();", " }", " public void objectUnusedFoo() {", " Object unusedFoo = ignorable();", " }", " public void reuseOfUnusedVariable(String unused) {", " unused = ignorable();", " }", " @com.google.errorprone.annotations.CanIgnoreReturnValue", " public String ignorable() {", " return \"hi\";", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public void varNotUnused() {", " var notUnused = ignorable();", " }", " public void varUnused() {", " ignorable();", " }", " public void varUnusedFoo() {", " var unusedFoo = ignorable();", " }", " public void varUnused0() {", " ignorable();", " }", " public void varUnused1() {", " ignorable();", " }", " public void varUnused10() {", " ignorable();", " }", " public void objectUnused() {", " ignorable();", " }", " public void objectUnusedFoo() {", " Object unusedFoo = ignorable();", " }", " public void reuseOfUnusedVariable(String unused) {", " ignorable();", " }", " @com.google.errorprone.annotations.CanIgnoreReturnValue", " public String ignorable() {", " return \"hi\";", " }", "}") .doTest(); } @Test public void constructors() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public void varNotUnused() {", " var notUnused = new Client();", " }", " public void varUnused() {", " var unused = new Client();", " }", " public void varUnusedFoo() {", " var unusedFoo = new Client();", " }", " public void objectUnused() {", " Object unused = new Client();", " }", " public void objectUnusedFoo() {", " Object unusedFoo = new Client();", " }", " public void reuseOfUnusedVariable(Client unused) {", " unused = new Client();", " }", " @com.google.errorprone.annotations.CanIgnoreReturnValue", " public Client() {", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public void varNotUnused() {", " var notUnused = new Client();", " }", " public void varUnused() {", " new Client();", " }", " public void varUnusedFoo() {", " var unusedFoo = new Client();", " }", " public void objectUnused() {", " new Client();", " }", " public void objectUnusedFoo() {", " Object unusedFoo = new Client();", " }", " public void reuseOfUnusedVariable(Client unused) {", " new Client();", " }", " @com.google.errorprone.annotations.CanIgnoreReturnValue", " public Client() {", " }", "}") .doTest(); } @Test public void tryWithResources() { helper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public void varNotUnused() throws Exception {", " try (java.io.Closeable unused = getCloseable()) {", " }", " }", " @com.google.errorprone.annotations.CanIgnoreReturnValue", " private java.io.Closeable getCloseable() {", " return null;", " }", "}") .expectUnchanged() .doTest(); } }
6,342
33.102151
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/NoCanIgnoreReturnValueOnClassesTest.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.checkreturnvalue; import static com.google.errorprone.bugpatterns.checkreturnvalue.NoCanIgnoreReturnValueOnClasses.CTOR_COMMENT; import static com.google.errorprone.bugpatterns.checkreturnvalue.NoCanIgnoreReturnValueOnClasses.METHOD_COMMENT; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for the {@link NoCanIgnoreReturnValueOnClasses}. */ @RunWith(JUnit4.class) public final class NoCanIgnoreReturnValueOnClassesTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance( NoCanIgnoreReturnValueOnClasses.class, getClass()); @Test public void simpleCase_returnsThis() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@CanIgnoreReturnValue", "public final class Client {", " public Client getValue() {", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " @CanIgnoreReturnValue", " public Client getValue() {", " return this;", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void simpleCase_returnsParenthesizedCastThis() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@CanIgnoreReturnValue", "public final class Client {", " public Client getValue() {", " return ((Client) (this));", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " @CanIgnoreReturnValue", " public Client getValue() {", " return ((Client) (this));", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void simpleCase_returnsSelf() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@CanIgnoreReturnValue", "public final class Client {", " public Client getValue() {", " return self();", " }", " private Client self() {", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " @CanIgnoreReturnValue", " public Client getValue() {", " return self();", " }", " @CanIgnoreReturnValue", " private Client self() {", " return this;", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void simpleCase_returnsGetThis() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@CanIgnoreReturnValue", "public final class Client {", " public Client getValue() {", " return getThis();", " }", " private Client getThis() {", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " @CanIgnoreReturnValue", " public Client getValue() {", " return getThis();", " }", " @CanIgnoreReturnValue", " private Client getThis() {", " return this;", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void simpleCase_returnsNewInstance() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@CanIgnoreReturnValue", "public final class Client {", " public Client getValue() {", " return new Client();", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " @CanIgnoreReturnValue" + METHOD_COMMENT, " public Client getValue() {", " return new Client();", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void simpleCase_explicitConstructor() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@CanIgnoreReturnValue", "public final class Client {", " Client() {}", " public Client getValue() {", " return this;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class Client {", " @CanIgnoreReturnValue" + CTOR_COMMENT, " Client() {}", " @CanIgnoreReturnValue", " public Client getValue() {", " return this;", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void nestedClasses_cirvAndCrv() { helper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "import com.google.errorprone.annotations.CheckReturnValue;", "@CanIgnoreReturnValue", "public final class Client {", " public Client getValue() {", " return this;", " }", " @CheckReturnValue", " public static final class Nested {", " public int getValue() {", " return 42;", " }", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "import com.google.errorprone.annotations.CheckReturnValue;", "public final class Client {", " @CanIgnoreReturnValue", " public Client getValue() {", " return this;", " }", " @CheckReturnValue", " public static final class Nested {", " public int getValue() {", " return 42;", " }", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void nestedClasses_bothCirv() { helper .addInputLines( "User.java", "package com.google.gaia;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@CanIgnoreReturnValue", "public final class User {", " public User persist() {", " return this;", " }", " public static final class Builder {", " public Builder setFirstName(String firstName) {", " return this;", " }", " }", "}") .addOutputLines( "User.java", "package com.google.gaia;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public final class User {", " @CanIgnoreReturnValue", " public User persist() {", " return this;", " }", " public static final class Builder {", " @CanIgnoreReturnValue", " public Builder setFirstName(String firstName) {", " return this;", " }", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void autoValue() { helper .addInputLines( "Animal.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@AutoValue", "@CanIgnoreReturnValue", "abstract class Animal {", " abstract String name();", " @AutoValue.Builder", " abstract static class Builder {", " abstract Builder setName(String value);", " abstract Animal build();", " }", "}") .addOutputLines( "Animal.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@AutoValue", "abstract class Animal {", " abstract String name();", " @AutoValue.Builder", " abstract static class Builder {", " abstract Builder setName(String value);", " abstract Animal build();", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void autoValueBuilder() { helper .addInputLines( "Animal.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@AutoValue", "abstract class Animal {", " abstract String name();", " @CanIgnoreReturnValue", " @AutoValue.Builder", " abstract static class Builder {", " abstract Builder setName(String value);", " abstract Animal build();", " }", "}") .addOutputLines( "Animal.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@AutoValue", "abstract class Animal {", " abstract String name();", " @AutoValue.Builder", " abstract static class Builder {", " abstract Builder setName(String value);", " abstract Animal build();", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void nestedAutoValue() { helper .addInputLines( "Outer.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "@CanIgnoreReturnValue", "public class Outer {", " public String name() {", " return null;", " }", " @AutoValue", " abstract static class Inner {", " abstract String id();", " }", "}") .addOutputLines( "Outer.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.CanIgnoreReturnValue;", "public class Outer {", " @CanIgnoreReturnValue" + METHOD_COMMENT, " public String name() {", " return null;", " }", " @AutoValue", " abstract static class Inner {", " abstract String id();", " }", "}") .doTest(TestMode.TEXT_MATCH); } }
13,433
33.270408
112
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CheckReturnValueWellKnownLibrariesTest.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.checkreturnvalue; import com.google.auto.value.processor.AutoBuilderProcessor; import com.google.auto.value.processor.AutoValueProcessor; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.bugpatterns.CheckReturnValue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class CheckReturnValueWellKnownLibrariesTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(CheckReturnValue.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(CheckReturnValue.class, getClass()); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); // Don't match methods invoked through {@link org.mockito.Mockito}. @Test public void ignoreCRVOnMockito() { compilationHelper .addSourceLines( "Test.java", "package lib;", "public class Test {", " @com.google.errorprone.annotations.CheckReturnValue", " public int f() {", " return 0;", " }", "}") .addSourceLines( "TestCase.java", "import static org.mockito.Mockito.verify;", "import static org.mockito.Mockito.doReturn;", "import org.mockito.Mockito;", "class TestCase {", " void m() {", " lib.Test t = new lib.Test();", " Mockito.verify(t).f();", " verify(t).f();", " doReturn(1).when(t).f();", " Mockito.doReturn(1).when(t).f();", " }", "}") .doTest(); } @Test public void mockitoVerifyMistake() { refactoringHelper .addInputLines( "Test.java", // "interface Test {", " int f();", "}") .expectUnchanged() .addInputLines( "TestCase.java", "import static org.mockito.Mockito.verify;", "class TestCase {", " void m(Test t) {", " verify(t.f());", " }", "}") .addOutputLines( "TestCase.java", "import static org.mockito.Mockito.verify;", "class TestCase {", " void m(Test t) {", " verify(t).f();", " }", "}") .doTest(); } @Test public void ignoreInTests() { compilationHelper .addSourceLines( "Foo.java", "@com.google.errorprone.annotations.CheckReturnValue", "public class Foo {", " public int f() {", " return 42;", " }", "}") .addSourceLines( "Test.java", "class Test {", " void f(Foo foo) {", " try {", " foo.f();", " org.junit.Assert.fail();", " } catch (Exception expected) {}", " try {", " foo.f();", " junit.framework.Assert.fail();", " } catch (Exception expected) {}", " try {", " foo.f();", " junit.framework.TestCase.fail();", " } catch (Exception expected) {}", " }", "}") .doTest(); } @Test public void ignoreInTestsWithRule() { compilationHelper .addSourceLines( "Foo.java", "@com.google.errorprone.annotations.CheckReturnValue", "public class Foo {", " public int f() {", " return 42;", " }", "}") .addSourceLines( "Test.java", "class Test {", " private org.junit.rules.ExpectedException exception;", " void f(Foo foo) {", " exception.expect(IllegalArgumentException.class);", " foo.f();", " }", "}") .doTest(); } @Test public void ignoreInTestsWithFailureMessage() { compilationHelper .addSourceLines( "Foo.java", "@com.google.errorprone.annotations.CheckReturnValue", "public class Foo {", " public int f() {", " return 42;", " }", "}") .addSourceLines( "Test.java", "class Test {", " void f(Foo foo) {", " try {", " foo.f();", " org.junit.Assert.fail(\"message\");", " } catch (Exception expected) {}", " try {", " foo.f();", " junit.framework.Assert.fail(\"message\");", " } catch (Exception expected) {}", " try {", " foo.f();", " junit.framework.TestCase.fail(\"message\");", " } catch (Exception expected) {}", " }", "}") .doTest(); } @Test public void ignoreInThrowingRunnables() { compilationHelper .addSourceLines( "Foo.java", "@com.google.errorprone.annotations.CheckReturnValue", "public class Foo {", " public int f() {", " return 42;", " }", "}") .addSourceLines( "Test.java", "class Test {", " void f(Foo foo) {", " org.junit.Assert.assertThrows(IllegalStateException.class, ", " new org.junit.function.ThrowingRunnable() {", " @Override", " public void run() throws Throwable {", " foo.f();", " }", " });", " org.junit.Assert.assertThrows(IllegalStateException.class, () -> foo.f());", " org.junit.Assert.assertThrows(IllegalStateException.class, foo::f);", " org.junit.Assert.assertThrows(IllegalStateException.class, () -> {", " int bah = foo.f();", " foo.f(); ", " });", " org.junit.Assert.assertThrows(IllegalStateException.class, () -> { ", " // BUG: Diagnostic contains: CheckReturnValue", " foo.f(); ", " foo.f(); ", " });", " bar(() -> foo.f());", " org.assertj.core.api.Assertions.assertThatExceptionOfType(IllegalStateException.class)", " .isThrownBy(() -> foo.f());", " }", " void bar(org.junit.function.ThrowingRunnable r) {}", "}") .doTest(); } @Test public void ignoreTruthFailure() { compilationHelper .addSourceLines( "Foo.java", "@com.google.errorprone.annotations.CheckReturnValue", "public class Foo {", " public int f() {", " return 42;", " }", "}") .addSourceLines( "Test.java", "import static com.google.common.truth.Truth.assert_;", "class Test {", " void f(Foo foo) {", " try {", " foo.f();", " assert_().fail();", " } catch (Exception expected) {}", " }", "}") .doTest(); } @Test public void truthMissingIsTrue() { refactoringHelper .addInputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "class Test {", " void f(boolean b) {", " assertThat(b);", " }", "}") .addOutputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "class Test {", " void f(boolean b) {", " assertThat(b).isTrue();", " }", "}") .setFixChooser(Iterables::getOnlyElement) .doTest(); } @Test public void booleanToTruthAssertion() { refactoringHelper .setArgs("-XepCompilingTestOnlyCode") .addInputLines( "Lib.java", "@com.google.errorprone.annotations.CheckReturnValue", "interface Lib {", " boolean b();", "}") .expectUnchanged() .addInputLines( "Test.java", // "class Test {", " void go(Lib lib) {", " lib.b();", " }", "}") .addOutputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "class Test {", " void go(Lib lib) {", " assertThat(lib.b()).isTrue();", " }", "}") .doTest(); } @Test public void booleanToVerifyCall() { refactoringHelper .addInputLines( "Lib.java", "@com.google.errorprone.annotations.CheckReturnValue", "interface Lib {", " boolean b();", "}") .expectUnchanged() .addInputLines( "Test.java", // "class Test {", " void go(Lib lib) {", " lib.b();", " }", "}") .addOutputLines( "Test.java", "import static com.google.common.base.Verify.verify;", "class Test {", " void go(Lib lib) {", " verify(lib.b());", " }", "}") .doTest(); } @Test public void onlyIgnoreWithEnclosingTryCatch() { compilationHelper .addSourceLines( "Foo.java", "@com.google.errorprone.annotations.CheckReturnValue", "public class Foo {", " public int f() {", " return 42;", " }", "}") .addSourceLines( "Test.java", "import static org.junit.Assert.fail;", "class Test {", " void f(Foo foo) {", " // BUG: Diagnostic contains: CheckReturnValue", " foo.f();", " org.junit.Assert.fail();", " // BUG: Diagnostic contains: CheckReturnValue", " foo.f();", " junit.framework.Assert.fail();", " // BUG: Diagnostic contains: CheckReturnValue", " foo.f();", " junit.framework.TestCase.fail();", " }", "}") .doTest(); } @Test public void ignoreInOrderVerification() { compilationHelper .addSourceLines( "Lib.java", "public class Lib {", " @com.google.errorprone.annotations.CheckReturnValue", " public int f() {", " return 0;", " }", "}") .addSourceLines( "Test.java", "import static org.mockito.Mockito.inOrder;", "class Test {", " void m() {", " inOrder().verify(new Lib()).f();", " }", "}") .doTest(); } @Test public void usingElementInTestExpected() { compilationHelperLookingAtAllConstructors() .addSourceLines( "Foo.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.junit.Test;", "@RunWith(JUnit4.class)", "class Foo {", " @Test(expected = IllegalArgumentException.class) ", " public void foo() {", " new Foo();", // OK when it's the only statement " }", " @Test(expected = IllegalArgumentException.class) ", " public void fooWith2Statements() {", " Foo f = new Foo();", " // BUG: Diagnostic contains: CheckReturnValue", " new Foo();", // Not OK if there is more than one statement in the block. " }", " @Test(expected = Test.None.class) ", // This is a weird way to spell the default " public void fooWithNone() {", " // BUG: Diagnostic contains: CheckReturnValue", " new Foo();", " }", "}") .doTest(); } @Test public void autoValueBuilderSetterMethods() { compilationHelper .addSourceLines( "Animal.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.CheckReturnValue;", "@AutoValue", "@CheckReturnValue", "abstract class Animal {", " abstract String name();", " abstract int numberOfLegs();", " static Builder builder() {", " return new AutoValue_Animal.Builder();", " }", " @AutoValue.Builder", " abstract static class Builder {", " abstract Builder setName(String value);", " abstract Builder setNumberOfLegs(int value);", " abstract Animal build();", " }", "}") .addSourceLines( "AnimalCaller.java", "package com.google.frobber;", "public final class AnimalCaller {", " static void testAnimal() {", " Animal.Builder builder = Animal.builder();", " builder.setNumberOfLegs(4);", // AutoValue.Builder setters are implicitly @CIRV " // BUG: Diagnostic contains: CheckReturnValue", " builder.build();", " }", "}") .setArgs(ImmutableList.of("-processor", AutoValueProcessor.class.getName())) .doTest(); } @Test public void autoValueBuilderSetterMethodsOnInterface() { compilationHelper .addSourceLines( "Animal.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.CheckReturnValue;", "@AutoValue", "@CheckReturnValue", "abstract class Animal {", " abstract String name();", " abstract int numberOfLegs();", " static Builder builder() {", " return new AutoValue_Animal.Builder();", " }", " @AutoValue.Builder", " interface Builder {", " Builder setName(String value);", " Builder setNumberOfLegs(int numberOfLegs);", " default Builder defaultMethod(int value) {", " return new AutoValue_Animal.Builder();", " }", " Animal build();", " }", "}") .addSourceLines( "AnimalCaller.java", "package com.google.frobber;", "public final class AnimalCaller {", " static void testAnimal() {", " Animal.Builder builder = Animal.builder();", " builder.setName(\"Stumpy\");", // AutoValue.Builder setters are implicitly @CIRV " // BUG: Diagnostic contains: CheckReturnValue", " builder.defaultMethod(4);", " // BUG: Diagnostic contains: CheckReturnValue", " builder.build();", " }", "}") .setArgs(ImmutableList.of("-processor", AutoValueProcessor.class.getName())) .doTest(); } @Test public void autoValueGetterMethods() { compilationHelper .addSourceLines( "Animal.java", "package com.google.frobber;", "import com.google.auto.value.AutoValue;", "@AutoValue", "abstract class Animal {", " abstract String name();", " abstract int numberOfLegs();", "}") .addSourceLines( "AnimalCaller.java", "package com.google.frobber;", "public final class AnimalCaller {", " static void testAnimal() {", " Animal a = new AutoValue_Animal(\"dog\", 4);", " // BUG: Diagnostic contains: CheckReturnValue", " a.numberOfLegs();", "", // And test usages where the static type is the generated class, too: " AutoValue_Animal b = new AutoValue_Animal(\"dog\", 4);", " // BUG: Diagnostic contains: CheckReturnValue", " b.numberOfLegs();", " }", "}") .setArgs(ImmutableList.of("-processor", AutoValueProcessor.class.getName())) .doTest(); } @Test public void autoBuilderSetterMethods() { compilationHelper .addSourceLines( "Person.java", "package com.google.frobber;", "public final class Person {", " public Person(String name, int id) {}", "}") .addSourceLines( "PersonBuilder.java", "package com.google.frobber;", "import com.google.auto.value.AutoBuilder;", "import com.google.errorprone.annotations.CheckReturnValue;", "@CheckReturnValue", "@AutoBuilder(ofClass = Person.class)", "interface PersonBuilder {", " static PersonBuilder personBuilder() {", " return new AutoBuilder_PersonBuilder();", " }", " PersonBuilder setName(String name);", " PersonBuilder setId(int id);", " Person build();", "}") .addSourceLines( "PersonCaller.java", "package com.google.frobber;", "public final class PersonCaller {", " static void testPersonBuilder() {", " // BUG: Diagnostic contains: CheckReturnValue", " PersonBuilder.personBuilder();", " PersonBuilder builder = PersonBuilder.personBuilder();", " builder.setName(\"kurt\");", // AutoBuilder setters are implicitly @CIRV " builder.setId(42);", // AutoBuilder setters are implicitly @CIRV " // BUG: Diagnostic contains: CheckReturnValue", " builder.build();", "", // And test usages where the static type is the generated class, too: " // BUG: Diagnostic contains: CheckReturnValue", " new AutoBuilder_PersonBuilder().build();", " }", "}") .setArgs(ImmutableList.of("-processor", AutoBuilderProcessor.class.getName())) .doTest(); } @Test public void autoBuilderSetterMethods_withInterface() { compilationHelper .addSourceLines( "LogUtil.java", "package com.google.frobber;", "import java.util.logging.Level;", "public class LogUtil {", " public static void log(Level severity, String message) {}", "}") .addSourceLines( "Caller.java", "package com.google.frobber;", "import com.google.auto.value.AutoBuilder;", "import java.util.logging.Level;", "import com.google.errorprone.annotations.CheckReturnValue;", "@CheckReturnValue", "@AutoBuilder(callMethod = \"log\", ofClass = LogUtil.class)", "public interface Caller {", " static Caller logCaller() {", " return new AutoBuilder_Caller();", " }", " Caller setSeverity(Level level);", " Caller setMessage(String message);", " void call(); // calls: LogUtil.log(severity, message)", "}") .addSourceLines( "LogCaller.java", "package com.google.frobber;", "import java.util.logging.Level;", "public final class LogCaller {", " static void testLogCaller() {", " // BUG: Diagnostic contains: CheckReturnValue", " Caller.logCaller();", " Caller caller = Caller.logCaller();", " caller.setMessage(\"hi\");", // AutoBuilder setters are implicitly @CIRV " caller.setSeverity(Level.FINE);", // AutoBuilder setters are implicitly @CIRV " caller.call();", " }", "}") .setArgs(ImmutableList.of("-processor", AutoBuilderProcessor.class.getName())) .doTest(); } private CompilationTestHelper compilationHelperLookingAtAllConstructors() { return compilationHelper.setArgs( "-XepOpt:" + CheckReturnValue.CHECK_ALL_CONSTRUCTORS + "=true"); } private CompilationTestHelper compilationHelperLookingAtAllMethods() { return compilationHelper.setArgs("-XepOpt:" + CheckReturnValue.CHECK_ALL_METHODS + "=true"); } }
21,914
33.896497
104
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/JavaxInjectOnFinalFieldTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class JavaxInjectOnFinalFieldTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(JavaxInjectOnFinalField.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("JavaxInjectOnFinalFieldPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("JavaxInjectOnFinalFieldNegativeCases.java").doTest(); } }
1,342
30.97619
90
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/InvalidTargetingOnScopingAnnotationTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class InvalidTargetingOnScopingAnnotationTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InvalidTargetingOnScopingAnnotation.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceFile("InvalidTargetingOnScopingAnnotationPositiveCases.java") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceFile("InvalidTargetingOnScopingAnnotationNegativeCases.java") .doTest(); } }
1,427
29.382979
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/AssistedInjectAndInjectOnSameConstructorTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class AssistedInjectAndInjectOnSameConstructorTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(AssistedInjectAndInjectOnSameConstructor.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceFile("AssistedInjectAndInjectOnSameConstructorPositiveCases.java") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceFile("AssistedInjectAndInjectOnSameConstructorNegativeCases.java") .doTest(); } }
1,447
29.808511
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/InjectedConstructorAnnotationsTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** A test for InjectedConstructorAnnotations */ @RunWith(JUnit4.class) public class InjectedConstructorAnnotationsTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InjectedConstructorAnnotations.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("InjectedConstructorAnnotationsPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("InjectedConstructorAnnotationsNegativeCases.java").doTest(); } }
1,360
32.195122
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/OverlappingQualifierAndScopeAnnotationTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class OverlappingQualifierAndScopeAnnotationTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(OverlappingQualifierAndScopeAnnotation.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceFile("OverlappingQualifierAndScopeAnnotationPositiveCases.java") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceFile("OverlappingQualifierAndScopeAnnotationNegativeCases.java") .doTest(); } }
1,439
29.638298
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/AssistedInjectAndInjectOnConstructorsTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class AssistedInjectAndInjectOnConstructorsTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(AssistedInjectAndInjectOnConstructors.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceFile("AssistedInjectAndInjectOnConstructorsPositiveCases.java") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceFile("AssistedInjectAndInjectOnConstructorsNegativeCases.java") .doTest(); } }
1,435
29.553191
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/CloseableProvidesTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class CloseableProvidesTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(CloseableProvides.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("CloseableProvidesPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("CloseableProvidesNegativeCases.java").doTest(); } }
1,315
29.604651
84
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/AutoFactoryAtInjectTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author ronshapiro@google.com (Ron Shapiro) */ @RunWith(JUnit4.class) public class AutoFactoryAtInjectTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(AutoFactoryAtInject.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("AutoFactoryAtInjectPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("AutoFactoryAtInjectNegativeCases.java").doTest(); } }
1,322
29.767442
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/JavaxInjectOnAbstractMethodTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class JavaxInjectOnAbstractMethodTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(JavaxInjectOnAbstractMethod.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("JavaxInjectOnAbstractMethodPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("JavaxInjectOnAbstractMethodNegativeCases.java").doTest(); } }
1,359
30.627907
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/MoreThanOneInjectableConstructorTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class MoreThanOneInjectableConstructorTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MoreThanOneInjectableConstructor.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("MoreThanOneInjectableConstructorPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("MoreThanOneInjectableConstructorNegativeCases.java").doTest(); } }
1,379
31.093023
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructorTest.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.inject; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class InjectOnMemberAndConstructorTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(InjectOnMemberAndConstructor.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InjectOnMemberAndConstructor.class, getClass()); @Test public void positiveCase() { testHelper .addInputLines( "in/InjectOnMemberAndConstructorPositiveCases.java", "import javax.inject.Inject;", "public class InjectOnMemberAndConstructorPositiveCases {", " @Inject private final String stringFieldWithInject;", " @Inject private final Long longFieldWithInject;", " private final String stringFieldWithoutInject;", " @Inject", " public InjectOnMemberAndConstructorPositiveCases(String stringFieldWithInject,", " String stringFieldWithoutInject, Long longFieldWithInject) {", " this.stringFieldWithInject = stringFieldWithInject;", " this.stringFieldWithoutInject = stringFieldWithoutInject;", " this.longFieldWithInject = longFieldWithInject;", " }", "}") .addOutputLines( "out/InjectOnMemberAndConstructorPositiveCases.java", "import javax.inject.Inject;", "public class InjectOnMemberAndConstructorPositiveCases {", " private final String stringFieldWithInject;", " private final Long longFieldWithInject;", " private final String stringFieldWithoutInject;", " @Inject", " public InjectOnMemberAndConstructorPositiveCases(String stringFieldWithInject,", " String stringFieldWithoutInject, Long longFieldWithInject) {", " this.stringFieldWithInject = stringFieldWithInject;", " this.stringFieldWithoutInject = stringFieldWithoutInject;", " this.longFieldWithInject = longFieldWithInject;", " }", "}") .doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("InjectOnMemberAndConstructorNegativeCases.java").doTest(); } }
3,237
41.051948
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/InjectOnConstructorOfAbstractClassTest.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.inject; 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 InjectOnConstructorOfAbstractClassTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InjectOnConstructorOfAbstractClass.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceLines( "Foo.java", "import javax.inject.Inject;", "abstract class Foo {", " // BUG: Diagnostic contains: Foo() {}", " @Inject Foo() {}", "}") .doTest(); } @Test public void guiceConstructor() { compilationHelper .addSourceLines( "Foo.java", "import com.google.inject.Inject;", "abstract class Foo {", " // BUG: Diagnostic contains: Foo() {}", " @Inject Foo() {}", "}") .doTest(); } @Test public void abstractClassInConcreteClass() { compilationHelper .addSourceLines( "Foo.java", "import javax.inject.Inject;", "class Bar {", " abstract static class Foo {", " // BUG: Diagnostic contains: Foo() {}", " @Inject Foo() {}", " }", "}") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceLines( "Foo.java", // "import javax.inject.Inject;", "class Foo {", " @Inject Foo() {}", "}") .doTest(); } @Test public void concreteClassInAbstractClass() { compilationHelper .addSourceLines( "Foo.java", "import javax.inject.Inject;", "abstract class Bar {", " static class Foo {", " @Inject Foo() {}", " }", "}") .doTest(); } }
2,728
26.29
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/MoreThanOneScopeAnnotationOnClassTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class MoreThanOneScopeAnnotationOnClassTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MoreThanOneScopeAnnotationOnClass.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("MoreThanOneScopeAnnotationOnClassPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("MoreThanOneScopeAnnotationOnClassNegativeCases.java").doTest(); } }
1,382
31.928571
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/QualifierOrScopeOnInjectMethodTest.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.inject; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author glorioso@google.com (Nick Glorioso) */ @RunWith(JUnit4.class) public class QualifierOrScopeOnInjectMethodTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(QualifierOrScopeOnInjectMethod.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(QualifierOrScopeOnInjectMethod.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceLines( "Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "class Foo {", " // BUG: Diagnostic contains: @Inject void someMethod() {}", " @Inject @Named(\"bar\") void someMethod() {}", "}") .doTest(); } @Test public void positiveCase_injectConstructor() { refactoringHelper .addInputLines( "in/Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " @Inject @Singleton @Named(\"bar\") Foo() {}", "}") .addOutputLines( "out/Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "@Singleton class Foo {", " @Inject Foo() {}", "}") .doTest(); } @Test public void negativeNotInject() { compilationHelper .addSourceLines( "Foo.java", "import dagger.Provides;", "import dagger.Module;", "import javax.inject.Named;", "@Module", "class Foo {", " @Provides @Named(\"bar\") int something() { return 42; }", "}") .doTest(); } }
2,775
30.908046
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/MoreThanOneQualifierTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class MoreThanOneQualifierTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MoreThanOneQualifier.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("MoreThanOneQualifierPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("MoreThanOneQualifierNegativeCases.java").doTest(); } }
1,331
29.976744
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/ScopeAnnotationOnInterfaceOrAbstractClassTest.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.inject; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class ScopeAnnotationOnInterfaceOrAbstractClassTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance( ScopeAnnotationOnInterfaceOrAbstractClass.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceFile("ScopeAnnotationOnInterfaceOrAbstractClassPositiveCases.java") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceFile("ScopeAnnotationOnInterfaceOrAbstractClassNegativeCases.java") .doTest(); } }
1,462
29.479167
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/MisplacedScopeAnnotationsTest.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.inject; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test for {@link MisplacedScopeAnnotations}. */ @RunWith(JUnit4.class) public class MisplacedScopeAnnotationsTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MisplacedScopeAnnotations.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(MisplacedScopeAnnotations.class, getClass()); @Test public void positiveCase_methodInjection() { compilationHelper .addSourceLines( "Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " // BUG: Diagnostic contains: @Inject void someMethod( String foo) {}", " @Inject void someMethod(@Singleton String foo) {}", "}") .doTest(); } @Test public void positiveCase_providerMethod() { refactoringHelper .addInputLines( "in/Foo.java", "import com.google.inject.Provides;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " @Provides String provideString(@Singleton @Named(\"foo\") String foo) {", " return foo;", " }", "}") .addOutputLines( "out/Foo.java", "import com.google.inject.Provides;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " @Provides String provideString( @Named(\"foo\") String foo) {", " return foo;", " }", "}") .doTest(); } @Test public void positiveCase_injectConstructor() { refactoringHelper .addInputLines( "in/Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " @Inject Foo(@Singleton @Named(\"bar\") String bar) {}", "}") .addOutputLines( "out/Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " @Inject Foo( @Named(\"bar\") String bar) {}", "}") .doTest(); } @Test public void positiveCase_injectConstructorMultipleAnnotations() { refactoringHelper .addInputLines( "in/Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " @Inject Foo(@Singleton String bar, Integer i, @Singleton Long c) {}", "}") .addOutputLines( "out/Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " @Inject Foo( String bar, Integer i, Long c) {}", "}") .doTest(); } @Test public void positiveCase_fieldInjection() { refactoringHelper .addInputLines( "in/Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " @Inject @Singleton String foo;", "}") .addOutputLines( "out/Foo.java", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "class Foo {", " @Inject String foo;", "}") .doTest(); } @Test public void negativeCase_noScopeAnnotationOnInjectedParameters() { compilationHelper .addSourceLines( "Foo.java", "import dagger.Provides;", "import dagger.Module;", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Singleton;", "@Module", "class Foo {", " @Provides @Singleton @Named(\"bar\")", " int something(@Named(\"bar\") Integer bar) {", " return 42;", " }", "}") .doTest(); } @Test public void negativeCase_scopeAnnotationIsAlsoQualifier() { compilationHelper .addSourceLines( "Foo.java", "import dagger.Provides;", "import dagger.Module;", "import javax.inject.Inject;", "import javax.inject.Named;", "import javax.inject.Qualifier;", "import javax.inject.Scope;", "import java.lang.annotation.Retention;", "import java.lang.annotation.RetentionPolicy;", "@Module", "class Foo {", " @Qualifier", " @Scope", " @Retention(RetentionPolicy.RUNTIME)", " @interface RequestScoped {}", " ", " @Provides", " int something(@RequestScoped Integer bar) {", " return 42;", " }", "}") .doTest(); } }
6,200
31.984043
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/ScopeOrQualifierAnnotationRetentionTest.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.inject; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import java.util.Collections; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class ScopeOrQualifierAnnotationRetentionTest { private final BugCheckerRefactoringTestHelper refactoringTestHelper = BugCheckerRefactoringTestHelper.newInstance( ScopeOrQualifierAnnotationRetention.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ScopeOrQualifierAnnotationRetention.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceFile("ScopeOrQualifierAnnotationRetentionPositiveCases.java") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceFile("ScopeOrQualifierAnnotationRetentionNegativeCases.java") .doTest(); } @Test public void refactoring() { refactoringTestHelper .addInputLines( "in/Anno.java", "import static java.lang.annotation.ElementType.METHOD;", "import static java.lang.annotation.ElementType.TYPE;", "", "import java.lang.annotation.Target;", "import javax.inject.Qualifier;", "", "@Qualifier", "@Target({TYPE, METHOD})", "public @interface Anno {}") .addOutputLines( "out/Anno.java", "import static java.lang.annotation.ElementType.METHOD;", "import static java.lang.annotation.ElementType.TYPE;", "import static java.lang.annotation.RetentionPolicy.RUNTIME;", "", "import java.lang.annotation.Retention;", "import java.lang.annotation.Target;", "import javax.inject.Qualifier;", "", "@Qualifier", "@Target({TYPE, METHOD})", "@Retention(RUNTIME)", "public @interface Anno {}") .doTest(); } @Test public void nestedQualifierInDaggerModule() { compilationHelper .addSourceLines( "DaggerModule.java", // "@dagger.Module class DaggerModule {", "@javax.inject.Scope", "public @interface TestAnnotation {}", "}") .doTest(); } @Test public void ignoredOnAndroid() { compilationHelper .setArgs(Collections.singletonList("-XDandroidCompatible=true")) .addSourceLines( "TestAnnotation.java", // "@javax.inject.Scope", "public @interface TestAnnotation {}") .doTest(); } @Test public void sourceRetentionStillFiringOnAndroid() { compilationHelper .setArgs(Collections.singletonList("-XDandroidCompatible=true")) .addSourceLines( "TestAnnotation.java", "import java.lang.annotation.Retention;", "import java.lang.annotation.RetentionPolicy;", "@javax.inject.Scope", "// BUG: Diagnostic contains: @Retention(RUNTIME)", "@Retention(RetentionPolicy.SOURCE)", "public @interface TestAnnotation {}") .doTest(); } }
3,996
31.762295
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/QualifierWithTypeUseTest.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.inject; 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 QualifierWithTypeUseTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(QualifierWithTypeUse.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("QualifierWithTypeUsePositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("QualifierWithTypeUseNegativeCases.java").doTest(); } }
1,326
29.860465
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/ScopeOnModuleTest.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.inject.dagger; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link ScopeOnModule}. */ @RunWith(JUnit4.class) public class ScopeOnModuleTest { private BugCheckerRefactoringTestHelper testHelper; @Before public void setUp() { testHelper = BugCheckerRefactoringTestHelper.newInstance(ScopeOnModule.class, getClass()); } @Test public void removeScope() { testHelper .addInputLines( "in/Test.java", "import dagger.Module;", "import dagger.Provides;", "import javax.inject.Singleton;", "", "@Module", "@Singleton", "class Test {", " @Provides", " @Singleton", " Object provideObject() {", " return new Object();", " }", "}") .addOutputLines( "out/Test.java", "import dagger.Module;", "import dagger.Provides;", "import javax.inject.Singleton;", "", "@Module", "class Test {", " @Provides", " @Singleton", " Object provideObject() {", " return new Object();", " }", "}") .doTest(); } @Test public void customScope() { testHelper .addInputLines( "in/Test.java", "import dagger.Module;", "import dagger.Provides;", "import javax.inject.Scope;", "", "@Module", "@Test.MyScope", "class Test {", " @Scope @interface MyScope {}", "", " @Provides", " @MyScope", " Object provideObject() {", " return new Object();", " }", "}") .addOutputLines( "out/Test.java", "import dagger.Module;", "import dagger.Provides;", "import javax.inject.Scope;", "", "@Module", "class Test {", " @Scope @interface MyScope {}", "", " @Provides", " @MyScope", " Object provideObject() {", " return new Object();", " }", "}") .doTest(); } @Test public void notAScope() { testHelper .addInputLines( "in/Test.java", "import dagger.Module;", "import dagger.Provides;", "", "@Module", "@Test.NotAScope", "class Test {", " @interface NotAScope {}", "", " @Provides", " Object provideObject() {", " return new Object();", " }", "}") .expectUnchanged() .doTest(); } }
3,641
26.801527
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/PrivateConstructorForNoninstantiableModuleTest.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.inject.dagger; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author Gregory Kick (gak@google.com) */ @RunWith(JUnit4.class) public final class PrivateConstructorForNoninstantiableModuleTest { private BugCheckerRefactoringTestHelper testHelper; @Before public void setUp() { testHelper = BugCheckerRefactoringTestHelper.newInstance( PrivateConstructorForNoninstantiableModule.class, getClass()); } @Test public void emptyModuleGetsLeftAlone() { testHelper .addInputLines( "in/Test.java", // "import dagger.Module;", "@Module class Test {}") .expectUnchanged() .doTest(); } @Test public void onlyStaticMethods() { testHelper .addInputLines( "in/TestModule.java", // "import dagger.Module;", "import dagger.Provides;", "@Module final class TestModule {", " @Provides static String provideString() { return \"\"; }", " @Provides static Integer provideInteger() { return 1; }", "}") .addOutputLines( "out/TestModule.java", // "import dagger.Module;", "import dagger.Provides;", "@Module final class TestModule {", " @Provides static String provideString() { return \"\"; }", " @Provides static Integer provideInteger() { return 1; }", " private TestModule() {}", "}") .doTest(); } @Test public void onlyStaticMethods_withConstructorGetsLeftAlone() { testHelper .addInputLines( "in/TestModule.java", // "import dagger.Module;", "import dagger.Provides;", "@Module final class TestModule {", " @Provides static String provideString() { return \"\"; }", " @Provides static Integer provideInteger() { return 1; }", " private TestModule() {}", "}") .expectUnchanged() .doTest(); } @Test public void abstractClassWithStaticAndAbstractMethods() { testHelper .addInputLines( "in/TestModule.java", "import dagger.Binds;", "import dagger.Module;", "import dagger.Provides;", "@Module abstract class TestModule {", " @Provides static String provideString() { return \"\"; }", " @Binds abstract Object bindObject(String string);", " @Provides static Integer provideInteger() { return 1; }", " @Binds abstract Number bindNumber(Integer integer);", "}") .addOutputLines( "out/TestModule.java", // "import dagger.Binds;", "import dagger.Module;", "import dagger.Provides;", "@Module abstract class TestModule {", " @Provides static String provideString() { return \"\"; }", " @Binds abstract Object bindObject(String string);", " @Provides static Integer provideInteger() { return 1; }", " @Binds abstract Number bindNumber(Integer integer);", " private TestModule() {}", "}") .doTest(); } @Test public void abstractClassWithStaticAndAbstractMethods_withConstructorGetsLeftAlone() { testHelper .addInputLines( "in/TestModule.java", "import dagger.Binds;", "import dagger.Module;", "import dagger.Provides;", "@Module abstract class TestModule {", " @Provides static String provideString() { return \"\"; }", " @Binds abstract Object bindObject(String string);", " @Provides static Integer provideInteger() { return 1; }", " @Binds abstract Number bindNumber(Integer integer);", " private TestModule() {}", "}") .expectUnchanged() .doTest(); } @Test public void onlyAbstractMethods() { testHelper .addInputLines( "in/TestModule.java", "import dagger.Binds;", "import dagger.Module;", "@Module abstract class TestModule {", " @Binds abstract Object bindObject(String string);", " @Binds abstract Number bindNumber(Integer integer);", "}") .addOutputLines( "out/TestModule.java", // "import dagger.Binds;", "import dagger.Module;", "@Module abstract class TestModule {", " @Binds abstract Object bindObject(String string);", " @Binds abstract Number bindNumber(Integer integer);", " private TestModule() {}", "}") .doTest(); } @Test public void onlyAbstractMethods_withConstructorGetsLeftAlone() { testHelper .addInputLines( "in/TestModule.java", "import dagger.Binds;", "import dagger.Module;", "@Module abstract class TestModule {", " @Binds abstract Object bindObject(String string);", " @Binds abstract Number bindNumber(Integer integer);", " private TestModule() {}", "}") .expectUnchanged() .doTest(); } @Test public void interfaceModuleGetsLeftAlone() { testHelper .addInputLines( "in/TestModule.java", "import dagger.Binds;", "import dagger.Module;", "@Module interface TestModule {", " @Binds Object bindObject(String string);", " @Binds Number bindNumber(Integer integer);", "}") .expectUnchanged() .doTest(); } }
6,493
33.178947
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/AndroidInjectionBeforeSuperTest.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.inject.dagger; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link AndroidInjectionBeforeSuper}. */ @RunWith(JUnit4.class) public final class AndroidInjectionBeforeSuperTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(AndroidInjectionBeforeSuper.class, getClass()) .addSourceFile("testdata/stubs/android/app/Activity.java") .addSourceFile("testdata/stubs/android/app/Fragment.java") .addSourceFile("testdata/stubs/android/app/Service.java") .addSourceFile("testdata/stubs/android/content/Context.java") .addSourceFile("testdata/stubs/android/content/Intent.java") .addSourceFile("testdata/stubs/android/os/Bundle.java") .addSourceFile("testdata/stubs/android/os/IBinder.java"); @Test public void positiveCase() { compilationHelper .addSourceFile("AndroidInjectionBeforeSuperPositiveCases.java") .addSourceFile("AndroidInjection.java") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceFile("AndroidInjectionBeforeSuperNegativeCases.java") .addSourceFile("AndroidInjection.java") .doTest(); } }
1,980
35.685185
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/ProvidesNullTest.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.inject.dagger; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link ProvidesNull}. */ @RunWith(JUnit4.class) public class ProvidesNullTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ProvidesNull.class, getClass()); // Positive cases @Test public void simple() { compilationHelper .addSourceLines( "Test.java", "import dagger.Provides;", "public class Test {", " @Provides public Object providesObject() {", " // BUG: Diagnostic contains: Did you mean '@Nullable' or 'throw new" + " RuntimeException();'", " return null;", " }", "}") .doTest(); } @Test public void hasJavaxAnnotationNullable() { compilationHelper .addSourceLines( "Test.java", "import dagger.Provides;", "import javax.annotation.Nullable;", "public class Test {", " @Provides", " @Nullable", " public Object providesObject() {", " return null;", " }", "}") .doTest(); } @Test public void hasOtherNullable() { compilationHelper .addSourceLines("Nullable.java", "public @interface Nullable {}") .addSourceLines( "Test.java", "import dagger.Provides;", "public class Test {", " @Provides", " @Nullable", " public Object providesObject() {", " return null;", " }", "}") .doTest(); } @Test public void hasTypeUseNullableOnMethod() { compilationHelper .addSourceLines( "Test.java", "import dagger.Provides;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class Test {", " @Provides", " @Nullable", " public Object providesObject() {", " // BUG: Diagnostic contains: Did you mean '@Nullable' or 'throw new" + " RuntimeException();'", " return null;", " }", "}") .doTest(); } @Test public void hasTypeUseNullableOnReturnType() { compilationHelper .addSourceLines( "Test.java", "import dagger.Provides;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class Test {", " @Provides", " public @Nullable Object providesObject() {", " // BUG: Diagnostic contains: Did you mean '@Nullable' or 'throw new" + " RuntimeException();'", " return null;", " }", "}") .doTest(); } /** * Tests that we do not flag Guice {@code @Provides} methods. While this is also wrong, there is * no enforcement in Guice and so the incorrect usage is too common to error on. */ @Test public void guiceProvides() { compilationHelper .addSourceLines( "Test.java", "import com.google.inject.Provides;", "public class Test {", " @Provides", " public Object providesObject() {", " return null;", " }", "}") .doTest(); } @Test public void inCatch() { compilationHelper .addSourceLines( "Test.java", "import java.io.IOException;", "import dagger.Provides;", "public class Test {", " @Provides public Object providesObject() {", " try {", " return new Object();", " } catch (Exception e) {", " // BUG: Diagnostic contains: Did you mean 'throw new RuntimeException(e);' or" + " '@Nullable'", " return null;", " }", " }", "}") .doTest(); } @Test public void inTry() { compilationHelper .addSourceLines( "Test.java", "import dagger.Provides;", "public class Test {", " @Provides public Object providesObject() {", " try {", " // BUG: Diagnostic contains: Did you mean '@Nullable' or 'throw new" + " RuntimeException();'", " return null;", " } catch (Exception e) {", " return new Object();", " }", " }", "}") .doTest(); } @Test public void returnWithNoExpression() { compilationHelper .addSourceLines( "Test.java", "import dagger.Provides;", "public class Test {", " public void doNothing() {", " return;", " }", "}") .doTest(); } }
5,724
28.663212
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/UseBindsTest.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.inject.dagger; import com.google.errorprone.BugCheckerRefactoringTestHelper; import dagger.Module; import dagger.Provides; import dagger.producers.ProducerModule; import dagger.producers.Produces; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** Tests for {@link UseBinds}. */ @RunWith(Parameterized.class) public class UseBindsTest { @Parameters(name = "{0}") public static List<Object[]> data() { return Arrays.asList( new Object[][] { {Provides.class.getCanonicalName(), Module.class.getCanonicalName()}, {Produces.class.getCanonicalName(), ProducerModule.class.getCanonicalName()} }); } private final String bindingMethodAnnotation; private final String moduleAnnotation; private BugCheckerRefactoringTestHelper testHelper; public UseBindsTest(String bindingMethodAnnotation, String moduleAnnotation) { this.bindingMethodAnnotation = bindingMethodAnnotation; this.moduleAnnotation = moduleAnnotation; } @Before public void setUp() { testHelper = BugCheckerRefactoringTestHelper.newInstance(UseBinds.class, getClass()); } @Test public void staticProvidesMethod() { testHelper .addInputLines( "in/Test.java", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "class Test {", " @" + bindingMethodAnnotation, " static Random provideRandom(SecureRandom impl) {", " return impl;", " }", "}") .addOutputLines( "out/Test.java", "import dagger.Binds;", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "abstract class Test {", " @Binds abstract Random provideRandom(SecureRandom impl);", "}") .doTest(); } @Test public void staticProvidesMethod_inInterface() { testHelper .addInputLines( "in/Test.java", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "interface Test {", " @" + bindingMethodAnnotation, " static Random provideRandom(SecureRandom impl) {", " return impl;", " }", "}") .addOutputLines( "out/Test.java", "import dagger.Binds;", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "interface Test {", " @Binds Random provideRandom(SecureRandom impl);", "}") .doTest(); } @Test public void intoSetMethod() { testHelper .addInputLines( "in/Test.java", "import dagger.multibindings.IntoSet;", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "class Test {", " @" + bindingMethodAnnotation, " @IntoSet static Random provideRandom(SecureRandom impl) {", " return impl;", " }", "}") .addOutputLines( "out/Test.java", "import dagger.Binds;", "import dagger.multibindings.IntoSet;", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "abstract class Test {", " @Binds @IntoSet abstract Random provideRandom(SecureRandom impl);", "}") .doTest(); } @Test public void instanceProvidesMethod() { testHelper .addInputLines( "in/Test.java", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "class Test {", " @" + bindingMethodAnnotation, " Random provideRandom(SecureRandom impl) {", " return impl;", " }", "}") .addOutputLines( "out/Test.java", "import dagger.Binds;", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "abstract class Test {", " @Binds abstract Random provideRandom(SecureRandom impl);", "}") .doTest(); } @Test public void multipleBindsMethods() { testHelper .addInputLines( "in/Test.java", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "class Test {", " @" + bindingMethodAnnotation, " Random provideRandom(SecureRandom impl) {", " return impl;", " }", " @" + bindingMethodAnnotation, " Object provideRandomObject(SecureRandom impl) {", " return impl;", " }", "}") .addOutputLines( "out/Test.java", "import dagger.Binds;", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "abstract class Test {", " @Binds abstract Random provideRandom(SecureRandom impl);", " @Binds abstract Object provideRandomObject(SecureRandom impl);", "}") .doTest(); } @Test public void instanceProvidesMethodWithInstanceSibling() { testHelper .addInputLines( "in/Test.java", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "class Test {", " @" + bindingMethodAnnotation, " Random provideRandom(SecureRandom impl) {", " return impl;", " }", " @" + bindingMethodAnnotation, " SecureRandom provideSecureRandom() {", " return new SecureRandom();", " }", "}") .expectUnchanged() .doTest(); } @Test public void instanceProvidesMethodWithStaticSibling() { testHelper .addInputLines( "in/Test.java", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "class Test {", " @" + bindingMethodAnnotation, " Random provideRandom(SecureRandom impl) {", " return impl;", " }", " @" + bindingMethodAnnotation, " static SecureRandom provideRandom() {", " return new SecureRandom();", " }", "}") .addOutputLines( "out/Test.java", "import dagger.Binds;", "import java.security.SecureRandom;", "import java.util.Random;", "@" + moduleAnnotation, "abstract class Test {", " @Binds abstract Random provideRandom(SecureRandom impl);", " @" + bindingMethodAnnotation, " static SecureRandom provideRandom() {", " return new SecureRandom();", " }", "}") .doTest(); } @Test public void notABindsMethod() { testHelper .addInputLines( "in/Test.java", "import java.util.Random;", "@" + moduleAnnotation, "class Test {", " @" + bindingMethodAnnotation, " Random provideRandom() {", " return new Random();", " }", "}") .expectUnchanged() .doTest(); } }
8,614
31.026022
89
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/EmptySetMultibindingContributionsTest.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.inject.dagger; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Sets; import com.google.errorprone.BugCheckerRefactoringTestHelper; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.TreeSet; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** Tests {@link EmptySetMultibindingContributions}. */ @RunWith(Parameterized.class) public final class EmptySetMultibindingContributionsTest { @Parameters(name = "{0}") public static List<Object[]> data() { return Arrays.asList( new Object[][] { {Collections.class.getCanonicalName() + ".emptySet()"}, {ImmutableSet.class.getCanonicalName() + ".of()"}, {ImmutableSortedSet.class.getCanonicalName() + ".of()"}, {"new " + HashSet.class.getCanonicalName() + "<>()"}, {"new " + LinkedHashSet.class.getCanonicalName() + "<>()"}, {"new " + TreeSet.class.getCanonicalName() + "<>()"}, {Sets.class.getCanonicalName() + ".newHashSet()"}, {Sets.class.getCanonicalName() + ".newLinkedHashSet()"}, {Sets.class.getCanonicalName() + ".newConcurrentHashSet()"}, {EnumSet.class.getCanonicalName() + ".noneOf(java.util.concurrent.TimeUnit.class)"}, }); } private final String emptySetSnippet; private BugCheckerRefactoringTestHelper testHelper; public EmptySetMultibindingContributionsTest(String emptySetSnippet) { this.emptySetSnippet = emptySetSnippet; } @Before public void setUp() { testHelper = BugCheckerRefactoringTestHelper.newInstance( EmptySetMultibindingContributions.class, getClass()); } @Test public void elementsIntoSetMethod_emptySet() { testHelper .addInputLines( "in/Test.java", "import dagger.Module;", "import dagger.Provides;", "import dagger.multibindings.ElementsIntoSet;", "import java.util.Set;", "@Module", "class Test {", " @Provides @ElementsIntoSet Set<?> provideEmpty() {", String.format(" return %s;", emptySetSnippet), " }", "}") .addOutputLines( "out/Test.java", "import dagger.Module;", "import dagger.Provides;", "import dagger.multibindings.ElementsIntoSet;", "import dagger.multibindings.Multibinds;", "import java.util.Set;", "@Module", "abstract class Test {", " @Multibinds abstract Set<?> provideEmpty();", "}") .doTest(); } }
3,546
35.193878
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/testdata/AndroidInjectionBeforeSuperNegativeCases.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.inject.dagger.testdata; import android.app.Activity; import android.app.Fragment; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; import dagger.android.AndroidInjection; final class AndroidInjectionBeforeSuperNegativeCases { public class CorrectOrder extends Activity { @Override public void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); super.onCreate(savedInstanceState); } } public class StatementsInBetween extends Activity { @Override public void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); System.out.println("hello, world"); super.onCreate(savedInstanceState); } } public static class BaseActivity extends Activity {} public class ExtendsBase extends BaseActivity { @Override public void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); super.onCreate(savedInstanceState); } } public static class Foo { public void onCreate(Bundle bundle) {} } public class FooActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { new Foo().onCreate(savedInstanceState); AndroidInjection.inject(this); super.onCreate(savedInstanceState); } } public abstract class ActivityWithAbstractOnCreate extends Activity { @Override public void onCreate(Bundle savedInstanceState) {} public abstract void onCreate(Bundle savedInstanceState, boolean bar); } public class CorrectOrderFragment extends Fragment { @Override public void onAttach(Activity activity) { AndroidInjection.inject(this); super.onAttach(activity); } } public class CorrectOrderService extends Service { @Override public void onCreate() { AndroidInjection.inject(this); super.onCreate(); } @Override public IBinder onBind(Intent intent) { return null; } } }
2,660
26.71875
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/testdata/AndroidInjection.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 dagger.android; import android.app.Activity; import android.app.Fragment; import android.app.Service; /** * Stub class for {@code dagger.android.AndroidInjection}. ErrorProne isn't an Android project and * can't depend on an {@code .aar} in Maven, so this is provided as a stub for testing. */ public final class AndroidInjection { public static void inject(Activity activity) {} public static void inject(Fragment fragment) {} public static void inject(Service service) {} }
1,106
31.558824
98
java