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/IdentityHashMapUsageTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link IdentityHashMapUsage} bug pattern. */ @RunWith(JUnit4.class) public class IdentityHashMapUsageTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(IdentityHashMapUsage.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(IdentityHashMapUsage.class, getClass()); @Test public void equals_putAll_positive() { compilationHelper .addSourceLines( "Test.java", "import java.util.IdentityHashMap;", "import java.util.Map;", "class Test {", " boolean test(Map map, IdentityHashMap ihm) {", " // BUG: Diagnostic contains: IdentityHashMapUsage", " return ihm.equals(map);", " }", " void putAll(Map map, IdentityHashMap ihm) {", " // BUG: Diagnostic contains: IdentityHashMapUsage", " ihm.putAll(map);", " }", "}") .doTest(); } @Test public void equals_putAll_negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.IdentityHashMap;", "import java.util.Map;", "class Test {", " boolean test(Map map, IdentityHashMap ihm) {", " return map.equals(ihm);", " }", " boolean equalsSameType(IdentityHashMap ihm, IdentityHashMap ihm2) {", " return ihm.equals(ihm2);", " }", " void putAll(Map map, IdentityHashMap ihm) {", " map.putAll(ihm);", " }", " void putAllSameType(IdentityHashMap ihm, IdentityHashMap ihm2) {", " ihm.putAll(ihm2);", " }", "}") .doTest(); } @Test public void assignmentToMap() { compilationHelper .addSourceLines( "Test.java", "import java.util.IdentityHashMap;", "import java.util.Map;", "class Test {", " Map putAll(IdentityHashMap ihm) {", " Map map;", " // BUG: Diagnostic contains: IdentityHashMapUsage", " map = ihm;", " return map;", " }", "}") .doTest(); } @Test public void variableInitializationToSuperType() { refactoringHelper .addInputLines( "Test.java", "import java.util.IdentityHashMap;", "import java.util.Map;", "class Test {", " Map putAll(IdentityHashMap ihmArg) {", " Map map = ihmArg;", " return map;", " }", "}") .addOutputLines( "Test.java", "import java.util.IdentityHashMap;", "import java.util.Map;", "class Test {", " Map putAll(IdentityHashMap ihmArg) {", " IdentityHashMap map = ihmArg;", " return map;", " }", "}") .doTest(); } @Test public void ihmInitializationWithNonIhm() { compilationHelper .addSourceLines( "Test.java", "import java.util.IdentityHashMap;", "import java.util.Map;", "class Test {", " IdentityHashMap something(Map mapArg) {", " // BUG: Diagnostic contains: IdentityHashMapUsage", " return new IdentityHashMap(mapArg);", " }", "}") .doTest(); } @Test public void fieldType() { refactoringHelper .addInputLines( "Test.java", "import java.util.IdentityHashMap;", "import java.util.Map;", "class Test {", " private final Map<String, Integer> m = new IdentityHashMap<>();", "}") .addOutputLines( "Test.java", "import java.util.IdentityHashMap;", "import java.util.Map;", "class Test {", " private final IdentityHashMap<String, Integer> m = new IdentityHashMap<>();", "}") .doTest(); } }
5,096
31.464968
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/PreconditionsCheckNotNullRepeatedTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link PreconditionsCheckNotNullRepeated} check. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class PreconditionsCheckNotNullRepeatedTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance( PreconditionsCheckNotNullRepeated.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(PreconditionsCheckNotNullRepeated.class, getClass()); @Test public void positiveMatchesWithReplacement() { testHelper .addInputLines( "in/Test.java", "import static com.google.common.base.Preconditions.checkNotNull;", "import com.google.common.base.Preconditions;", "public class Test {", " public void error() {", " Object someObject = new Object();", " Preconditions.checkNotNull(someObject, someObject);", " checkNotNull(someObject, someObject);", " }", "}") .addOutputLines( "out/Test.java", "import static com.google.common.base.Preconditions.checkNotNull;", "import com.google.common.base.Preconditions;", "public class Test {", " public void error() {", " Object someObject = new Object();", " Preconditions.checkNotNull(someObject, \"someObject must not be null\");", " checkNotNull(someObject, \"someObject must not be null\");", " }", "}") .doTest(); } @Test public void flagArgInVarargs() { compilationHelper .addSourceLines( "out/Test.java", "import static com.google.common.base.Preconditions.checkNotNull;", "import com.google.common.base.Preconditions;", "public class Test {", " public void notError() {", " Object obj = new Object();", " Preconditions.checkNotNull(", " obj, \"%s must not be null\",", " // BUG: Diagnostic contains: Including `obj` in the failure message", " obj);", " String s = \"test string\";", " // BUG: Diagnostic contains: PreconditionsCheckNotNullRepeated", " Preconditions.checkNotNull(s, s, s);", " }", "}") .doTest(); } @Test public void negativeCases() { compilationHelper .addSourceLines( "out/Test.java", "import static com.google.common.base.Preconditions.checkNotNull;", "import com.google.common.base.Preconditions;", "public class Test {", " public void notError() {", " Object obj = new Object();", " Preconditions.checkNotNull(obj);", " Preconditions.checkNotNull(obj, \"obj\");", " Preconditions.checkNotNull(obj, \"check with message\");", " Preconditions.checkNotNull(obj, \"check with msg and an arg %s\", new Object());", " }", "}") .doTest(); } }
4,071
36.703704
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnitAssertSameCheckTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link JUnitAssertSameCheck} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class JUnitAssertSameCheckTest { CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(JUnitAssertSameCheck.class, getClass()); } @Test public void positiveCase() { compilationHelper.addSourceFile("JUnitAssertSameCheckPositiveCase.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("JUnitAssertSameCheckNegativeCases.java").doTest(); } }
1,448
28.571429
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ModifyCollectionInEnhancedForLoopTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author anishvisaria98@gmail.com (Anish Visaria) */ @RunWith(JUnit4.class) public class ModifyCollectionInEnhancedForLoopTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ModifyCollectionInEnhancedForLoop.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("ModifyCollectionInEnhancedForLoopPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("ModifyCollectionInEnhancedForLoopNegativeCases.java").doTest(); } @Test public void modifyCollectionInItself() { compilationHelper .addSourceLines( "Test.java", "import java.util.AbstractCollection;", "import java.util.Collection;", "abstract class Test<E> extends AbstractCollection<E> {", " public boolean addAll(Collection<? extends E> c) {", " boolean modified = false;", " for (E e : c)", " if (add(e))", " modified = true;", " return modified;", " }", "}") .doTest(); } @Test public void concurrentMap() { compilationHelper .addSourceLines( "Test.java", "import java.util.Map;", "import java.util.concurrent.ConcurrentMap;", "class Test {", " void f(ConcurrentMap<String, Integer> map) {", " for (Map.Entry<String, Integer> e : map.entrySet()) {", " map.remove(e.getKey());", " }", " }", "}") .doTest(); } }
2,466
31.038961
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ComplexBooleanConstantTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link ComplexBooleanConstantTest}. * * @author Sumit Bhagwani (bhagwani@google.com) */ @RunWith(JUnit4.class) public class ComplexBooleanConstantTest { private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(ComplexBooleanConstant.class, getClass()); @Test public void refactorTest() { refactoringHelper .addInputLines( "in/Foo.java", "class Foo {", " int CONSTANT1 = 1;", " int CONSTANT2 = 1;", " int barNoOp() {", " return 1 - 1;", " }", " boolean barNoOpWithConstants() {", " return CONSTANT1 == CONSTANT2;", " }", " boolean barEquals() {", " return 1 == 1;", " }", " boolean barNotEquals() {", " return 1 != 1;", " }", " boolean f(boolean x) {", " boolean r;", " r = x || !false;", " r = x || !true;", " r = x || true;", " r = x && !false;", " r = x && !true;", " r = x && false;", " return r;", " }", "}") .addOutputLines( "out/Foo.java", "class Foo {", " int CONSTANT1 = 1;", " int CONSTANT2 = 1;", " int barNoOp() {", " return 1 - 1;", " }", " boolean barNoOpWithConstants() {", " return CONSTANT1 == CONSTANT2;", " }", " boolean barEquals() {", " return true;", " }", " boolean barNotEquals() {", " return false;", " }", " boolean f(boolean x) {", " boolean r;", " r = true;", " r = x || !true;", " r = true;", " r = x && !false;", " r = false;", " r = false;", " return r;", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void negative() { CompilationTestHelper.newInstance(ComplexBooleanConstant.class, getClass()) .addSourceLines( "A.java", // "package a;", "class A {", " static final int A = 1;", " static final int B = 2;", " static final boolean C = A > B;", " static final boolean D = A + B > 0;", " static final boolean E = (A + B) > 0;", "}") .doTest(); } }
3,619
31.035398
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InstanceOfAndCastMatchWrongTypeTest.java
/* Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sulku@google.com (Marsela Sulku) * @author mariasam@google.com (Maria Sam) */ @RunWith(JUnit4.class) public class InstanceOfAndCastMatchWrongTypeTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InstanceOfAndCastMatchWrongType.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("InstanceOfAndCastMatchWrongTypePositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("InstanceOfAndCastMatchWrongTypeNegativeCases.java").doTest(); } @Test public void regressionTestIssue651() { compilationHelper .addSourceLines( "Foo.java", "class Foo {", " void foo() {", " Object[] values = null;", " if (values[0] instanceof Integer) {", " int x = (Integer) values[0];", " } else if (values[0] instanceof Long) {", " long y = (Long) values[0];", " }", " }", "}") .doTest(); } @Test public void handlesArrayAccessOnIdentifier() { compilationHelper .addSourceLines( "Foo.java", "class Foo {", " void foo() {", " Object[] values = null;", " if (values[0] instanceof Integer) {", " // BUG: Diagnostic contains:", " String s0 = (String) values[0];", // OK because indices are different " String s1 = (String) values[1];", " }", " }", "}") .doTest(); } @Test public void doesNotHandleArrayAccessOnNonIdentifiers() { compilationHelper .addSourceLines( "Foo.java", "class Foo {", " private Object[] getArray() {", " return new Object[0];", " }", " void doIt() {", " if (getArray()[0] instanceof Integer) {", " String s0 = (String) getArray()[0];", " }", " }", "}") .doTest(); } }
2,980
29.731959
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryMethodInvocationMatcherTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author amalloy@google.com (Alan Malloy) */ @RunWith(JUnit4.class) public class UnnecessaryMethodInvocationMatcherTest { private final BugCheckerRefactoringTestHelper refactoringTestHelper = BugCheckerRefactoringTestHelper.newInstance( UnnecessaryMethodInvocationMatcher.class, getClass()); @Test public void replace() { refactoringTestHelper .addInputLines( "Test.java", "import static com.google.errorprone.matchers.Matchers.*;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.ExpressionTree;", "public class Test {", " private static final Matcher<ExpressionTree> TO_STRING = ", " methodInvocation(", " instanceMethod()", " .anyClass()", " .named(\"toString\"));", "}") .addOutputLines( "Test.java", "import static com.google.errorprone.matchers.Matchers.*;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.ExpressionTree;", "public class Test {", " private static final Matcher<ExpressionTree> TO_STRING = ", " instanceMethod()", " .anyClass()", " .named(\"toString\");", "}") .doTest(); } @Test public void descendIntoCombinators() { refactoringTestHelper .addInputLines( "Test.java", "import static com.google.errorprone.matchers.Matchers.*;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.ExpressionTree;", "public class Test {", " private static final Matcher<ExpressionTree> STRINGIFY = ", " methodInvocation(", " anyOf(", " instanceMethod()", " .anyClass()", " .named(\"toString\"),", " allOf(", " staticMethod())));", "}") .addOutputLines( "Test.java", "import static com.google.errorprone.matchers.Matchers.*;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.ExpressionTree;", "public class Test {", " private static final Matcher<ExpressionTree> STRINGIFY = ", " anyOf(", " instanceMethod()", " .anyClass()", " .named(\"toString\"),", " allOf(", " staticMethod()));", "}") .doTest(); } @Test public void onlyChangeMethodMatchers() { refactoringTestHelper .addInputLines( "Test.java", "import static com.google.errorprone.matchers.Matchers.*;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.ExpressionTree;", "public class Test {", " private static final Matcher<ExpressionTree> STRINGIFY = ", " methodInvocation(", " anyOf(", " instanceMethod()", " .anyClass()", " .named(\"toString\"),", " allOf(", " hasAnnotation(\"java.lang.SuppressWarnings\"))));", "}") .expectUnchanged() .doTest(); } @Test public void permitWithArguments() { refactoringTestHelper .addInputLines( "Test.java", "import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.ALL;", "import static com.google.errorprone.matchers.Matchers.*;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.ExpressionTree;", "public class Test {", " private static final Matcher<ExpressionTree> TO_STRING = ", " methodInvocation(", " instanceMethod()", " .anyClass()", " .named(\"toString\"),", " ALL,", " isVariable());", "}") .expectUnchanged() .doTest(); } @Test public void expressionStatement() { refactoringTestHelper .addInputLines( "Test.java", "import static com.google.errorprone.matchers.Matchers.*;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.StatementTree;", "public class Test {", " private static final Matcher<StatementTree> TARGETED =", " expressionStatement(", " methodInvocation(", " instanceMethod()", " .onDescendantOfAny(", " \"java.lang.Class\",", " \"java.lang.String\")));", "}") .addOutputLines( "Test.java", "import static com.google.errorprone.matchers.Matchers.*;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.StatementTree;", "public class Test {", " private static final Matcher<StatementTree> TARGETED =", " expressionStatement(", " instanceMethod()", " .onDescendantOfAny(", " \"java.lang.Class\",", " \"java.lang.String\"));", "}") .doTest(); } }
6,489
36.298851
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ArrayToStringTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ArrayToString}Test */ @RunWith(JUnit4.class) public class ArrayToStringTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ArrayToString.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(ArrayToString.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("ArrayToStringPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("ArrayToStringNegativeCases.java").doTest(); } @Test public void stringConcat() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f(int[] xs) {", " // BUG: Diagnostic contains: (\"\" + Arrays.toString(xs));", " System.err.println(\"\" + xs);", " String s = \"\";", " // BUG: Diagnostic contains: s += Arrays.toString(xs);", " s += xs;", " }", "}") .doTest(); } @Test public void printString() { refactoringHelper .addInputLines( "Test.java", "class Test {", " int[] g() { return null; }", " void f(int[] xs) {", " System.err.println(xs);", " System.err.println(String.valueOf(xs));", " System.err.println(String.valueOf(g()));", " }", "}") .addOutputLines( "Test.java", "import java.util.Arrays;", "class Test {", " int[] g() { return null; }", " void f(int[] xs) {", " System.err.println(Arrays.toString(xs));", " System.err.println(Arrays.toString(xs));", " System.err.println(Arrays.toString(g()));", " }", "}") .doTest(); } @Test public void negativePrintString() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f(char[] xs) {", " System.err.println(String.valueOf(xs));", " }", "}") .doTest(); } @Test public void stringBuilder() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f(int[] xs) {", " // BUG: Diagnostic contains: append(Arrays.toString(xs))", " new StringBuilder().append(xs);", " }", "}") .doTest(); } /** * Don't complain about {@code @FormatMethod}s; there's a chance they're handling arrays * correctly. */ @Test public void customFormatMethod() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.FormatMethod;", "class Test {", " private void test(Object[] arr) {", " format(\"%s %s\", arr, 2);", " }", " @FormatMethod", " String format(String format, Object... args) {", " return String.format(format, args);", " }", "}") .doTest(); } @Test public void methodReturningArray() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private void test() {", " // BUG: Diagnostic contains:", " String.format(\"%s %s\", arr(), 1);", " }", " Object[] arr() {", " return null;", " }", "}") .doTest(); } @Test public void throwableToString() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void test(Exception e) {", " // BUG: Diagnostic contains: Throwables.getStackTraceAsString(e)", " String.format(\"%s, %s\", 1, e.getStackTrace());", " }", "}") .doTest(); } @Test public void positiveCompoundAssignment() { compilationHelper.addSourceFile("ArrayToStringCompoundAssignmentPositiveCases.java").doTest(); } @Test public void negativeCompoundAssignment() { compilationHelper.addSourceFile("ArrayToStringCompoundAssignmentNegativeCases.java").doTest(); } @Test public void positiveConcat() { compilationHelper.addSourceFile("ArrayToStringConcatenationPositiveCases.java").doTest(); } @Test public void negativeConcat() { compilationHelper.addSourceFile("ArrayToStringConcatenationNegativeCases.java").doTest(); } }
5,590
28.582011
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NullOptionalTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link NullOptional}. */ @RunWith(JUnit4.class) public final class NullOptionalTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(NullOptional.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(NullOptional.class, getClass()); @Test public void simplePositiveCase() { refactoringHelper .addInputLines( "Test.java", "import java.util.Optional;", "class Test {", " void a(Optional<Object> o) {}", " void test() {", " a(null);", " }", "}") .addOutputLines( "Test.java", "import java.util.Optional;", "class Test {", " void a(Optional<Object> o) {}", " void test() {", " a(Optional.empty());", " }", "}") .doTest(); } @Test public void annotatedWithNullable_noMatch() { helper .addSourceLines( "Test.java", "import java.util.Optional;", "import javax.annotation.Nullable;", "class Test {", " void a(@Nullable Optional<Object> o) {}", " void test() {", " a(null);", " }", "}") .doTest(); } @Test public void notPassingNull_noMatch() { helper .addSourceLines( "Test.java", "import java.util.Optional;", "class Test {", " void a(Optional<Object> o) {}", " void test() {", " a(Optional.empty());", " }", "}") .doTest(); } @Test public void withinAssertThrows_noMatch() { helper .addSourceLines( "Test.java", "import static org.junit.Assert.assertThrows;", "import java.util.Optional;", "class Test {", " void a(Optional<Object> o) {}", " void test() {", " assertThrows(NullPointerException.class, () -> a(null));", " }", "}") .doTest(); } @Test public void lastVarArgsParameter_match() { helper .addSourceLines( "Test.java", "import java.util.Optional;", "class Test {", " @SafeVarargs", " private final void a(int a, Optional<Object>... o) {}", " void test() {", " // BUG: Diagnostic contains:", " a(1, Optional.empty(), null);", " }", "}") .doTest(); } }
3,558
28.172131
82
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TypeEqualsCheckerTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link TypeEqualsChecker}. */ @RunWith(JUnit4.class) public class TypeEqualsCheckerTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(TypeEqualsChecker.class, getClass()); @Test public void noMatch() { testHelper .addSourceLines( "ExampleChecker.java", "import com.google.errorprone.BugPattern;", "import com.google.errorprone.BugPattern.SeverityLevel;", "import com.google.errorprone.VisitorState;", "import com.google.errorprone.bugpatterns.BugChecker;", "import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;", "import com.google.errorprone.matchers.Description;", "import com.sun.source.tree.ClassTree;", "import com.sun.tools.javac.code.Types;", "@BugPattern(name = \"Example\", summary = \"\", severity = SeverityLevel.ERROR)", "public class ExampleChecker extends BugChecker implements ClassTreeMatcher {", " @Override public Description matchClass(ClassTree t, VisitorState s) {", " return Description.NO_MATCH;", " }", "}") .addModules("jdk.compiler/com.sun.tools.javac.code") .doTest(); } @Test public void matchInABugChecker() { testHelper .addSourceLines( "ExampleChecker.java", "import static com.google.errorprone.util.ASTHelpers.getSymbol;", "import com.google.errorprone.BugPattern;", "import com.google.errorprone.BugPattern.SeverityLevel;", "import com.google.errorprone.VisitorState;", "import com.google.errorprone.bugpatterns.BugChecker;", "import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;", "import com.google.errorprone.fixes.SuggestedFix;", "import com.google.errorprone.matchers.Description;", "import com.sun.source.tree.ClassTree;", "import com.sun.tools.javac.code.Symbol;", "import com.sun.tools.javac.code.Symbol.ClassSymbol;", "import com.sun.tools.javac.code.Type;", "import com.sun.tools.javac.code.Types;", "import java.util.Objects;", "@BugPattern(name = \"Example\", summary = \"\", severity = SeverityLevel.ERROR)", "public class ExampleChecker extends BugChecker implements ClassTreeMatcher {", " @Override public Description matchClass(ClassTree tree, VisitorState state) {", " Symbol sym = getSymbol(tree);", " Types types = state.getTypes();", " ClassSymbol owner = sym.enclClass();", " for (Type s : types.closure(owner.type)) {", " // BUG: Diagnostic contains: TypeEquals", " if (s.equals(owner.type)) {", " return Description.NO_MATCH;", " }", " // BUG: Diagnostic contains: TypeEquals", " if (Objects.equals(s, owner.type)) {", " return Description.NO_MATCH;", " }", " }", " return Description.NO_MATCH;", " }", "}") .addModules( "jdk.compiler/com.sun.tools.javac.code", "jdk.compiler/com.sun.tools.javac.util") .doTest(); } }
4,209
42.854167
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CheckedExceptionNotThrownTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link CheckedExceptionNotThrown}. */ @RunWith(JUnit4.class) public final class CheckedExceptionNotThrownTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(CheckedExceptionNotThrown.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(CheckedExceptionNotThrown.class, getClass()); @Test public void noExceptionThrown_entireThrowsBlockRemoved() { helper .addInputLines( "Test.java", // "public final class Test {", " /**", " * Frobnicate", " *", " * @throws Exception foo", " */", " void test() throws Exception {}", "}") .addOutputLines( "Test.java", // "public final class Test {", " /**", " * Frobnicate", " *", " */", " void test() {}", "}") .doTest(TEXT_MATCH); } @Test public void exceptionActuallyThrown_noChange() { helper .addInputLines( "Test.java", // "public final class Test {", " void test() throws Exception {", " Thread.sleep(1);", " }", "}") .expectUnchanged() .doTest(); } @Test public void overridable_noChange() { helper .addInputLines( "Test.java", // "public class Test {", " void test() throws Exception {", " }", "}") .expectUnchanged() .doTest(); } @Test public void thrownViaGenericChecked() { helper .addInputLines( "Test.java", // "import java.util.Optional;", "public final class Test {", " int test(Optional<Integer> x) throws Exception {", " return x.orElseThrow(() -> new Exception());", " }", "}") .expectUnchanged() .doTest(); } @Test public void thrownViaGenericUnchecked() { helper .addInputLines( "Test.java", // "import java.util.Optional;", "public final class Test {", " int test(Optional<Integer> x) throws Exception {", " return x.orElseThrow(() -> new IllegalStateException());", " }", "}") .addOutputLines( "Test.java", // "import java.util.Optional;", "public final class Test {", " int test(Optional<Integer> x) {", " return x.orElseThrow(() -> new IllegalStateException());", " }", "}") .doTest(); } @Test public void oneCheckedOneUnchecked() { helper .addInputLines( "Test.java", // "public final class Test {", " void test() throws IllegalStateException, Exception {}", "}") .addOutputLines( "Test.java", // "public final class Test {", " void test() throws IllegalStateException {}", "}") .doTest(); } @Test public void oneCheckedOneUnchecked_finding() { compilationHelper .addSourceLines( "Test.java", // "public final class Test {", " // BUG: Diagnostic contains: (Exception)", " void test() throws IllegalStateException, Exception {}", "}") .doTest(); } @Test public void ignoredOnTestMethods() { helper .addInputLines( "Test.java", // "public final class Test {", " @org.junit.Test", " void test() throws IllegalStateException, Exception {}", "}") .expectUnchanged() .setArgs("-XepCompilingTestOnlyCode") .doTest(); } @Test public void exceptionActuallyThrownInFieldInitializer() { helper .addInputLines( "Test.java", // "public final class Test {", " Test() throws Exception {}", " int f = test();", " static int test() throws Exception {", " Thread.sleep(1);", " return 1;", " }", "}") .expectUnchanged() .doTest(); } }
5,348
28.070652
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UseCorrectAssertInTestsTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static java.util.Arrays.stream; import static java.util.stream.Collectors.joining; 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 galitch@google.com (Anton Galitch) */ @RunWith(JUnit4.class) public final class UseCorrectAssertInTestsTest { private static final String ASSERT_THAT_IMPORT = "import static com.google.common.truth.Truth.assertThat;"; private static final String ASSERT_WITH_MESSAGE_IMPORT = "import static com.google.common.truth.Truth.assertWithMessage;"; private static final String INPUT = "in/FooTest.java"; private static final String OUTPUT = "out/FooTest.java"; private static final String TEST_ONLY = "-XepCompilingTestOnlyCode"; private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(UseCorrectAssertInTests.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UseCorrectAssertInTests.class, getClass()); @Test public void correctAssertInTest() { refactoringHelper .addInputLines( INPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "assertThat(true).isTrue();")) .expectUnchanged() .doTest(); } @Test public void noAssertInTestsFound() { refactoringHelper .addInputLines(INPUT, inputWithExpressions("int a = 1;")) .expectUnchanged() .doTest(); } @Test public void diagnosticIssuedAtFirstAssert() { compilationHelper .addSourceLines( INPUT, "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class FooTest {", " void foo() {", " int x = 1;", " // BUG: Diagnostic contains: UseCorrectAssertInTests", " assert true;", " assert true;", " }", "}") .doTest(); } @Test public void assertInNonTestMethod() { refactoringHelper .addInputLines( INPUT, "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class FooTest {", " void foo() {", " assert true;", " }", "}") .addOutputLines( OUTPUT, ASSERT_THAT_IMPORT, "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class FooTest {", " void foo() {", " assertThat(true).isTrue();", " }", "}") .doTest(); } @Test public void assertInTestOnlyCode() { refactoringHelper .addInputLines( INPUT, "public class FooTest {", // " void foo() {", " assert true;", " }", "}") .addOutputLines( OUTPUT, ASSERT_THAT_IMPORT, "public class FooTest {", " void foo() {", " assertThat(true).isTrue();", " }", "}") .setArgs(TEST_ONLY) .doTest(); } @Test public void assertInNonTestCode() { refactoringHelper .addInputLines( INPUT, "public class FooTest {", // " void foo() {", " assert true;", " }", "}") .expectUnchanged() .doTest(); } @Test public void wrongAssertInTestWithParentheses() { refactoringHelper .addInputLines(INPUT, inputWithExpressions("assert (true);")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "assertThat(true).isTrue();")) .doTest(); } @Test public void wrongAssertInTestWithoutParentheses() { refactoringHelper .addInputLines(INPUT, inputWithExpressions("assert true;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "assertThat(true).isTrue();")) .doTest(); } @Test public void wrongAssertInTestWithDetailString() { refactoringHelper .addInputLines(INPUT, inputWithExpressions("assert (true) : \"description\";")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_WITH_MESSAGE_IMPORT, // "assertWithMessage(\"description\").that(true).isTrue();")) .doTest(); } @Test public void wrongAssertInTestWithDetailStringVariable() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "String desc = \"description\";", // "assert (true) : desc;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_WITH_MESSAGE_IMPORT, // "String desc = \"description\";", "assertWithMessage(desc).that(true).isTrue();")) .doTest(); } @Test public void wrongAssertInTestWithDetailNonStringVariable() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer desc = 1;", // "assert (true) : desc;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_WITH_MESSAGE_IMPORT, // "Integer desc = 1;", "assertWithMessage(desc.toString()).that(true).isTrue();")) .doTest(); } @Test public void wrongAssertFalseCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "boolean a = false;", // "assert (!a);")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "boolean a = false;", "assertThat(a).isFalse();")) .doTest(); } @Test public void wrongAssertEqualsCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "String a = \"test\";", // "assert a.equals(\"test\");")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "String a = \"test\";", "assertThat(a).isEqualTo(\"test\");")) .doTest(); } @Test public void wrongAssertEqualsNullCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = null;", // "assert a == null;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "Integer a = null;", "assertThat(a).isNull();")) .doTest(); } @Test public void wrongAssertEqualsNullCaseLeftSide() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = null;", // "assert null == a;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "Integer a = null;", "assertThat(a).isNull();")) .doTest(); } @Test public void wrongAssertEqualsNullCaseWithDetail() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = null;", // "assert a == null : \"detail\";")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_WITH_MESSAGE_IMPORT, // "Integer a = null;", "assertWithMessage(\"detail\").that(a).isNull();")) .doTest(); } @Test public void wrongAssertNotEqualsNullCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "assert a != null;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "Integer a = 1;", "assertThat(a).isNotNull();")) .doTest(); } @Test public void wrongAssertReferenceSameCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "Integer b = 1;", "assert a == b;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "Integer a = 1;", "Integer b = 1;", "assertThat(a).isSameInstanceAs(b);")) .doTest(); } @Test public void wrongAssertReferenceWithParensCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "Integer b = 1;", "assert (a == b);")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "Integer a = 1;", "Integer b = 1;", "assertThat(a).isSameInstanceAs(b);")) .doTest(); } @Test public void wrongAssertReferenceNotSameCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "Integer b = 1;", "assert a != b;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "Integer a = 1;", "Integer b = 1;", "assertThat(a).isNotSameInstanceAs(b);")) .doTest(); } @Test public void wrongAssertEqualsPrimitiveCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "assert a == 1;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "Integer a = 1;", "assertThat(a).isEqualTo(1);")) .doTest(); } @Test public void wrongAssertNotEqualsPrimitiveCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "assert a != 1;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_THAT_IMPORT, // "Integer a = 1;", "assertThat(a).isNotEqualTo(1);")) .doTest(); } @Test public void wrongAssertReferenceSameCaseWithDetailCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "int a = 1;", // "assert a == 1 : \"detail\";")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( ASSERT_WITH_MESSAGE_IMPORT, // "int a = 1;", "assertWithMessage(\"detail\").that(a).isEqualTo(1);")) .doTest(); } private static String[] inputWithExpressionsAndImport(String importStatement, String... body) { return new String[] { importStatement, "import org.junit.Test;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class FooTest {", " @Test", " void foo() {", stream(body).map(line -> String.format(" %s", line)).collect(joining("\n")), " }", "}" }; } private static String[] inputWithExpressions(String... expr) { return inputWithExpressionsAndImport("", expr); } }
13,117
28.086475
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/HashtableContainsTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link HashtableContains}Test */ @RunWith(JUnit4.class) public class HashtableContainsTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(HashtableContains.class, getClass()); @Test public void positive_cHM() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "import java.util.concurrent.ConcurrentHashMap;", "class Test {", " void f(ConcurrentHashMap<String, Integer> m, Integer v) {", " // BUG: Diagnostic contains: containsValue(v)", " m.contains(v);", " }", "}") .doTest(); } @Test public void positive_hashtable() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "import java.util.Hashtable;", "class Test {", " void f(Hashtable<String, Integer> m, Integer v) {", " // BUG: Diagnostic contains: containsValue(v)", " m.contains(v);", " }", "}") .doTest(); } @Test public void positive_wildcardUpperBound() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "import java.util.Hashtable;", "class Test {", " void f(Hashtable<String, ? extends Number> m, Integer v) {", " // BUG: Diagnostic contains: containsValue(v)", " m.contains(v);", " }", "}") .doTest(); } @Test public void positive_wildcardLowerBound() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "import java.util.Hashtable;", "class Test {", " void f(Hashtable<String, ? super Integer> m, Integer v) {", " // BUG: Diagnostic contains: containsValue(v)", " m.contains(v);", " }", "}") .doTest(); } @Test public void positive_wildcard() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "import java.util.Hashtable;", "class Test {", " void f(Hashtable<String, ?> m, String k) {", " // BUG: Diagnostic contains: 'java.lang.String' could be a key or a value", " // Did you mean 'm.containsValue(k);' or 'm.containsKey(k);'?", " m.contains(k);", " }", "}") .doTest(); } @Test public void positive_containsKey() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "import java.util.Hashtable;", "class Test {", " void f(Hashtable<String, Integer> m, String k) {", " // BUG: Diagnostic contains:", " // argument type 'java.lang.String' looks like a key", " // Did you mean 'm.containsKey(k);'", " m.contains(k);", " }", "}") .doTest(); } @Test public void positive_extendsHashtable() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "import java.util.Hashtable;", "class MyHashTable<K, V> extends Hashtable<K, V> {", " @Override public boolean contains(Object v) {", " // BUG: Diagnostic contains:", " // Did you mean 'return containsValue(v);' or 'return containsKey(v);'?", " return contains(v);", " }", "}") .doTest(); } @Test public void negative_containsAmbiguous() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "import java.util.Hashtable;", "class Test {", " void f(Hashtable<Number, Integer> m, Integer v) {", " // BUG: Diagnostic contains: 'java.lang.Number' could be a key or a value", " // Did you mean 'm.containsValue(v);' or 'm.containsKey(v);'?", " m.contains(v);", " }", "}") .doTest(); } }
5,118
30.404908
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EqualsReferenceTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author mariasam on 6/22/17. */ @RunWith(JUnit4.class) public class EqualsReferenceTest { private final CompilationTestHelper compilationTestHelper = CompilationTestHelper.newInstance(EqualsReference.class, getClass()); @Test public void positiveCases() { compilationTestHelper.addSourceFile("EqualsReferencePositiveCases.java").doTest(); } @Test public void negativeCases() { compilationTestHelper.addSourceFile("EqualsReferenceNegativeCases.java").doTest(); } }
1,297
29.904762
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LoopOverCharArrayTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link LoopOverCharArray}Test */ @RunWith(JUnit4.class) public class LoopOverCharArrayTest { @Test public void refactor() { BugCheckerRefactoringTestHelper.newInstance(LoopOverCharArray.class, getClass()) .addInputLines( "Test.java", "class T {", " void f(String s) {", " for (char c : s.toCharArray()) {", " System.err.print(c);", " }", " for (char i : s.toCharArray()) {", " System.err.print(i);", " }", " }", "}") .addOutputLines( "Test.java", "class T {", " void f(String s) {", " for (int i = 0; i < s.length(); i++) {", " char c = s.charAt(i);", " System.err.print(c);", " }", " for (char i : s.toCharArray()) {", " System.err.print(i);", " }", " }", "}") .doTest(); } }
1,849
30.896552
84
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EmptyIfStatementTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author alexeagle@google.com (Alex Eagle) */ @RunWith(JUnit4.class) public class EmptyIfStatementTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(EmptyIfStatement.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("EmptyIfStatementPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("EmptyIfStatementNegativeCases.java").doTest(); } }
1,301
29.27907
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SubstringOfZeroTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link SubstringOfZero}. */ @RunWith(JUnit4.class) public class SubstringOfZeroTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(SubstringOfZero.class, getClass()); @Test public void positiveJustVars() { helper .addInputLines( "Test.java", "class Test {", " void f() {", " String x = \"hello\";", " String y = x.substring(0);", " }", "}") .addOutputLines( "Test.java", "class Test {", " void f() {", " String x = \"hello\";", " String y = x;", " }", "}") .doTest(); } @Test public void positiveVarsWithMethods() { helper .addInputLines( "Test.java", "class Test {", " void f() {", " String x = \"HELLO\";", " String y = x.toLowerCase().substring(0);", " }", "}") .addOutputLines( "Test.java", "class Test {", " void f() {", " String x = \"HELLO\";", " String y = x.toLowerCase();", " }", "}") .doTest(); } @Test public void negativeJustVarsOneArg() { helper .addInputLines( "Test.java", "class Test {", " void f() {", " String x = \"hello\";", " String y = x.substring(1);", " }", "}") .expectUnchanged() .doTest(); } @Test public void negativeJustVarsTwoArg() { helper .addInputLines( "Test.java", "class Test {", " void f() {", " String x = \"hello\";", " String y = x.substring(1,3);", " }", "}") .expectUnchanged() .doTest(); } @Test public void negativeVarsWithMethodsOneArg() { helper .addInputLines( "Test.java", "class Test {", " void f() {", " String x = \"HELLO\";", " String y = x.toLowerCase().substring(1);", " }", "}") .expectUnchanged() .doTest(); } @Test public void negativeVarsWithMethodsTwoArg() { helper .addInputLines( "Test.java", "class Test {", " void f() {", " String x = \"HELLO\";", " String y = x.toLowerCase().substring(1,3);", " }", "}") .expectUnchanged() .doTest(); } @Test public void negativeVarsWithDifferentMethod() { helper .addInputLines( "Test.java", "class Test {", " void f() {", " String x = \"HELLO\";", " char y = x.charAt(0);", " }", "}") .expectUnchanged() .doTest(); } @Test public void positiveStringLiteral() { helper .addInputLines( "Test.java", "class Test {", " public static final int MY_CONSTANT = 0;", " void f() {", " String x = \"hello\".substring(MY_CONSTANT);", " }", "}") .addOutputLines( "Test.java", "class Test {", " public static final int MY_CONSTANT = 0;", " void f() {", " String x = \"hello\";", " }", "}") .doTest(); } }
4,451
25.035088
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AmbiguousMethodReferenceTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link AmbiguousMethodReference}Test */ @RunWith(JUnit4.class) public class AmbiguousMethodReferenceTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(AmbiguousMethodReference.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "A.java", // "public class A {", " interface B {}", " interface C {}", " interface D {}", "", " // BUG: Diagnostic contains: c(A, D)", " B c(D d) {", " return null;", " }", " static B c(A a, D d) {", " return null;", " }", "}") .doTest(); } @Test public void moreThan1PublicMethod() { testHelper .addSourceLines( "A.java", // "public class A {", " interface B {}", " interface C {}", " interface D {}", "", " // BUG: Diagnostic contains: c(A, D)", " public B c(D d) {", " return null;", " }", " public static B c(A a, D d) {", " return null;", " }", "}") .doTest(); } @Test public void suppressedAtClass() { testHelper .addSourceLines( "A.java", // "@SuppressWarnings(\"AmbiguousMethodReference\")", "public class A {", " interface B {}", " interface C {}", " interface D {}", "", " B c(D d) {", " return null;", " }", " static B c(A a, D d) {", " return null;", " }", "}") .doTest(); } @Test public void suppressedAtMethod() { testHelper .addSourceLines( "A.java", // "public class A {", " interface B {}", " interface C {}", " interface D {}", "", " @SuppressWarnings(\"AmbiguousMethodReference\")", " B c(D d) {", " return null;", " }", " // BUG: Diagnostic contains: c(D)", " static B c(A a, D d) {", " return null;", " }", "}") .doTest(); } @Test public void suppressedAtBothMethods() { testHelper .addSourceLines( "A.java", // "public class A {", " interface B {}", " interface C {}", " interface D {}", "", " @SuppressWarnings(\"AmbiguousMethodReference\")", " B c(D d) {", " return null;", " }", " @SuppressWarnings(\"AmbiguousMethodReference\")", " static B c(A a, D d) {", " return null;", " }", "}") .doTest(); } @Test public void negativeDifferentNames() { testHelper .addSourceLines( "A.java", // "public class A {", " interface B {}", " interface C {}", " interface D {}", "", " B c(D d) {", " return null;", " }", " static B d(A a, D d) {", " return null;", " }", "}") .doTest(); } @Test public void negativePrivateMethods() { testHelper .addSourceLines( "A.java", // "public class A {", " interface B {}", " interface C {}", " interface D {}", "", " private B c(D d) {", " return null;", " }", " private static B c(A a, D d) {", " return null;", " }", "}") .doTest(); } @Test public void only1PublicMethod() { testHelper .addSourceLines( "A.java", // "public class A {", " interface B {}", " interface C {}", " interface D {}", "", " private B c(D d) {", " return null;", " }", " public static B c(A a, D d) {", " return null;", " }", "}") .doTest(); } @Test public void negativeStatic() { testHelper .addSourceLines( "B.java", // "public interface B<T> {", " static <T> B<T> f() { return null; }", "}") .addSourceLines( "A.java", // "public abstract class A<T> implements B<T> {", " public static <T> A<T> f() { return null; }", "}") .doTest(); } }
5,659
25.448598
84
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StaticAssignmentOfThrowableTest.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link StaticAssignmentOfThrowable}. */ @RunWith(JUnit4.class) public final class StaticAssignmentOfThrowableTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(StaticAssignmentOfThrowable.class, getClass()); @Test public void staticWithThrowableInMethod_error() { helper .addSourceLines( "Test.java", "class Test {", " static Throwable foo;", " public Test(int foo) {", " }", " ", " public void foo() { ", " // BUG: Diagnostic contains: [StaticAssignmentOfThrowable]", " foo = new NullPointerException(\"assign in method\");", " }", "}") .doTest(); } @Test public void staticWithThrowableDuringInitialization_error() { helper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: [StaticAssignmentOfThrowable]", " static Throwable foo = new NullPointerException(\"message\");", " public Test(int foo) {", " }", "}") .doTest(); } @Test public void staticWithThrowableDuringInitializationFromMethod_error() { helper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: [StaticAssignmentOfThrowable]", " static Throwable foo = bar(); ", " public Test(int foo) {", " } ", " ", " private static Throwable bar() { ", " return new NullPointerException(\"initialized with return value\"); ", " } ", "}") .doTest(); } @Test public void dynamicWithThrowableDuringInitializationFromMethod_noMatch() { helper .addSourceLines( "Test.java", "class Test {", " Throwable foo = bar(); ", " public Test(int foo) {", " } ", " ", " private static Throwable bar() { ", " return new NullPointerException(\"initialized with return value\"); ", " } ", "}") .doTest(); } @Test public void staticWithThrowableDuringConstructor_noMatch() { // Handling this scenario delegated to StaticAssignmentInConstructor helper .addSourceLines( "Test.java", "class Test {", " static Throwable foo;", " public Test(int bar) {", " foo = new NullPointerException(Integer.toString(bar));", " }", "}") .doTest(); } @Test public void staticWithNonThrowableFromMethod_noMatch() { helper .addSourceLines( "Test.java", "class Test {", " static int foo;", " public Test(int foo) {", " }", " private void bar() { ", " this.foo = 5;", " } ", "}") .doTest(); } @Test public void staticWithNonThrowableFromDeclaration_noMatch() { helper .addSourceLines( "Test.java", "class Test {", " private static final String RULE = \"allow this\";", " public Test(int foo) {", " }", "}") .doTest(); } @Test public void dynamic_noMatch() { helper .addSourceLines( "Test.java", "class Test {", " Throwable foo;", " public Test(int foo) {", " this.foo = new RuntimeException(\"odd but not an error here\");", " }", "}") .doTest(); } @Test public void staticWithThrowableInLambdaInMethod_error() { helper .addSourceLines( "Test.java", "class Test {", " static Throwable foo;", " public Test(int a) {", " } ", " void foo(int a) { ", " java.util.Arrays.asList().stream().map(x -> { ", " // BUG: Diagnostic contains: [StaticAssignmentOfThrowable]", " foo = new NullPointerException(\"assign\"); ", " return a; }) ", " .count();", " }", "}") .doTest(); } @Test public void staticWithThrowableInLambdaInLambdaInMethod_error() { helper .addSourceLines( "Test.java", "class Test {", " static Throwable foo;", " public Test(int a) {", " } ", " void bar(int a) { ", " java.util.Arrays.asList().stream().map(x -> { ", " java.util.Arrays.asList().stream().map(y -> { ", " // BUG: Diagnostic contains: [StaticAssignmentOfThrowable]", " foo = new NullPointerException(\"inner assign\"); return y;}", " ).count(); ", " // BUG: Diagnostic contains: [StaticAssignmentOfThrowable]", " foo = new NullPointerException(\"outer assign\"); ", " return a; }) ", " .count();", " }", "}") .doTest(); } }
6,093
28.726829
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SystemExitOutsideMainTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link SystemExitOutsideMain}. */ @RunWith(JUnit4.class) public class SystemExitOutsideMainTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(SystemExitOutsideMain.class, getClass()); @Test public void systemExitNotMain() { helper .addSourceLines( "Test.java", // "class Test {", " void f() {", " // BUG: Diagnostic contains: SystemExitOutsideMain", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitMainLookalikeWithoutParameters() { helper .addSourceLines( "Test.java", // "class Test {", " public static void main() {", " // BUG: Diagnostic contains: SystemExitOutsideMain", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitMainLookalikeWithTwoParameters() { helper .addSourceLines( "Test.java", // "class Test {", " public static void main(String[] args, int num) {", " // BUG: Diagnostic contains: SystemExitOutsideMain", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitMainLookalikeWithoutStatic() { helper .addSourceLines( "Test.java", // "class Test {", " public void main(String[] args) {", " // BUG: Diagnostic contains: SystemExitOutsideMain", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitMainLookalikeDifferentReturnType() { helper .addSourceLines( "Test.java", // "class Test {", " public static int main(String[] args) {", " // BUG: Diagnostic contains: SystemExitOutsideMain", " System.exit(0);", " return 0;", " }", "}") .doTest(); } @Test public void systemExitMainLookalikeDifferentVisibility() { helper .addSourceLines( "Test.java", // "class Test {", " private static void main(String[] args) {", " // BUG: Diagnostic contains: SystemExitOutsideMain", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitMainLookalikeDifferentArrayParameter() { helper .addSourceLines( "Test.java", // "class Test {", " private static void main(int[] args) {", " // BUG: Diagnostic contains: SystemExitOutsideMain", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitMainLookalikeStringParameter() { helper .addSourceLines( "Test.java", // "class Test {", " private static void main(String args) {", " // BUG: Diagnostic contains: SystemExitOutsideMain", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitInMethodMainNotInClass() { helper .addSourceLines( "Test.java", // "class Test {", " public static void foo() {", " // BUG: Diagnostic contains: SystemExitOutsideMain", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitInMethodMainInClassNegative() { helper .addSourceLines( "Test.java", // "class Test {", " public static void main(String[] args) {", " foo();", " }", " public static void foo() {", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitMainVarArgsParameterNegative() { helper .addSourceLines( "Test.java", // "class Test {", " public static void main(String... args) {", " System.exit(0);", " }", "}") .doTest(); } @Test public void systemExitMainNegative() { helper .addSourceLines( "Test.java", // "class Test {", " public static void main(String[] args) {", " System.exit(0);", " }", "}") .doTest(); } }
5,409
26.05
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NullablePrimitiveArrayTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link NullablePrimitiveArray}Test */ @RunWith(JUnit4.class) public class NullablePrimitiveArrayTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(NullablePrimitiveArray.class, getClass()); @Test public void typeAnnotation() { testHelper .addInputLines( "Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "abstract class Test {", " @Nullable abstract byte[] f();", " abstract @Nullable byte[] g();", " abstract void h(@Nullable byte[] x);", " abstract void i(@Nullable byte @Nullable [] x);", " abstract void j(@Nullable byte... x);", "}") .addOutputLines( "Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "abstract class Test {", " abstract byte @Nullable [] f();", " abstract byte @Nullable [] g();", " abstract void h(byte @Nullable [] x);", " abstract void i(byte @Nullable [] x);", " abstract void j(byte @Nullable... x);", "}") .doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH); } @Test public void negative() { testHelper .addInputLines( "Test.java", "import javax.annotation.Nullable;", "abstract class Test {", " @Nullable abstract Object[] f();", " abstract @Nullable Object[] g();", " abstract void h(@Nullable Object[] x);", "}") .expectUnchanged() .doTest(); } @Test public void declarationAnnotation() { testHelper .addInputLines( "Test.java", "import javax.annotation.Nullable;", "abstract class Test {", " @Nullable abstract byte[] f();", " abstract @Nullable byte[] g();", " abstract void h(@Nullable byte[] x);", "}") .expectUnchanged() .doTest(); } }
2,915
32.517241
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MultipleTopLevelClassesTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.truth.TruthJUnit.assume; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link MultipleTopLevelClasses}Test */ @RunWith(JUnit4.class) public class MultipleTopLevelClassesTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MultipleTopLevelClasses.class, getClass()); @Test public void twoClasses() { compilationHelper .addSourceLines( "a/A.java", "package a;", "// BUG: Diagnostic contains: one top-level class declaration, instead found: One, Two", "class One {}", "// BUG: Diagnostic contains:", "class Two {}") .doTest(); } @Test public void packageInfo() { compilationHelper .addSourceLines( "a/package-info.java", // "/** Documentation for our package */", "package a;") .doTest(); } @Test public void defaultPackage() { compilationHelper .addSourceLines( "a/A.java", // "// BUG: Diagnostic contains:", "class A {}", "// BUG: Diagnostic contains:", "class B {}") .doTest(); } @Test public void suppression() { compilationHelper .addSourceLines( "a/A.java", "package a;", "class One {}", "@SuppressWarnings(\"TopLevel\") class Other {}") .doTest(); } @Test public void emptyDeclaration() { compilationHelper .addSourceLines( "a/A.java", // "package a;", "class Test {};") .doTest(); } @Test public void semiInImportList() { assume().that(RuntimeVersion.isAtLeast21()).isFalse(); compilationHelper .addSourceLines( "a/A.java", "package a;", "// BUG: Diagnostic contains:", "// one top-level class declaration, instead found: Test, Extra", "import java.util.List;;", "// BUG: Diagnostic contains:", "import java.util.ArrayList;", "// BUG: Diagnostic contains:", "class Test {", " List<String> xs = new ArrayList<>();", "}", "// BUG: Diagnostic contains:", "class Extra {}") .doTest(); } }
3,154
27.423423
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/PreconditionsInvalidPlaceholderTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class PreconditionsInvalidPlaceholderTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(PreconditionsInvalidPlaceholder.class, getClass()); @Test public void positiveCase1() { compilationHelper.addSourceFile("PreconditionsInvalidPlaceholderPositiveCase1.java").doTest(); } @Test public void negativeCase1() { compilationHelper.addSourceFile("PreconditionsInvalidPlaceholderNegativeCase1.java").doTest(); } }
1,366
31.547619
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ErroneousThreadPoolConstructorCheckerTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link ErroneousThreadPoolConstructorChecker} bug pattern. */ @RunWith(JUnit4.class) public class ErroneousThreadPoolConstructorCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ErroneousThreadPoolConstructorChecker.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance( ErroneousThreadPoolConstructorChecker.class, getClass()); @Test public void positiveCases() { compilationHelper .addSourceFile("ErroneousThreadPoolConstructorCheckerPositiveCases.java") .doTest(); } @Test public void negativeCases() { compilationHelper .addSourceFile("ErroneousThreadPoolConstructorCheckerNegativeCases.java") .doTest(); } @Test public void erroneousThreadPoolConstructor_literalConstantsForPoolSize_refactorUsingFirstFix() { refactoringHelper .setFixChooser(FixChoosers.FIRST) .addInputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " public void createThreadPool() {", " new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .addOutputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " public void createThreadPool() {", " new ThreadPoolExecutor(10, 10, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .doTest(); } @Test public void erroneousThreadPoolConstructor_corePoolSizeZero_refactorUsingFirstFix() { refactoringHelper .setFixChooser(FixChoosers.FIRST) .addInputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " public void createThreadPool() {", " new ThreadPoolExecutor(0, 20, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .addOutputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " public void createThreadPool() {", " new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .doTest(); } @Test public void erroneousThreadPoolConstructor_literalConstantsForPoolSize_refactorUsingSecondFix() { refactoringHelper .setFixChooser(FixChoosers.SECOND) .addInputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " public void createThreadPool() {", " new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .addOutputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " public void createThreadPool() {", " new ThreadPoolExecutor(20, 20, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .doTest(); } @Test public void erroneousThreadPoolConstructor_staticConstantsForPoolSize_refactorUsingFirstFix() { refactoringHelper .setFixChooser(FixChoosers.FIRST) .addInputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " private static final int CORE_SIZE = 10;", " private static final int MAX_SIZE = 20;", " public void createThreadPool() {", " new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .addOutputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " private static final int CORE_SIZE = 10;", " private static final int MAX_SIZE = 20;", " public void createThreadPool() {", " new ThreadPoolExecutor(CORE_SIZE, CORE_SIZE, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .doTest(); } @Test public void erroneousThreadPoolConstructor_staticConstantsForPoolSize_refactorUsingSecondFix() { refactoringHelper .setFixChooser(FixChoosers.SECOND) .addInputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " private static final int CORE_SIZE = 10;", " private static final int MAX_SIZE = 20;", " public void createThreadPool() {", " new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .addOutputLines( "Test.java", "import java.util.concurrent.LinkedBlockingQueue;", "import java.util.concurrent.ThreadPoolExecutor;", "import java.util.concurrent.TimeUnit;", "", "class Test {", " private static final int CORE_SIZE = 10;", " private static final int MAX_SIZE = 20;", " public void createThreadPool() {", " new ThreadPoolExecutor(MAX_SIZE, MAX_SIZE, 60, TimeUnit.SECONDS,", " new LinkedBlockingQueue<>());", " }", "}") .doTest(); } }
8,284
37.896714
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DepAnnTest.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.common.collect.ImmutableList; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DepAnnTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(DepAnn.class, getClass()); private static final ImmutableList<String> JAVACOPTS = ImmutableList.of("-Xlint:-dep-ann"); @Test public void positiveCase() { compilationHelper.setArgs(JAVACOPTS).addSourceFile("DepAnnPositiveCases.java").doTest(); } @Test public void negativeCase1() { compilationHelper.setArgs(JAVACOPTS).addSourceFile("DepAnnNegativeCase1.java").doTest(); } @Test public void negativeCase2() { compilationHelper.setArgs(JAVACOPTS).addSourceFile("DepAnnNegativeCase2.java").doTest(); } @Test public void disableable() { compilationHelper .setArgs(ImmutableList.of("-Xlint:-dep-ann", "-Xep:DepAnn:OFF")) .expectNoDiagnostics() .addSourceFile("DepAnnPositiveCases.java") .doTest(); } }
1,767
30.017544
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ConstantOverflowTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ConstantOverflow}Test */ @RunWith(JUnit4.class) public class ConstantOverflowTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(ConstantOverflow.class, getClass()); @Test public void positiveExpressions() { testHelper .addSourceLines( "Test.java", "class Test {", " static final int C = 1;", " void g(int x) {}", " void f() {", " // BUG: Diagnostic contains: if (1000L * 1000 * 1000 * 10 * 1L == 0);", " if (1000 * 1000 * 1000 * 10 * 1L == 0);", " // BUG: Diagnostic contains: int x = (int) (1000L * 1000 * 1000 * 10 * 1L);", " int x = (int) (1000 * 1000 * 1000 * 10 * 1L);", " // BUG: Diagnostic contains: long y = 1000L * 1000 * 1000 * 10;", " int y = 1000 * 1000 * 1000 * 10;", " // BUG: Diagnostic contains:", " g(C * 1000 * 1000 * 1000 * 10);", " }", "}") .doTest(); } @Test public void positiveFields() { testHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: Long a = 1000L * 1000 * 1000 * 10 * 1L;", " Long a = 1000 * 1000 * 1000 * 10 * 1L;", " // BUG: Diagnostic contains:", " int b = (int) 24L * 60 * 60 * 1000 * 1000;", " long c = (long) 24L * 60 * 60 * 1000 * 1000;", " // BUG: Diagnostic contains: long d = 24L * 60 * 60 * 1000 * 1000;", " long d = 24 * 60 * 60 * 1000 * 1000;", "}") .doTest(); } @Test public void negativeFloat() { testHelper .addSourceLines( "Test.java", // "class Test {", " public static final int a = (int) (10 / 0.5);", "}") .doTest(); } @Test public void negativeCharCast() { testHelper .addSourceLines( "Test.java", "class Test {", " public static final char a = (char) Integer.MAX_VALUE;", " public static final char b = (char) -1;", " public static final char c = (char) 1;", "}") .doTest(); } @Test public void negativeCast() { testHelper .addSourceLines( "Test.java", "class Test {", " public static final byte a = (byte) 1;", " private static final byte b = (byte) 0b1000_0000;", " private static final byte c = (byte) 0x80;", " private static final byte d = (byte) 0xfff;", " private static final byte e = (byte) -1;", "}") .doTest(); } @Test public void negative() { testHelper .addSourceLines( "Test.java", // "class Test {", " long microDay = 24L * 60 * 60 * 1000 * 1000;", "}") .doTest(); } @Test public void bitAnd() { testHelper .addSourceLines( "Test.java", "class Test {", " private static final int MASK = (1 << 31);", " void f(int[] xs) {", " for (final int x : xs) {", " final int y = (x & (MASK - 1));", " }", " }", "}") .doTest(); } @Test public void longOverflow() { BugCheckerRefactoringTestHelper.newInstance(ConstantOverflow.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;", " void f() {", " System.err.println(2 * GOLDEN_GAMMA);", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;", " void f() {", " System.err.println(2 * GOLDEN_GAMMA);", " }", "}") .doTest(); } @Test public void onlyFixIntegers() { BugCheckerRefactoringTestHelper.newInstance(ConstantOverflow.class, getClass()) .addInputLines("in/Test.java", "class Test {", " int a = 'a' + Integer.MAX_VALUE;", "}") .addOutputLines("out/Test.java", "class Test {", " int a = 'a' + Integer.MAX_VALUE;", "}") .doTest(); } @Test public void varType() { BugCheckerRefactoringTestHelper.newInstance(ConstantOverflow.class, getClass()) .addInputLines( "Test.java", // "class Test {", " void f() {", " var x = 1 + Integer.MAX_VALUE;", " }", "}") .addOutputLines( "Test.java", // "class Test {", " void f() {", " var x = 1L + Integer.MAX_VALUE;", " }", "}") .doTest(); } }
5,850
30.28877
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/PrimitiveAtomicReferenceTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link PrimitiveAtomicReference}. */ @RunWith(JUnit4.class) public final class PrimitiveAtomicReferenceTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(PrimitiveAtomicReference.class, getClass()); @Test public void positive() { helper .addSourceLines( "Test.java", "import java.util.concurrent.atomic.AtomicReference;", "class Test {", " private AtomicReference<Integer> ref = new AtomicReference<>();", " public boolean cas(int i) {", " // BUG: Diagnostic contains:", " return ref.compareAndSet(i, 10);", " }", "}") .doTest(); } @Test public void negativeNull() { helper .addSourceLines( "Test.java", "import java.util.concurrent.atomic.AtomicReference;", "class Test {", " private AtomicReference<Integer> ref = new AtomicReference<>();", " public boolean cas() {", " return ref.compareAndSet(null, 10);", " }", "}") .doTest(); } @Test public void negativeNotBoxedType() { helper .addSourceLines( "Test.java", "import java.util.concurrent.atomic.AtomicReference;", "class Test {", " private AtomicReference<String> ref = new AtomicReference<>();", " public boolean cas(String s) {", " return ref.compareAndSet(s, \"foo\");", " }", "}") .doTest(); } }
2,409
30.710526
84
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/WaitNotInLoopTest.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class WaitNotInLoopTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(WaitNotInLoop.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("WaitNotInLoopPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("WaitNotInLoopNegativeCases.java").doTest(); } }
1,293
29.093023
80
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BanJNDITest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link BanJNDI}Test */ @RunWith(JUnit4.class) public class BanJNDITest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(BanJNDI.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(BanJNDI.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("BanJNDIPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("BanJNDINegativeCases.java").doTest(); } @Test public void negativeCaseUnchanged() { refactoringHelper .addInput("BanJNDINegativeCases.java") .expectUnchanged() .setArgs("-XepCompilingTestOnlyCode") .doTest(); } }
1,661
30.358491
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TruthConstantAssertsTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link TruthConstantAsserts} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public final class TruthConstantAssertsTest { CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(TruthConstantAsserts.class, getClass()); } @Test public void positiveCase() { compilationHelper.addSourceFile("TruthConstantAssertsPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("TruthConstantAssertsNegativeCases.java").doTest(); } }
1,455
28.714286
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StaticQualifiedUsingExpressionTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class StaticQualifiedUsingExpressionTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(StaticQualifiedUsingExpression.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(StaticQualifiedUsingExpression.class, getClass()); @Test public void positiveCase1() { compilationHelper.addSourceFile("StaticQualifiedUsingExpressionPositiveCase1.java").doTest(); } @Test public void positiveCase2() { compilationHelper.addSourceFile("StaticQualifiedUsingExpressionPositiveCase2.java").doTest(); } @Test public void negativeCases() { compilationHelper.addSourceFile("StaticQualifiedUsingExpressionNegativeCases.java").doTest(); } @Test public void clash() { refactoringHelper .addInputLines( "a/Lib.java", // "package a;", "public class Lib {", " public static final int CONST = 0;", "}") .expectUnchanged() .addInputLines( "b/Lib.java", // "package b;", "public class Lib {", " public static final int CONST = 0;", "}") .expectUnchanged() .addInputLines( "in/Test.java", "import a.Lib;", "class Test {", " void test() {", " int x = Lib.CONST + new b.Lib().CONST;", " }", "}") .addOutputLines( "out/Test.java", "import a.Lib;", "class Test {", " void test() {", " new b.Lib();", " int x = Lib.CONST + b.Lib.CONST;", " }", "}") .doTest(); } @Test public void expr() { refactoringHelper .addInputLines( "I.java", // "interface I {", " int CONST = 42;", " I id();", "}") .expectUnchanged() .addInputLines( "in/Test.java", // "class Test {", " void f(I i) {", " System.err.println(((I) null).CONST);", " System.err.println(i.id().CONST);", " }", "}") .addOutputLines( "out/Test.java", // "class Test {", " void f(I i) {", " System.err.println(I.CONST);", " i.id();", " System.err.println(I.CONST);", " }", "}") .doTest(); } @Test public void superAccess() { refactoringHelper .addInputLines( "I.java", // "interface I {", " interface Builder {", " default void f() {}", " }", "}") .expectUnchanged() .addInputLines( "in/Test.java", // "interface J extends I {", " interface Builder extends I.Builder {", " default void f() {}", " default void aI() {", " I.Builder.super.f();", " }", " }", "}") .expectUnchanged() .doTest(); } @Test public void enumConstantAccessedViaInstance() { refactoringHelper .addInputLines( "Enum.java", // "enum Enum {", "A, B;", "}") .expectUnchanged() .addInputLines( "Test.java", // "class Test {", " Enum foo(Enum e) {", " return e.B;", " }", "}") .addOutputLines( "Test.java", // "class Test {", " Enum foo(Enum e) {", " return Enum.B;", " }", "}") .doTest(); } @Test public void qualified() { refactoringHelper .addInputLines( "C.java", "class C {", " static Object x;", " void f() {", " Object x = this.x;", " }", " void g() {", " Object y = this.x;", " }", "}") .addOutputLines( "C.java", "class C {", " static Object x;", " void f() {", " Object x = C.x;", " }", " void g() {", " Object y = x;", " }", "}") .doTest(); } }
5,438
26.609137
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InexactVarargsConditionalTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link InexactVarargsConditional}Test */ @RunWith(JUnit4.class) public class InexactVarargsConditionalTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InexactVarargsConditional.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import java.util.Arrays;", "class Test {", " public static void main(String[] args) {", " Object[] a = {1, 2};", " Object b = \"hello\";", " for (boolean flag : new boolean[]{true, false}) {", " // BUG: Diagnostic contains: 'f(0, flag ? a : new Object[] {b});'?", " f(0, flag ? a : b);", " }", " }", " static void f(int x, Object... xs) {", " System.err.println(Arrays.deepToString(xs));", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.Arrays;", "class Test {", " public static void main(String[] args) {", " Object[] a = {1, 2};", " Object b = \"hello\";", " f(0, a);", " f(0, b);", " for (boolean flag : new boolean[]{true, false}) {", " f(0, 1, flag ? a : b);", " }", " }", " static void f(int x, Object... xs) {", " System.err.println(Arrays.deepToString(xs));", " }", "}") .doTest(); } }
2,486
31.723684
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CollectorShouldNotUseStateTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sulku@google.com (Marsela Sulku) */ @RunWith(JUnit4.class) public class CollectorShouldNotUseStateTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(CollectorShouldNotUseState.class, getClass()); @Test public void positiveCases() { compilationHelper.addSourceFile("CollectorShouldNotUseStatePositiveCases.java").doTest(); } @Test public void negativeCases() { compilationHelper.addSourceFile("CollectorShouldNotUseStateNegativeCases.java").doTest(); } }
1,340
31.707317
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnusedLabelTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class UnusedLabelTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(UnusedLabel.class, getClass()); @Test public void positive() { helper .addSourceLines( "Test.java", "class Test {", " void test() {", " // BUG: Diagnostic contains:", " label: while(true) {}", " }", "}") .doTest(); } @Test public void usedInBreak_noFinding() { helper .addSourceLines( "Test.java", "class Test {", " void test() {", " label: while(true) {", " break label;", " }", " }", "}") .doTest(); } @Test public void usedInContinue_noFinding() { helper .addSourceLines( "Test.java", "class Test {", " void test() {", " label: while(true) {", " continue label;", " }", " }", "}") .doTest(); } }
1,932
25.479452
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LossyPrimitiveCompareTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author awturner@google.com (Andy Turner) */ @RunWith(JUnit4.class) public class LossyPrimitiveCompareTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(LossyPrimitiveCompare.class, getClass()); @Test public void doubleCompare() { helper .addSourceLines( "Test.java", "class Test {", " int[] results = {", " // BUG: Diagnostic contains: Long.compare(0L, 0L)", " Double.compare(0L, 0L),", " // BUG: Diagnostic contains: Long.compare(Long.valueOf(0L), 0L)", " Double.compare(Long.valueOf(0L), 0L),", "", " // Not lossy.", " Double.compare((byte) 0, (byte) 0),", " Double.compare((short) 0, (short) 0),", " Double.compare('0', '0'),", " Double.compare(0, 0),", " Double.compare(0.f, 0.f),", " Double.compare(0.0, 0.0),", " };", "}") .doTest(); } @Test public void floatCompare() { helper .addSourceLines( "Test.java", "class Test {", " int[] results = {", " // BUG: Diagnostic contains: Long.compare(0L, 0L)", " Float.compare(0L, 0L),", " // BUG: Diagnostic contains: Long.compare(Long.valueOf(0L), 0L)", " Float.compare(Long.valueOf(0L), 0L),", " // BUG: Diagnostic contains: Integer.compare(0, 0)", " Float.compare(0, 0),", " // BUG: Diagnostic contains: Integer.compare(0, Integer.valueOf(0))", " Float.compare(0, Integer.valueOf(0)),", "", " // Not lossy.", " Float.compare((byte) 0, (byte) 0),", " Float.compare((short) 0, (short) 0),", " Float.compare('0', '0'),", " Float.compare(0.f, 0.f),", " };", "}") .doTest(); } }
2,832
33.54878
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BoxedPrimitiveConstructorTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link BoxedPrimitiveConstructor}Test */ @RunWith(JUnit4.class) public class BoxedPrimitiveConstructorTest { CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(BoxedPrimitiveConstructor.class, getClass()); } @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "public class Test {", " {", " // BUG: Diagnostic contains: byte b = (byte) 0;", " byte b = new Byte((byte) 0);", " // BUG: Diagnostic contains: char c = (char) 0;", " char c = new Character((char) 0);", " // BUG: Diagnostic contains: double d = 0;", " double d = new Double(0);", " // BUG: Diagnostic contains: float f = 0;", " float f = new Float(0);", " // BUG: Diagnostic contains: int i = 0;", " int i = new Integer(0);", " // BUG: Diagnostic contains: long j = 0;", " long j = new Long(0);", " // BUG: Diagnostic contains: short s = (short) 0;", " short s = new Short((short) 0);", " Double dd = d;", " // BUG: Diagnostic contains: float f2 = dd.floatValue();", " float f2 = new Float(dd);", " // BUG: Diagnostic contains: float f3 = (float) d;", " float f3 = new Float(d);", " // BUG: Diagnostic contains: foo(Float.valueOf((float) d));", " foo(new Float(d));", " }", " public void foo(Float f) {}", "}") .doTest(); } @Test public void positiveStrings() { compilationHelper .addSourceLines( "Test.java", "public class Test {", " {", " // BUG: Diagnostic contains: byte b = Byte.valueOf(\"0\");", " byte b = new Byte(\"0\");", " // BUG: Diagnostic contains: double d = Double.valueOf(\"0\");", " double d = new Double(\"0\");", " // BUG: Diagnostic contains: float f = Float.valueOf(\"0\");", " float f = new Float(\"0\");", " // BUG: Diagnostic contains: int i = Integer.valueOf(\"0\");", " int i = new Integer(\"0\");", " // BUG: Diagnostic contains: long j = Long.valueOf(\"0\");", " long j = new Long(\"0\");", " // BUG: Diagnostic contains: short s = Short.valueOf(\"0\");", " short s = new Short(\"0\");", " }", "}") .doTest(); } @Test public void booleanConstant() { compilationHelper .addSourceLines( "Test.java", "public class Test {", " static final Boolean CONST = true;", " static final String CONST2 = null;", " {", " // BUG: Diagnostic contains: boolean a = true;", " boolean a = new Boolean(true);", " // BUG: Diagnostic contains: boolean b = false;", " boolean b = new Boolean(false);", " // BUG: Diagnostic contains: boolean c = Boolean.valueOf(CONST);", " boolean c = new Boolean(CONST);", " // BUG: Diagnostic contains: boolean e = true;", " boolean e = new Boolean(\"true\");", " // BUG: Diagnostic contains: boolean f = false;", " boolean f = new Boolean(\"nope\");", " // BUG: Diagnostic contains: boolean g = Boolean.valueOf(CONST2);", " boolean g = new Boolean(CONST2);", " // BUG: Diagnostic contains: System.err.println(Boolean.TRUE);", " System.err.println(new Boolean(\"true\"));", " // BUG: Diagnostic contains: System.err.println(Boolean.FALSE);", " System.err.println(new Boolean(\"false\"));", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "public class Test {", " {", " String s = new String((String) null);", " }", "}") .doTest(); } @Test public void autoboxing() { compilationHelper .addSourceLines( "Test.java", "public abstract class Test {", " abstract int g(Integer x);", " void f(int x) {", " // BUG: Diagnostic contains: int i = x;", " int i = new Integer(x);", " // BUG: Diagnostic contains: i = g(Integer.valueOf(x));", " i = g(new Integer(x));", " // BUG: Diagnostic contains: i = (short) 0;", " i = new Integer((short) 0);", " }", "}") .doTest(); } // Tests that `new Integer(x).memberSelect` isn't unboxed to x.memberSelect // TODO(cushon): we could provide a better fix for byteValue(), but hopefully no one does that? @Test public void methodCall() { compilationHelper .addSourceLines( "Test.java", "public abstract class Test {", " abstract int g(Integer x);", " void f(int x) {", " // BUG: Diagnostic contains: int i = Integer.valueOf(x).byteValue();", " int i = new Integer(x).byteValue();", " }", "}") .doTest(); } @Test public void stringValue() { compilationHelper .addSourceLines( "Test.java", "public abstract class Test {", " abstract int g(Integer x);", " void f(int x) {", " // BUG: Diagnostic contains: String s = String.valueOf(x);", " String s = new Integer(x).toString();", " }", "}") .doTest(); } @Test public void compareTo() { compilationHelper .addSourceLines( "Test.java", "public abstract class Test {", " abstract int g(Integer x);", " void f(int x, Integer y, double d, Double dd, Float f) {", " // BUG: Diagnostic contains: int c1 = Integer.compare(x, y);", " int c1 = new Integer(x).compareTo(y);", " // BUG: Diagnostic contains: int c2 = y.compareTo(Integer.valueOf(x));", " int c2 = y.compareTo(new Integer(x));", " // BUG: Diagnostic contains: int c3 = Float.compare((float) d, f);", " int c3 = new Float(d).compareTo(f);", " // BUG: Diagnostic contains: int c4 = Float.compare(dd.floatValue(), f);", " int c4 = new Float(dd).compareTo(f);", " }", "}") .doTest(); } @Test public void hashCodeRefactoring() { compilationHelper .addSourceLines( "Test.java", "public abstract class Test {", " abstract int g(Integer x);", " int f(int x, Integer y, long z, double d, Double dd) {", " // BUG: Diagnostic contains: int h = Integer.hashCode(x);", " int h = new Integer(x).hashCode();", " // BUG: Diagnostic contains: h = Float.hashCode((float) d);", " h = new Float(d).hashCode();", " // BUG: Diagnostic contains: h = Float.hashCode(dd.floatValue());", " h = new Float(dd).hashCode();", " // BUG: Diagnostic contains: return Long.hashCode(z);", " return new Long(z).hashCode();", " }", "}") .doTest(); } public static class Super {} public static class Inner extends Super {} @Test public void incompleteClasspath() { compilationHelper .addSourceLines( "Test.java", "import " + Inner.class.getCanonicalName() + ";", "class Test {", " void m() {", " new Inner();", " }", "}") .withClasspath(BoxedPrimitiveConstructorTest.class, Inner.class) .doTest(); } @Test public void autoboxWidening() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f(float f) {", " // BUG: Diagnostic contains: (double) f;", " Double d = new Double(f);", " // BUG: Diagnostic contains: (short) (byte) 0;", " Short s = new Short((byte) 0);", " }", "}") .doTest(); } @Test public void autoboxGenerics() { compilationHelper .addSourceLines( "Test.java", "class Test {", " <T> T f(Object o) {", " // BUG: Diagnostic contains: return (T) Integer.valueOf(o.hashCode());", " return (T) new Integer(o.hashCode());", " }", "}") .doTest(); } }
9,917
34.421429
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NonCanonicalTypeTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link NonCanonicalType}. */ @RunWith(JUnit4.class) public final class NonCanonicalTypeTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(NonCanonicalType.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "class Test {", " void test() {", " // BUG: Diagnostic contains: `Map.Entry` was referred to by the" + " non-canonical name `ImmutableMap.Entry`", " ImmutableMap.Entry<?, ?> entry = null;", " }", "}") .doTest(); } @Test public void differingOnlyByPackageName() { compilationHelper .addSourceLines( "foo/A.java", // "package foo;", "public class A {", " public static class B {}", "}") .addSourceLines( "bar/A.java", // "package bar;", "public class A extends foo.A {}") .addSourceLines( "D.java", // "package bar;", "import bar.A;", "public interface D {", " // BUG: Diagnostic contains: The type `foo.A.B` was referred to by the" + " non-canonical name `bar.A.B`", " A.B test();", "}") .doTest(); } @Test public void notVisibleFromUsageSite() { compilationHelper .addSourceLines( "foo/A.java", // "package foo;", "class A {", " public static class C {}", "}") .addSourceLines( "foo/B.java", // "package foo;", "public class B extends A {}") .addSourceLines( "D.java", // "package bar;", "import foo.B;", "public interface D {", " B.C test();", "}") .doTest(); } @Test public void positiveWithGenerics() { compilationHelper .addSourceLines( "A.java", // "class A<T> {", " class B {}", "}") .addSourceLines( "AString.java", // "class AString extends A<String> {}") .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: Did you mean 'A.B test() {'", " AString.B test() {", " return null;", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.Map;", "class Test {", " void test() {", " Map.Entry<?, ?> entry = null;", " }", "}") .doTest(); } @Test public void qualifiedName_inLambdaParameter_cantFix() { compilationHelper .addSourceLines( "Test.java", "import java.util.function.Function;", "class Test {", " interface Rec extends Function<Rec, Rec> {}\n", " void run() {", " Rec f = x -> x.apply(x);", " }", "}") .doTest(); } @Test public void qualifiedName_ambiguous() { compilationHelper .addSourceLines( "Test.java", "interface A {", " interface N {}", "}", "interface B extends A {}", "class C implements D {}", "interface E extends D {", " interface N extends D.N {}", "}", "interface D {", " interface N {}", "}", "class Test extends C implements E {", " // BUG: Diagnostic contains: A.N", " private B.N f() {", " return null;", " }", "}") .doTest(); } @Test public void typeParameter_noFinding() { compilationHelper .addSourceLines( "Test.java", "class Test<E extends Enum<E>> {", " E test(Class<E> clazz, String name) {", " return E.valueOf(clazz, name);", " }", "}") .doTest(); } @Test public void arrays() { compilationHelper .addSourceLines( "Test.java", "class Test {", " int len(String[] xs) {", " return xs.length;", " }", "}") .doTest(); } @Test public void clazz_noFinding() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void test () {", " var c = boolean.class;", " }", "}") .doTest(); } @Test public void method_noFinding() { compilationHelper .addSourceLines("Super.java", "class Super {", " static void f() {}", "}") .addSourceLines( "Test.java", "class Test extends Super {", " void test() {", " Test.f();", " }", "}") .doTest(); } // TODO(cushon): the fix for this should be Super<?>.Inner, not Super.Inner @Test public void innerArray() { compilationHelper .addSourceLines( "Super.java", // "class Super<T> {", " class Inner {}", "}") .addSourceLines( "Super.java", // "class Sub<T> extends Super<T> {", "}") .addSourceLines( "Test.java", // "class Test {", " // BUG: Diagnostic contains: `Super.Inner` was referred to by the non-canonical name" + " `Sub.Inner`", " Sub<?>.Inner[] x;", "}") .doTest(); } // see https://github.com/google/error-prone/issues/3639 @Test public void moduleInfo() { compilationHelper .addSourceLines( "module-info.java", // "module testmodule {", " requires java.base;", "}") .doTest(); } }
7,037
26.27907
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LongDoubleConversionTest.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link LongDoubleConversion}Test */ @RunWith(JUnit4.class) public class LongDoubleConversionTest { private final CompilationTestHelper compilationTestHelper = CompilationTestHelper.newInstance(LongDoubleConversion.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringTestHelper = BugCheckerRefactoringTestHelper.newInstance(LongDoubleConversion.class, getClass()); @Test public void losesPrecision() { compilationTestHelper .addSourceLines( "Test.java", // "class Test {", " void method(Long l) {}", " void method(double l) {}", " {", " // BUG: Diagnostic contains:", " method(9223372036854775806L);", " }", "}") .doTest(); } @Test public void doesNotActuallyLosePrecision_noFinding() { compilationTestHelper .addSourceLines( "Test.java", // "class Test {", " void method(Long l) {}", " void method(double l) {}", " {", " method(0L);", " }", "}") .doTest(); } @Test public void explicitlyCastToDouble_noFinding() { compilationTestHelper .addSourceLines( "Test.java", // "class Test {", " void method(double l) {}", " {", " method((double) 0L);", " }", "}") .doTest(); } @Test public void refactors_simpleArgument() { refactoringTestHelper .addInputLines( "Test.java", // "class Test {", " void method(Long l) {}", " void method(double l) {}", " {", " method(9223372036854775806L);", " }", "}") .addOutputLines( "Test.java", // "class Test {", " void method(Long l) {}", " void method(double l) {}", " {", " method((double) 9223372036854775806L);", " }", "}") .doTest(); } @Test public void refactors_complexArgument() { refactoringTestHelper .addInputLines( "Test.java", // "class Test {", " void method(Long l) {}", " void method(double l) {}", " {", " method(9223372036854775805L + 1L);", " }", "}") .addOutputLines( "Test.java", // "class Test {", " void method(Long l) {}", " void method(double l) {}", " {", " method((double) (9223372036854775805L + 1L));", " }", "}") .doTest(); } }
3,666
27.648438
90
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RandomModIntegerTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link RandomModInteger}Test */ @RunWith(JUnit4.class) public class RandomModIntegerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(RandomModInteger.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import java.util.Random;", "class Test {", " public static void main(String[] args) {", " Random r = new Random();", " // BUG: Diagnostic contains:", " System.err.println(r.nextInt() % 100);", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.Random;", "class Test {", " public static void main(String[] args) {", " Random r = new Random();", " System.err.println(r.nextInt(100));", " }", "}") .doTest(); } }
1,863
29.064516
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InsecureCipherModeTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author avenet@google.com (Arnaud J. Venet) */ @RunWith(JUnit4.class) public class InsecureCipherModeTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InsecureCipherMode.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("InsecureCipherModePositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("InsecureCipherModeNegativeCases.java").doTest(); } }
1,310
30.214286
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/VarifierTest.java
/* * Copyright 2022 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link Varifier}. */ @RunWith(JUnit4.class) public final class VarifierTest { private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(Varifier.class, getClass()); @Test public void cast() { refactoringHelper .addInputLines( "Test.java", "class Test {", " public void t(Object o) {", " Test t = (Test) o;", " }", "}") .addOutputLines( "Test.java", "class Test {", " public void t(Object o) {", " var t = (Test) o;", " }", "}") .doTest(); } @Test public void constructor() { refactoringHelper .addInputLines( "Test.java", "class Test {", " public void t() {", " Test t = new Test();", " }", "}") .addOutputLines( "Test.java", "class Test {", " public void t() {", " var t = new Test();", " }", "}") .doTest(); } @Test public void constructor_usingDiamond() { refactoringHelper .addInputLines( "Test.java", "import java.util.ArrayList;", "class Test {", " public void t() {", " ArrayList<Integer> xs = new ArrayList<>();", " }", "}") .expectUnchanged() .doTest(); } @Test public void constructor_usingExplicitType() { refactoringHelper .addInputLines( "Test.java", "import java.util.ArrayList;", "class Test {", " public void t() {", " ArrayList<Integer> xs = new ArrayList<Integer>();", " }", "}") .addOutputLines( "Test.java", "import java.util.ArrayList;", "class Test {", " public void t() {", " var xs = new ArrayList<Integer>();", " }", "}") .doTest(); } @Test public void alreadyVar() { refactoringHelper .addInputLines( "Test.java", "class Test {", " public void t() {", " var t = new Test();", " }", "}") .expectUnchanged() .doTest(); } @Test public void fromInstanceMethod() { refactoringHelper .addInputLines( "Test.java", "abstract class Test {", " public void t() {", " Test t = t2();", " }", " public abstract Test t2();", "}") .expectUnchanged() .doTest(); } @Test public void builder() { refactoringHelper .addInputLines( "Test.java", "import com.google.protobuf.Duration;", "abstract class Test {", " public void t() {", " Duration duration = Duration.newBuilder().setSeconds(4).build();", " }", "}") .addOutputLines( "Test.java", "import com.google.protobuf.Duration;", "abstract class Test {", " public void t() {", " var duration = Duration.newBuilder().setSeconds(4).build();", " }", "}") .doTest(); } @Test public void fromFactoryMethod() { refactoringHelper .addInputLines( "Test.java", "import java.time.Instant;", "class Test {", " public void t() {", " Instant now = Instant.ofEpochMilli(1);", " }", "}") .addOutputLines( "Test.java", "import java.time.Instant;", "class Test {", " public void t() {", " var now = Instant.ofEpochMilli(1);", " }", "}") .doTest(); } }
4,857
25.988889
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TryFailRefactoringTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ExpectedExceptionRefactoring}Test */ @RunWith(JUnit4.class) public class TryFailRefactoringTest { private final CompilationTestHelper compilationTestHelper = CompilationTestHelper.newInstance(TryFailRefactoring.class, getClass()); private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(TryFailRefactoring.class, getClass()); @Test public void catchBlock() { testHelper .addInputLines( "in/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.fail;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void f(String message) throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " try {", " Files.readAllBytes(p);", " Files.readAllBytes(p);", " fail(message);", " } catch (IOException e) {", " assertThat(e).hasMessageThat().contains(\"NOSUCH\");", " }", " }", " @Test", " public void g() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " try {", " Files.readAllBytes(p);", " fail(\"expected exception not thrown\");", " } catch (IOException e) {", " assertThat(e).hasMessageThat().contains(\"NOSUCH\");", " }", " }", "}") .addOutputLines( "out/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.assertThrows;", "import static org.junit.Assert.fail;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void f(String message) throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " IOException e = assertThrows(message, IOException.class, () -> {", " Files.readAllBytes(p);", " Files.readAllBytes(p);", " });", " assertThat(e).hasMessageThat().contains(\"NOSUCH\");", " }", " @Test", " public void g() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " IOException e = assertThrows(IOException.class, () -> Files.readAllBytes(p));", " assertThat(e).hasMessageThat().contains(\"NOSUCH\");", " }", "}") .doTest(); } @Test public void emptyCatch() { testHelper .addInputLines( "in/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.fail;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void test() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " try {", " Files.readAllBytes(p);", " fail();", " } catch (IOException e) {", " }", " }", "}") .addOutputLines( "out/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.assertThrows;", "import static org.junit.Assert.fail;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void test() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " assertThrows(IOException.class, () -> Files.readAllBytes(p));", " }", "}") .doTest(); } @Test public void tryWithResources() { testHelper .addInputLines( "in/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.fail;", "import com.google.common.io.CharSource;", "import java.io.BufferedReader;", "import java.io.IOException;", "import java.io.PushbackReader;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void f(String message, CharSource cs) throws IOException {", " try (BufferedReader buf = cs.openBufferedStream();", " PushbackReader pbr = new PushbackReader(buf)) {", " pbr.read();", " fail(message);", " } catch (IOException e) {", " assertThat(e).hasMessageThat().contains(\"NOSUCH\");", " }", " }", "}") .addOutputLines( "out/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.assertThrows;", "import static org.junit.Assert.fail;", "import com.google.common.io.CharSource;", "import java.io.BufferedReader;", "import java.io.IOException;", "import java.io.PushbackReader;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void f(String message, CharSource cs) throws IOException {", " try (BufferedReader buf = cs.openBufferedStream();", " PushbackReader pbr = new PushbackReader(buf)) {", " IOException e = assertThrows(message, IOException.class, () -> pbr.read());", " assertThat(e).hasMessageThat().contains(\"NOSUCH\");", " }", " }", "}") .doTest(); } @Test public void negative() { CompilationTestHelper.newInstance(TryFailRefactoring.class, getClass()) .addSourceLines( "ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.fail;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void noFail() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " try {", " Files.readAllBytes(p);", " } catch (IOException e) {", " }", " }", " @Test", " public void unionCatch() throws Exception {", " try {", " ((Class<?>) null).newInstance();", " fail();", " } catch (IllegalAccessException | InstantiationException e) {", " }", " }", " @Test", " public void multiCatch() throws Exception {", " try {", " ((Class<?>) null).newInstance();", " fail();", " } catch (IllegalAccessException e) {", " } catch (InstantiationException e) {", " }", " }", " @Test", " public void finallyBlock() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " try {", " Files.readAllBytes(p);", " } catch (IOException e) {", " } finally {}", " }", " public void nonTestMethod() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " try {", " Files.readAllBytes(p);", " fail();", " } catch (IOException e) {", " assertThat(e).hasMessageThat().contains(\"NOSUCH\");", " }", " }", "}") .doTest(); } @Test public void tryInStaticInitializer() { compilationTestHelper .addSourceLines( "Test.java", "class Test {", " static {", " try {", " int a;", " } catch (Exception e) {", " }", " }", "}") .doTest(); } }
9,587
36.748031
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NonFinalCompileTimeConstantTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link NonFinalCompileTimeConstant}Test */ @RunWith(JUnit4.class) public class NonFinalCompileTimeConstantTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(NonFinalCompileTimeConstant.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.CompileTimeConstant;", "public class Test {", " // BUG: Diagnostic contains:", " public void f(@CompileTimeConstant Object x) {", " x = null;", " }", "}") .doTest(); } @Test public void positiveTwoParams() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.CompileTimeConstant;", "public class Test {", " // BUG: Diagnostic contains:", " public void f(@CompileTimeConstant Object x, @CompileTimeConstant Object y) {", " x = y = null;", " }", "}") .doTest(); } @Test public void positiveOneOfTwoParams() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.CompileTimeConstant;", "public class Test {", " public void f(", " @CompileTimeConstant Object x,", " // BUG: Diagnostic contains:", " @CompileTimeConstant Object y) {", " y = null;", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.CompileTimeConstant;", "public class Test {", " public void f(final @CompileTimeConstant Object x) {}", "}") .doTest(); } @Test public void negativeEffectivelyFinal() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.CompileTimeConstant;", "public class Test {", " public void f(@CompileTimeConstant Object x) {}", "}") .doTest(); } @Test public void negativeInterface() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.CompileTimeConstant;", "public interface Test {", " public void f(@CompileTimeConstant Object x);", "}") .doTest(); } }
3,459
29.350877
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OutlineNoneTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test for {@link OutlineNone} */ @RunWith(JUnit4.class) public final class OutlineNoneTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(OutlineNone.class, getClass()); @Test public void template() { compilationHelper .addSourceLines( "Test.java", "import com.google.gwt.safehtml.shared.SafeHtml;", "import com.google.gwt.safehtml.client.SafeHtmlTemplates.Template;", "interface Test {", " // BUG: Diagnostic contains: OutlineNone", " @Template(\".body {color: red;outline: 0px;}" + "<a href=http://outlinenone.com style=\\\"outline:none\\\">\")", " SafeHtml myElement();", " // BUG: Diagnostic contains: OutlineNone", " @Template(\".invisible {outline: none}\")", " SafeHtml invisible();", "}") .doTest(); } @Test public void templateMutliline() { compilationHelper .addSourceLines( "Test.java", "import com.google.gwt.safehtml.shared.SafeHtml;", "import com.google.gwt.safehtml.client.SafeHtmlTemplates.Template;", "interface Test {", " // BUG: Diagnostic contains: OutlineNone", " @Template(\".body {color: red;}\\n\"", " + \"<a href=http://outlinenone.com style=\\\"outline:none\\\">\")", " SafeHtml myElement();", "}") .doTest(); } @Test public void gwtSetProperty() { compilationHelper .addSourceLines( "Test.java", "import com.google.gwt.dom.client.Style;", "class Test {", " private static final String OUTLINE = \"outline\";", " private static final double d = 0.0;", " void test(Style s) {", " // BUG: Diagnostic contains: OutlineNone", " s.setProperty(OUTLINE, \"none\");", " // BUG: Diagnostic contains: OutlineNone", " s.setPropertyPx(\"outline\", 0);", " // BUG: Diagnostic contains: OutlineNone", " s.setProperty(OUTLINE, d, Style.Unit.PX);", " s.setPropertyPx(OUTLINE, 1);", // No bug " }", "}") .doTest(); } @Test public void gwtSetProperty_numberTypes() { compilationHelper .addSourceLines( "Test.java", "import static com.google.gwt.dom.client.Style.Unit.PX;", "import com.google.gwt.dom.client.Style;", "class Test {", " private static final String OUTLINE = \"outline\";", " private static final int ZEROI = 0;", " private static final long ZEROL = 0L;", " private static final short ZEROS = 0;", " private static final double ZEROD = 0.0d;", " private static final float ZEROF = 0.0f;", " private static final double NEG_ZERO = -0.0;", " void test(Style s) {", // setProperty(String, double, Unit) " // BUG: Diagnostic contains: OutlineNone", " s.setProperty(OUTLINE, ZEROI, PX);", " // BUG: Diagnostic contains: OutlineNone", " s.setProperty(OUTLINE, ZEROL, PX);", " // BUG: Diagnostic contains: OutlineNone", " s.setProperty(OUTLINE, ZEROS, PX);", " // BUG: Diagnostic contains: OutlineNone", " s.setProperty(OUTLINE, ZEROD, PX);", " // BUG: Diagnostic contains: OutlineNone", " s.setProperty(OUTLINE, ZEROF, PX);", " // BUG: Diagnostic contains: OutlineNone", " s.setProperty(OUTLINE, NEG_ZERO, PX);", // setProperty(String, int) " // BUG: Diagnostic contains: OutlineNone", " s.setPropertyPx(OUTLINE, ZEROI);", " // BUG: Diagnostic contains: OutlineNone", " s.setPropertyPx(OUTLINE, ZEROS);", // non-zero, no bugs " s.setProperty(OUTLINE, 0.00001d, PX);", " s.setProperty(OUTLINE, 0.00001f, PX);", " }", "}") .doTest(); } }
5,069
38
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ComparisonOutOfRangeTest.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author Bill Pugh (bill.pugh@gmail.com) */ @RunWith(JUnit4.class) public class ComparisonOutOfRangeTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ComparisonOutOfRange.class, getClass()); @Test public void positiveCases() { compilationHelper.addSourceFile("ComparisonOutOfRangePositiveCases.java").doTest(); } @Test public void negativeCases() { compilationHelper.addSourceFile("ComparisonOutOfRangeNegativeCases.java").doTest(); } }
1,317
29.651163
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DefaultPackageTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link DefaultPackage} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class DefaultPackageTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(DefaultPackage.class, getClass()); @Test public void positiveCases() { compilationHelper .addSourceLines( "Test.java", // "// BUG: Diagnostic contains: DefaultPackage", "class Test {", "}") .doTest(); } @Test public void negativeCases_classWithGenerated() { compilationHelper .addSourceLines( "Test.java", // "import javax.annotation.processing.Generated;", "@Generated(\"generator\")", "class Test {", "}") .doTest(); } @Test public void negativeCases_classWithWarningSuppressed() { compilationHelper .addSourceLines( "in/Test.java", // "@SuppressWarnings(\"DefaultPackage\")", "class Test {", "}") .doTest(); } @Test public void negativeCases_classWithPackage() { compilationHelper .addSourceLines( "in/Test.java", // "package in;", "class Test {", "}") .doTest(); } // see b/2276473 @Test public void trailingComma() { compilationHelper .addSourceLines( "T.java", // "package a;", "class T {};") .doTest(); } @Test public void moduleInfo() { compilationHelper .addSourceLines( "module-info.java", // "module testmodule {", "}") .doTest(); } }
2,550
24.257426
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InconsistentHashCodeTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link InconsistentHashCode} bugpattern. * * @author ghm@google.com (Graeme Morgan) */ @RunWith(JUnit4.class) public final class InconsistentHashCodeTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(InconsistentHashCode.class, getClass()); @Test public void negative() { helper .addSourceLines( "Test.java", "class Test {", " private int a;", " private int b;", " @Override public boolean equals(Object o) {", " Test that = (Test) o;", " return a == that.a && b == that.b;", " }", " @Override public int hashCode() {", " return a + 31 * b;", " }", "}") .doTest(); } @Test public void positive() { helper .addSourceLines( "Test.java", "class Test {", " private int foo;", " private int bar;", " @Override public boolean equals(Object o) {", " Test that = (Test) o;", " return foo == that.foo;", " }", " // BUG: Diagnostic contains: bar", " @Override public int hashCode() {", " return foo + 31 * bar;", " }", "}") .doTest(); } @Test public void positiveViaGetter() { helper .addSourceLines( "Test.java", "class Test {", " private int foo;", " private int bar;", " @Override public boolean equals(Object o) {", " Test that = (Test) o;", " return foo == that.foo;", " }", " // BUG: Diagnostic contains: bar", " @Override public int hashCode() {", " return foo + 31 * getBar();", " }", " private int getBar() { return bar; }", "}") .doTest(); } @Test public void instanceEquality() { helper .addSourceLines( "Test.java", "class Test {", " private int a;", " private int b;", " @Override public boolean equals(Object o) {", " return this == o;", " }", " @Override public int hashCode() {", " return a + 31 * b;", " }", "}") .doTest(); } @Test public void memoizedHashCode() { helper .addSourceLines( "Test.java", "class Test {", " private int a;", " private int b;", " private int hashCode;", " @Override public boolean equals(Object o) {", " Test that = (Test) o;", " return this.a == that.a && this.b == that.b;", " }", " @Override public int hashCode() {", " return hashCode;", " }", "}") .doTest(); } @Test public void breakLabeledBlock() { helper .addSourceLines( "Test.java", "class Test {", " private int a;", " private int b;", " private int hashCode;", " public void accessesLocalWithLabeledBreak() {", " label: {", " switch (a) {", " case 0: break label;", " }", " }", " }", " @Override public boolean equals(Object o) {", " Test that = (Test) o;", " return this.a == that.a && this.b == that.b;", " }", " @Override public int hashCode() {", " return hashCode;", " }", "}") .doTest(); } }
4,628
28.113208
80
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OptionalMapUnusedValueTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link OptionalMapUnusedValue} bugpattern. */ @RunWith(JUnit4.class) public final class OptionalMapUnusedValueTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(OptionalMapUnusedValue.class, getClass()); @Test public void positive_methodReference() { helper .addInputLines( "Test.java", "import java.util.Optional;", "class Test {", " private Integer foo(Integer v) {return v;}", "", " public void bar(Optional<Integer> optional) {", " optional.map(this::foo);", " }", "}") .addOutputLines( "Test.java", "import java.util.Optional;", "class Test {", " private Integer foo(Integer v) {return v;}", "", " public void bar(Optional<Integer> optional) {", " optional.ifPresent(this::foo);", " }", "}") .doTest(); } @Test public void positive_statementLambda() { helper .addInputLines( "Test.java", "import java.util.Optional;", "class Test {", " private Integer foo(Integer v) {return v;}", "", " public void bar(Optional<Integer> optional) {", " optional.map(v -> foo(v));", " }", "}") .addOutputLines( "Test.java", "import java.util.Optional;", "class Test {", " private Integer foo(Integer v) {return v;}", "", " public void bar(Optional<Integer> optional) {", " optional.ifPresent(v -> foo(v));", " }", "}") .doTest(); } @Test public void negative_resultReturned() { helper .addInputLines( "Test.java", "import java.util.Optional;", "class Test {", " private Integer foo(Integer v) {return v;}", "", " public Optional<Integer> bar(Optional<Integer> optional) {", " return optional.map(this::foo);", " }", "}") .expectUnchanged() .doTest(); } @Test public void negative_resultAssigned() { helper .addInputLines( "Test.java", "import java.util.Optional;", "class Test {", " private Integer foo(Integer v) {return v;}", "", " public void bar(Optional<Integer> optional) {", " Optional<Integer> result = optional.map(this::foo);", " }", "}") .expectUnchanged() .doTest(); } @Test public void negative_resultMethodCall() { helper .addInputLines( "Test.java", "import java.util.Optional;", "class Test {", " private Integer foo(Integer v) {return v;}", "", " public void bar(Optional<Integer> optional) {", " optional.map(this::foo).orElse(42);", " }", "}") .expectUnchanged() .doTest(); } @Test public void negative_nonStatementLambda() { helper .addInputLines( "Test.java", "import java.util.Optional;", "class Test {", " public void bar(Optional<Integer> optional) {", " optional.map(v -> v + 1);", " }", "}") .expectUnchanged() .doTest(); } @Test public void negative_voidIncompatibleLambdaBlock() { helper .addInputLines( "Test.java", "import java.util.Optional;", "class Test {", " public void bar(Optional<Integer> optional) {", " optional.map(v -> {return 2;});", " }", "}") .expectUnchanged() .doTest(); } }
4,803
28.838509
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FloatingPointLiteralPrecisionTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import static org.junit.Assume.assumeTrue; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link FloatingPointLiteralPrecision}Test */ @RunWith(JUnit4.class) public class FloatingPointLiteralPrecisionTest { @Test public void positive() { BugCheckerRefactoringTestHelper.newInstance(FloatingPointLiteralPrecision.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " double d = 1.99999999999999999999999;", " float f = 1.99999999999999999999999f;", "}") .addOutputLines( "out/Test.java", // "class Test {", " double d = 2.0;", " float f = 2.0f;", "}") .doTest(TEXT_MATCH); } @Test public void negative() { CompilationTestHelper.newInstance(FloatingPointLiteralPrecision.class, getClass()) .addSourceLines( "Test.java", "class Test {", " double d2 = 1.0;", " double d3 = 1;", " double d4 = 1e6;", " double d5 = 1e-3;", " double d6 = 1d;", " double d7 = 1_000.0;", " double d8 = 0x1.0p63d;", " float f2 = 1.0f;", " float f3 = 1f;", " float f4 = 0.88f;", " float f5 = 1_000.0f;", " float f6 = 0x1.0p63f;", "}") .doTest(); } @Test public void replacementTooLong() { // In JDK versions before 19, String.valueOf(1e23) was 9.999999999999999E22, and the logic we're // testing here was introduced to avoid introducing strings like that in rewrites. JDK 19 fixes // https://bugs.openjdk.org/browse/JDK-4511638 (over 20 years after it was filed) so // we don't need the logic or its test there. String string1e23 = String.valueOf(1e23); assumeTrue(string1e23.length() > "1e23".length() * 3); String[] input = { "class Test {", // " // BUG: Diagnostic contains:", " double d = 1e23;", "}" }; // Don't provide a fix if the replacement is much longer than the current literal. BugCheckerRefactoringTestHelper.newInstance(FloatingPointLiteralPrecision.class, getClass()) .addInputLines("in/Test.java", input) .expectUnchanged() .doTest(TEXT_MATCH); // Make sure we're still emitting a warning. CompilationTestHelper.newInstance(FloatingPointLiteralPrecision.class, getClass()) .addSourceLines("Test.java", input) .doTest(); } }
3,435
33.36
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TryFailThrowableTest.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author adamwos@google.com (Adam Wos) */ @RunWith(JUnit4.class) public class TryFailThrowableTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(TryFailThrowable.class, getClass()); @Test public void positiveCases() { compilationHelper.addSourceFile("TryFailThrowablePositiveCases.java").doTest(); } @Test public void negativeCases() { compilationHelper.addSourceFile("TryFailThrowableNegativeCases.java").doTest(); } }
1,298
29.928571
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ASTHelpersSuggestionsTest.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ASTHelpersSuggestionsTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(ASTHelpersSuggestions.class, getClass()); @Test public void positive() { testHelper .addInputLines( "Test.java", "import com.sun.tools.javac.code.Symbol;", "class Test {", " void f(Symbol s) {", " s.isStatic();", " s.packge();", " s.members().anyMatch(x -> x.isStatic());", " }", "}") .addOutputLines( "Test.java", "import static com.google.errorprone.util.ASTHelpers.enclosingPackage;", "import static com.google.errorprone.util.ASTHelpers.isStatic;", "import static com.google.errorprone.util.ASTHelpers.scope;", "import com.sun.tools.javac.code.Symbol;", "class Test {", " void f(Symbol s) {", " isStatic(s);", " enclosingPackage(s);", " scope(s.members()).anyMatch(x -> isStatic(x));", " }", "}") .addModules( "jdk.compiler/com.sun.tools.javac.code", "jdk.compiler/com.sun.tools.javac.util") .doTest(); } @Test public void onSymbolSubtype() { testHelper .addInputLines( "Test.java", "import com.sun.tools.javac.code.Symbol.VarSymbol;", "class Test {", " void f(VarSymbol s) {", " s.isStatic();", " s.packge();", " s.members().anyMatch(x -> x.isStatic());", " }", "}") .addOutputLines( "Test.java", "import static com.google.errorprone.util.ASTHelpers.enclosingPackage;", "import static com.google.errorprone.util.ASTHelpers.isStatic;", "import static com.google.errorprone.util.ASTHelpers.scope;", "import com.sun.tools.javac.code.Symbol.VarSymbol;", "class Test {", " void f(VarSymbol s) {", " s.isStatic();", " enclosingPackage(s);", " scope(s.members()).anyMatch(x -> isStatic(x));", " }", "}") .addModules( "jdk.compiler/com.sun.tools.javac.code", "jdk.compiler/com.sun.tools.javac.util") .doTest(); } }
3,250
34.725275
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InterruptedExceptionSwallowedTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link InterruptedExceptionSwallowed}. */ @RunWith(JUnit4.class) public final class InterruptedExceptionSwallowedTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InterruptedExceptionSwallowed.class, getClass()) .addSourceLines( "Thrower.java", "class Thrower implements AutoCloseable {", " public void close() throws InterruptedException {}", "}"); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(InterruptedExceptionSwallowed.class, getClass()); @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " throw new Exception();", " } catch (Exception e) {", " throw new IllegalStateException(e);", " }", " }", "}") .doTest(); } @Test public void negativeNestedCatch() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " try {", " future.get();", " } catch (InterruptedException e) {}", " } catch (Exception e) {", " throw new IllegalStateException(e);", " }", " }", "}") .doTest(); } @Test public void positiveRethrown() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " try {", " future.get();", " } catch (InterruptedException e) {", " throw e;", " }", " // BUG: Diagnostic contains:", " } catch (Exception e) {", " throw new IllegalStateException(e);", " }", " }", "}") .doTest(); } @Test public void thrownByClose_throwsClauseTooBroad() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " // BUG: Diagnostic contains:", " void test() throws Exception {", " try (Thrower t = new Thrower()) {", " }", " }", "}") .doTest(); } @Test public void thrownByClose_caughtByOuterCatch() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test() {", " try {", " try (Thrower t = new Thrower()) {", " }", " // BUG: Diagnostic contains:", " } catch (Exception e) {", " }", " }", "}") .doTest(); } @Test public void negative_fieldNamedClose() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " class Mischief implements AutoCloseable {", " public int close = 1;", " public void close() {}", " }", " void test() {", " try (Mischief m = new Mischief()) {", " }", " }", "}") .doTest(); } @Test public void negative_rethrown() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test() throws InterruptedException, Exception {", " try {", " try (Thrower t = new Thrower()) {", " }", " } catch (Exception e) {", " throw e;", " }", " }", "}") .doTest(); } @Test public void thrownByClose_inherited() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " class ThrowingParent implements AutoCloseable {", " public void close() throws InterruptedException {}", " }", " class ThrowingChild extends ThrowingParent {}", " // BUG: Diagnostic contains:", " void test() throws Exception {", " try (ThrowingChild t = new ThrowingChild()) {", " }", " }", "}") .doTest(); } @Test public void thrownByClose_swallowedSilently() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test() {", " try (Thrower t = new Thrower()) {", " // BUG: Diagnostic contains:", " } catch (Exception e) {", " }", " }", "}") .doTest(); } @Test public void positiveThrowFromCatch() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.ExecutionException;", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " try {", " future.get();", " } catch (ExecutionException e) {", " if (e.getCause() instanceof IllegalStateException) {", " throw new InterruptedException();", " }", " } catch (InterruptedException e) {", " Thread.currentThread().interrupt();", " throw new IllegalStateException(e);", " }", " // BUG: Diagnostic contains:", " } catch (Exception e) {", " }", " }", "}") .doTest(); } @Test public void checkedViaInstanceof_noWarning() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " throw new Exception();", " } catch (Exception e) {", " if (e instanceof InterruptedException) {", " Thread.currentThread().interrupt();", " }", " throw new IllegalStateException(e);", " }", " }", "}") .doTest(); } @Test public void positiveSimpleCase() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " future.get();", " // BUG: Diagnostic contains:", " } catch (Exception e) {", " throw new IllegalStateException(e);", " }", " }", "}") .doTest(); } @Test public void positiveRefactoring() { refactoringHelper .addInputLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " future.get();", " } catch (Exception e) {", " throw new IllegalStateException(e);", " }", " }", "}") .addOutputLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " future.get();", " } catch (Exception e) {", " if (e instanceof InterruptedException) {", " Thread.currentThread().interrupt();", " }", " throw new IllegalStateException(e);", " }", " }", "}") .doTest(); } @Test public void positiveRefactoringEmptyCatch() { refactoringHelper .addInputLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " future.get();", " } catch (Exception e) {}", " }", "}") .addOutputLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " future.get();", " } catch (Exception e) {", " if (e instanceof InterruptedException) {", " Thread.currentThread().interrupt();", " }", " }", " }", "}") .doTest(); } @Test public void negativeExplicitlyListed() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.ExecutionException;", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " future.get();", " } catch (ExecutionException | InterruptedException e) {", " throw new IllegalStateException(e);", " }", " }", "}") .doTest(); } @Test public void suppression() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) {", " try {", " future.get();", " } catch (@SuppressWarnings(\"InterruptedExceptionSwallowed\") Exception e) {", " throw new IllegalStateException(e);", " }", " }", "}") .doTest(); } @Test public void hiddenInMethodThrows() { refactoringHelper .addInputLines( "Test.java", "import java.util.concurrent.ExecutionException;", "import java.util.concurrent.Future;", "class Test {", " // BUG: Diagnostic contains:", " void test(Future<?> future) throws Exception {", " future.get();", " throw new IllegalStateException();", " }", "}") .addOutputLines( "Test.java", "import java.util.concurrent.ExecutionException;", "import java.util.concurrent.Future;", "class Test {", " // BUG: Diagnostic contains:", " void test(Future<?> future) throws ExecutionException, InterruptedException {", " future.get();", " throw new IllegalStateException();", " }", "}") .doTest(); } @Test public void hiddenInMethodThrows_butActuallyThrowsException_noFinding() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.ExecutionException;", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) throws Exception {", " future.get();", " throw new Exception();", " }", "}") .doTest(); } @Test public void hiddenInMethodThrows_throwsSimplified() { compilationHelper .addSourceLines( "Test.java", "import java.io.IOException;", "import java.io.FileNotFoundException;", "import java.util.concurrent.ExecutionException;", "import java.util.concurrent.Future;", "class Test {", " // BUG: Diagnostic contains: ExecutionException, IOException, InterruptedException", " void test(Future<?> future) throws Exception {", " future.get();", " if (true) {", " throw new IOException();", " } else {", " throw new FileNotFoundException();", " }", " }", "}") .doTest(); } @Test public void hiddenInMethodThrows_bailsIfTooManySpecificExceptions() { compilationHelper .addSourceLines( "Test.java", "import java.io.IOException;", "import java.util.concurrent.ExecutionException;", "import java.util.concurrent.Future;", "import java.util.concurrent.TimeoutException;", "class Test {", " void test(Future<?> future) throws Exception {", " future.get();", " if (hashCode() == 0) {", " throw new A();", " }", " if (hashCode() == 0) {", " throw new B();", " }", " if (hashCode() == 0) {", " throw new C();", " }", " if (hashCode() == 0) {", " throw new D();", " }", " if (hashCode() == 0) {", " throw new E();", " }", " }", " static class A extends Exception {}", " static class B extends Exception {}", " static class C extends Exception {}", " static class D extends Exception {}", " static class E extends Exception {}", "}") .doTest(); } @Test public void throwsExceptionButNoSignOfInterrupted() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) throws Exception {", " throw new Exception();", " }", "}") .doTest(); } @Test public void declaredInMethodThrows() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.ExecutionException;", "import java.util.concurrent.Future;", "class Test {", " void test(Future<?> future) throws InterruptedException, ExecutionException {", " future.get();", " }", "}") .doTest(); } @Test public void declaredInMain() { compilationHelper .addSourceLines( "Test.java", "import java.util.concurrent.ExecutionException;", "import java.util.concurrent.Future;", "public class Test {", " private static final Future<?> future = null;", " public static void main(String[] argv) throws Exception {", " future.get();", " }", "}") .doTest(); } }
16,506
30.322581
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FloatCastTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link FloatCast}Test */ @RunWith(JUnit4.class) public class FloatCastTest { @Test public void positive() { CompilationTestHelper.newInstance(FloatCast.class, getClass()) .addSourceLines( "Test.java", // "class Test {", " {", " // BUG: Diagnostic contains:" + "'int x = (int) (0.9f * 42);' or 'int x = ((int) 0.9f) * 42;'", " int x = (int) 0.9f * 42;", " // BUG: Diagnostic contains:" + "'float y = (int) (0.9f * 0.9f);' or 'float y = ((int) 0.9f) * 0.9f;'", " float y = (int) 0.9f * 0.9f;", " // BUG: Diagnostic contains:" + "'int z = (int) (0.9f * 42 * 1 * 2);' or 'int z = ((int) 0.9f) * 42 * 1 * 2;'", " int z = (int) 0.9f * 42 * 1 * 2;", " }", "}") .doTest(); } @Test public void negative() { CompilationTestHelper.newInstance(FloatCast.class, getClass()) .addSourceLines( "Test.java", // "class Test {", " {", " int x = (int) 0.9f + 42;", " float y = (int) 0.9f - 0.9f;", " x = ((int) 0.9f) * 42;", " y = (int) (0.9f * 0.9f);", " String s = (int) 0.9f + \"\";", " boolean b = (int) 0.9f > 1;", " long c = (long) Math.ceil(10.0d / 2) * 2;", " long f = (long) Math.floor(10.0d / 2) * 2;", " long g = (long) Math.signum(10.0d / 2) * 2;", " long r = (long) Math.rint(10.0d / 2) * 2;", " }", "}") .doTest(); } @Test public void pow() { CompilationTestHelper.newInstance(FloatCast.class, getClass()) .addSourceLines( "Test.java", // "class Test {", " {", " // BUG: Diagnostic contains: 'int x = (int) (Math.pow(10, 0.5f) * 42);'", " int x = (int) Math.pow(10, 0.5f) * 42;", " int y = (int) Math.pow(10, 2) * 42;", " }", "}") .doTest(); } }
2,938
33.576471
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DefaultCharsetTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static org.junit.Assume.assumeTrue; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link DefaultCharset}Test */ @RunWith(JUnit4.class) public class DefaultCharsetTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(DefaultCharset.class, getClass()); private BugCheckerRefactoringTestHelper refactoringTest() { return BugCheckerRefactoringTestHelper.newInstance(DefaultCharset.class, getClass()); } @Test public void bothFixes() { compilationHelper .addSourceLines( "Test.java", "import java.io.*;", "class Test {", " byte[] f(String s) {", " // BUG: Diagnostic contains: 'return s.getBytes(UTF_8);'" + " or 'return s.getBytes(Charset.defaultCharset());'", " return s.getBytes();", " }", "}") .doTest(); } @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import java.io.*;", "class Test {", " void f(String s, byte[] b, OutputStream out, InputStream in) throws Exception {", " // BUG: Diagnostic contains: s.getBytes(UTF_8);", " s.getBytes();", " // BUG: Diagnostic contains: new String(b, UTF_8);", " new String(b);", " // BUG: Diagnostic contains: new String(b, 0, 0, UTF_8);", " new String(b, 0, 0);", " // BUG: Diagnostic contains: new OutputStreamWriter(out, UTF_8);", " new OutputStreamWriter(out);", " // BUG: Diagnostic contains: new InputStreamReader(in, UTF_8);", " new InputStreamReader(in);", " }", "}") .doTest(); } @Test public void reader() { compilationHelper .addSourceLines( "Test.java", "import java.io.*;", "class Test {", " void f(String s, File f) throws Exception {", " // BUG: Diagnostic contains: Files.newBufferedReader(Paths.get(s), UTF_8);", " new FileReader(s);", " // BUG: Diagnostic contains: Files.newBufferedReader(f.toPath(), UTF_8);", " new FileReader(f);", " }", "}") .doTest(); } @Test public void writer() { compilationHelper .addSourceLines( "Test.java", "import java.io.*;", "class Test {", " static final boolean CONST = true;", " void f(File f, String s, boolean flag) throws Exception {", " // BUG: Diagnostic contains: Files.newBufferedWriter(Paths.get(s), UTF_8);", " new FileWriter(s);", " // BUG: Diagnostic contains:" + " Files.newBufferedWriter(Paths.get(s), UTF_8, CREATE, APPEND);", " new FileWriter(s, true);", " // BUG: Diagnostic contains:" + " Files.newBufferedWriter(Paths.get(s), UTF_8, CREATE, APPEND);", " new FileWriter(s, CONST);", " // BUG: Diagnostic contains: Files.newBufferedWriter(f.toPath(), UTF_8);", " new FileWriter(f);", " // BUG: Diagnostic contains:" + " Files.newBufferedWriter(f.toPath(), UTF_8, CREATE, APPEND);", " new FileWriter(f, true);", " // BUG: Diagnostic contains: Files.newBufferedWriter(f.toPath(), UTF_8);", " new FileWriter(f, false);", " // BUG: Diagnostic contains:" + " Files.newBufferedWriter(f.toPath(), UTF_8, flag" + " ? new StandardOpenOption[] {CREATE, APPEND}" + " : new StandardOpenOption[] {CREATE}", " new FileWriter(f, flag);", " }", "}") .doTest(); } @Test public void buffered() { compilationHelper .addSourceLines( "Test.java", "import java.io.*;", "class Test {", " void f(String s) throws Exception {", " // BUG: Diagnostic contains: " + "try (BufferedReader reader = Files.newBufferedReader(Paths.get(s), UTF_8)) {}'", " try (BufferedReader reader = new BufferedReader(new FileReader(s))) {}", " // BUG: Diagnostic contains: " + "try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(s), UTF_8)) {}", " try (BufferedWriter writer = new BufferedWriter(new FileWriter(s))) {}", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import java.io.*;", "class Test {", " void f(String s, byte[] b, OutputStream out, InputStream in, File f)", " throws Exception {", " s.getBytes(UTF_8);", " new String(b, UTF_8);", " new String(b, 0, 0, UTF_8);", " new OutputStreamWriter(out, UTF_8);", " new InputStreamReader(in, UTF_8);", " }", "}") .doTest(); } @Test public void ignoreFileDescriptor() { compilationHelper .addSourceLines( "Test.java", "import java.io.*;", "class Test {", " void f(FileDescriptor fd) throws Exception {", " try (BufferedReader reader = new BufferedReader(new FileReader(fd))) {}", " try (BufferedWriter writer = new BufferedWriter(new FileWriter(fd))) {}", " }", "}") .doTest(); } @Test public void guavaReader() { refactoringTest() .addInputLines( "in/Test.java", "import java.io.*;", "import com.google.common.io.Files;", "class Test {", " void f(String s, File f) throws Exception {", " new FileReader(s);", " new FileReader(f);", " }", "}") .addOutputLines( "out/Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import com.google.common.io.Files;", "import java.io.*;", "import java.io.File;", "class Test {", " void f(String s, File f) throws Exception {", " Files.newReader(new File(s), UTF_8);", " Files.newReader(f, UTF_8);", " }", "}") .doTest(); } @Test public void guavaWriterImportAppend() { refactoringTest() .addInputLines( "in/Test.java", "import java.io.*;", "import com.google.common.io.Files;", "class Test {", " void f(String s, File f) throws Exception {", " new FileWriter(s, true);", " new FileWriter(f, true);", " }", "}") .addOutputLines( "out/Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import static java.nio.file.StandardOpenOption.APPEND;", "import static java.nio.file.StandardOpenOption.CREATE;", "import com.google.common.io.Files;", "import java.io.*;", "import java.nio.file.Paths;", "class Test {", " void f(String s, File f) throws Exception {", " java.nio.file.Files.newBufferedWriter(Paths.get(s), UTF_8, CREATE, APPEND);", " java.nio.file.Files.newBufferedWriter(f.toPath(), UTF_8, CREATE, APPEND);", " }", "}") .doTest(); } @Test public void guavaWriter() { refactoringTest() .addInputLines( "in/Test.java", "import java.io.*;", "import com.google.common.io.Files;", "class Test {", " void f(String s, File f) throws Exception {", " new FileWriter(s);", " new FileWriter(f);", " }", "}") .addOutputLines( "out/Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import com.google.common.io.Files;", "import java.io.*;", "import java.io.File;", "class Test {", " void f(String s, File f) throws Exception {", " Files.newWriter(new File(s), UTF_8);", " Files.newWriter(f, UTF_8);", " }", "}") .doTest(); } @Test public void androidReader() { refactoringTest() .addInputLines( "in/Test.java", "import java.io.*;", "class Test {", " void f(String s, File f) throws Exception {", " new FileReader(s);", " new FileReader(f);", " }", "}") .expectUnchanged() .setArgs("-XDandroidCompatible=true") .doTest(); } @Test public void androidWriter() { refactoringTest() .addInputLines( "in/Test.java", "import java.io.*;", "class Test {", " void f(String s, File f) throws Exception {", " new FileWriter(s);", " new FileWriter(f);", " }", "}") .expectUnchanged() .setArgs("-XDandroidCompatible=true") .doTest(); } @Test public void variableFix() { refactoringTest() .addInputLines( "in/Test.java", "import java.io.*;", "class Test {", " void f(File f) throws Exception {", " FileWriter w = new FileWriter(f);", " FileReader r = new FileReader(f);", " }", "}") .addOutputLines( "out/Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import java.io.*;", "import java.io.Reader;", "import java.io.Writer;", "import java.nio.file.Files;", "class Test {", " void f(File f) throws Exception {", " Writer w = Files.newBufferedWriter(f.toPath(), UTF_8);", " Reader r = Files.newBufferedReader(f.toPath(), UTF_8);", " }", "}") .doTest(); } @Test public void variableFixAtADistance() { refactoringTest() .addInputLines( "in/Test.java", "import java.io.*;", "class Test {", " FileWriter w = null;", " FileReader r = null;", " void f(File f) throws Exception {", " w = new FileWriter(f);", " r = new FileReader(f);", " }", "}") .addOutputLines( "out/Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import java.io.*;", "import java.io.Reader;", "import java.io.Writer;", "import java.nio.file.Files;", "class Test {", " Writer w = null;", " Reader r = null;", " void f(File f) throws Exception {", " w = Files.newBufferedWriter(f.toPath(), UTF_8);", " r = Files.newBufferedReader(f.toPath(), UTF_8);", " }", "}") .doTest(); } @Test public void printWriter() { refactoringTest() .addInputLines( "in/Test.java", "import java.io.File;", "import java.io.PrintWriter;", "class Test {", " void f() throws Exception {", " PrintWriter pw1 = new PrintWriter(System.err, true);", " PrintWriter pw2 = new PrintWriter(System.err);", " PrintWriter pw3 = new PrintWriter(\"test\");", " PrintWriter pw4 = new PrintWriter(new File(\"test\"));", " }", "}") .addOutputLines( "out/Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import java.io.BufferedWriter;", "import java.io.File;", "import java.io.OutputStreamWriter;", "import java.io.PrintWriter;", "class Test {", " void f() throws Exception {", " PrintWriter pw1 = new PrintWriter(", " new BufferedWriter(new OutputStreamWriter(System.err, UTF_8)), true);", " PrintWriter pw2 = new PrintWriter(", " new BufferedWriter(new OutputStreamWriter(System.err, UTF_8)));", " PrintWriter pw3 = new PrintWriter(\"test\", UTF_8.name());", " PrintWriter pw4 = new PrintWriter(new File(\"test\"), UTF_8.name());", " }", "}") .doTest(); } @Test public void byteString() { refactoringTest() .addInputLines( "in/Test.java", "import com.google.protobuf.ByteString;", "class Test {", " void f() throws Exception {", " ByteString.copyFrom(\"hello\".getBytes());", " }", "}") .addOutputLines( "out/Test.java", "import com.google.protobuf.ByteString;", "class Test {", " void f() throws Exception {", " ByteString.copyFromUtf8(\"hello\");", " }", "}") .doTest(); } @Test public void byteStringDefaultCharset() { refactoringTest() .addInputLines( "in/Test.java", "import com.google.protobuf.ByteString;", "class Test {", " void f() throws Exception {", " ByteString.copyFrom(\"hello\".getBytes());", " }", "}") .addOutputLines( "out/Test.java", "import com.google.protobuf.ByteString;", "import java.nio.charset.Charset;", "class Test {", " void f() throws Exception {", " ByteString.copyFrom(\"hello\", Charset.defaultCharset());", " }", "}") .setFixChooser(FixChoosers.SECOND) .doTest(); } @Test public void byteStringDefaultCharset_staticImport() { refactoringTest() .addInputLines( "in/Test.java", "import static com.google.protobuf.ByteString.copyFrom;", "class Test {", " void f() throws Exception {", " copyFrom(\"hello\".getBytes());", " }", "}") .addOutputLines( "out/Test.java", "import static com.google.protobuf.ByteString.copyFrom;", "import java.nio.charset.Charset;", "class Test {", " void f() throws Exception {", " copyFrom(\"hello\", Charset.defaultCharset());", " }", "}") .setFixChooser(FixChoosers.SECOND) .doTest(); } @Test public void scannerDefaultCharset() { refactoringTest() .addInputLines( "in/Test.java", "import java.util.Scanner;", "import java.io.File;", "import java.io.InputStream;", "import java.nio.channels.ReadableByteChannel;", "import java.nio.file.Path;", "class Test {", " void f() throws Exception {", " new Scanner((InputStream) null);", " new Scanner((File) null);", " new Scanner((Path) null);", " new Scanner((ReadableByteChannel) null);", " }", "}") .addOutputLines( "out/Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import java.io.File;", "import java.io.InputStream;", "import java.nio.channels.ReadableByteChannel;", "import java.nio.file.Path;", "import java.util.Scanner;", "class Test {", " void f() throws Exception {", " new Scanner((InputStream) null, UTF_8.name());", " new Scanner((File) null, UTF_8.name());", " new Scanner((Path) null, UTF_8.name());", " new Scanner((ReadableByteChannel) null, UTF_8.name());", " }", "}") .doTest(); } @Test public void withVar() { assumeTrue(RuntimeVersion.isAtLeast15()); refactoringTest() .addInputLines( "in/Test.java", "import java.io.File;", "import java.io.FileWriter;", "class Test {", " void f(File file) throws Exception {", " var fileWriter = new FileWriter(file);", " }", "}") .addOutputLines( "out/Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import java.io.File;", "import java.io.FileWriter;", "import java.nio.file.Files;", "class Test {", " void f(File file) throws Exception {", " var fileWriter = Files.newBufferedWriter(file.toPath(), UTF_8);", " }", "}") .doTest(); } @Test public void byteArrayOutputStream() { refactoringTest() .addInputLines( "in/Test.java", "import java.io.ByteArrayOutputStream;", "class Test {", " String f(ByteArrayOutputStream b) throws Exception {", " return b.toString();", " }", "}") .addOutputLines( "out/Test.java", "import static java.nio.charset.StandardCharsets.UTF_8;", "import java.io.ByteArrayOutputStream;", "class Test {", " String f(ByteArrayOutputStream b) throws Exception {", " return b.toString(UTF_8);", " }", "}") .doTest(); } }
19,204
33.541367
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeFinalTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.annotations.Var; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author cushon@google.com (Liam Miller-Cushon) */ @RunWith(JUnit4.class) public class FieldCanBeFinalTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(FieldCanBeFinal.class, getClass()); @Test public void annotationFieldsAreAlreadyFinal() { compilationHelper .addSourceLines( "Anno.java", // "public @interface Anno {", " int x = 42;", " static int y = 42;", "}") .doTest(); } @Test public void simple() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: private final int x", " private int x;", " Test() {", " x = 42;", " }", "}") .doTest(); } @Test public void keepAnnotatedFields_ignored() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Keep;", "class Test {", " @Keep private int x;", " Test() {", " x = 42;", " }", "}") .doTest(); } @Test public void injectAnnotatedFields_ignored() { compilationHelper .addSourceLines( "Test.java", "import javax.inject.Inject;", "class Test {", " @Inject private int x;", " Test() {", " x = 42;", " }", "}") .doTest(); } @Test public void initializerBlocks() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: private final int x1", " private int x1;", " private int x2;", " // BUG: Diagnostic contains: private static final int y1", " private static int y1;", " private static int y2;", " {", " x1 = 42;", " x2 = 42;", " }", " static {", " y1 = 42;", " y2 = 42;", " }", " void mutate() {", " x2 = 0;", " y2 = 0;", " }", "}") .doTest(); } @Test public void staticSetFromInstance() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: private static final int x1", " private static int x1;", " private static int x2;", " static {", " x1 = 42;", " x2 = 42;", " }", " {", " x2 = 42;", " }", "}") .doTest(); } @Test public void suppressionOnField() { compilationHelper .addSourceLines( "Test.java", "class Test {", " @SuppressWarnings(\"FieldCanBeFinal\")", " private int x;", " Test() {", " x = 42;", " }", "}") .doTest(); } @Test public void suppressionOnClass() { compilationHelper .addSourceLines( "Test.java", "@SuppressWarnings(\"FieldCanBeFinal\") ", "class Test {", " private int x;", " Test() {", " x = 42;", " }", "}") .doTest(); } // the nullary constructor doesn't set x directly, but that's OK @Test public void constructorChaining() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: private final int x", " private int x;", " Test(int x) {", " this.x = x;", " }", " Test() {", " this(42);", " }", "}") .doTest(); } // we currently handle this by ignoring control flow and looking for at least one initialization @Test public void controlFlow() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: private final int x", " private int x;", " Test(boolean flag, int x, int y) {", " if (flag) {", " this.x = x;", " } else {", " this.x = y;", " }", " }", "}") .doTest(); } @Test public void doubleInitialization() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private int x;", " Test(int x) {", " this.x = x;", " this.x = x;", " }", "}") .doTest(); } @Test public void compoundAssignment() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private int x;", " Test() {", " this.x = 42;", " }", " void incr() {", " x += 1;", " }", "}") .doTest(); } @Test public void unaryAssignment() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private int x;", " Test() {", " this.x = 42;", " }", " void incr() {", " x++;", " }", "}") .doTest(); } @Test public void constructorAssignmentToOtherInstance() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private int x;", " // BUG: Diagnostic contains: private final int y", " private int y;", " Test(Test other) {", " x = 42;", " y = 42;", " other.x = x;", " }", "}") .doTest(); } @Test public void assignmentFromOutsideCompilationUnit() { compilationHelper .addSourceLines( "A.java", "class A {", " int x;", " A(B b) {", " x = 42;", " b.x = 42;", " }", "}") .addSourceLines( "B.java", "class B {", " int x;", " B(A a) {", " x = 42;", " a.x = 42;", " }", "}") // hackily force processing of both compilation units so we can verify both diagnostics .setArgs(Arrays.asList("-XDshouldStopPolicyIfError=FLOW")) .doTest(); } // don't report an error if the field has an initializer and is also written // in the constructor @Test public void guardInitialization() { compilationHelper .addSourceLines( "Test.java", String.format("import %s;", Var.class.getCanonicalName()), "class Test {", " private boolean initialized = false;", " Test() {", " initialized = true;", " }", "}") .doTest(); } @Test public void fieldInitialization() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: private final boolean flag", " private boolean flag = false;", " Test() {", " }", "}") .doTest(); } @Test public void ignoreInject() { compilationHelper .addSourceLines( "Test.java", "import javax.inject.Inject;", "class Test {", " @Inject private Object x;", " Test() {", " this.x = x;", " }", "}") .doTest(); } @Test public void allowNonFinal_nonFinalForTesting() { compilationHelper .addSourceLines( "Test.java", "@interface NonFinalForTesting {}", "class Test {", " @NonFinalForTesting private int x;", " Test(int x) {", " this.x = x;", " }", "}") .doTest(); } @Test public void visibleForTesting() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.annotations.VisibleForTesting;", "class Test {", " @VisibleForTesting public int x;", " Test() {", " x = 42;", " }", "}") .doTest(); } @Test public void protectedField() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.annotations.VisibleForTesting;", "class Test {", " protected int x;", " Test() {", " x = 42;", " }", "}") .doTest(); } @Test public void nonPrivateField() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.annotations.VisibleForTesting;", "class Test {", " public int x;", " int y;", " Test() {", " x = 42;", " y = 42;", " }", "}") .doTest(); } @Test public void allowObjectifyClasses() { compilationHelper .addSourceLines( "com/googlecode/objectify/v4/annotation/Entity.java", "package com.googlecode.objectify.v4.annotation;", "public @interface Entity {}") .addSourceLines( "Test.java", "import com.googlecode.objectify.v4.annotation.Entity;", "@Entity class Test {", " private int x;", " Test(int x) {", " this.x = x;", " }", "}") .doTest(); } @Test public void initInLambda() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private int x;", " private final Runnable r;", " Test() {", " r = () -> x = 1;", " }", "}") .doTest(); } @Test public void constructorAssignmentWithLambdaReassignment() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private Runnable r;", " Test() {", " r = foo(() -> r = null);", " }", " private static Runnable foo(Runnable r) {", " return r;", " }", "}") .doTest(); } }
11,854
24.771739
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LiteByteStringUtf8Test.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test cases for {@link LiteByteStringUtf8}. */ @RunWith(JUnit4.class) public class LiteByteStringUtf8Test { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(LiteByteStringUtf8.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceLines( "Foo.java", "import com.google.protobuf.ByteString;", "import com.google.protobuf.MessageLite;", "class Foo {", " void main(com.google.protobuf.MessageLite m) {", " // BUG: Diagnostic contains: ByteString", " String s = m.toByteString().toStringUtf8();", " }", "}") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceLines( "Foo.java", "import com.google.protobuf.ByteString;", "import com.google.protobuf.MessageLite;", "class Foo {", " void main(MessageLite m, ByteString b) {", " ByteString b2 = m.toByteString();", " String s = b2.toStringUtf8();", " }", "}") .doTest(); } }
2,004
30.825397
78
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EmptyCatchTest.java
/* * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author yuan@ece.toronto.edu (Ding Yuan) */ @RunWith(JUnit4.class) public class EmptyCatchTest { private CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(EmptyCatch.class, getClass()); } @Test public void positiveCase() throws Exception { compilationHelper.addSourceFile("EmptyCatchPositiveCases.java").doTest(); } @Test public void negativeCase() throws Exception { compilationHelper.addSourceFile("EmptyCatchNegativeCases.java").doTest(); } @Test public void addTestNgTest() { compilationHelper .addSourceLines( "org/testng/annotations/Test.java", "package org.testng.annotations;", "public @interface Test {", "}") .addSourceLines( "in/SomeTest.java", "import org.testng.annotations.Test;", "public class SomeTest {", " @Test", " public void testNG() {", " try {", " System.err.println();", " } catch (Exception doNotCare) {", " }", " }", "}") .doTest(); } }
2,042
27.774648
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EqualsIncompatibleTypeTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static org.junit.Assume.assumeFalse; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author avenet@google.com (Arnaud J. Venet) */ @RunWith(JUnit4.class) public class EqualsIncompatibleTypeTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(EqualsIncompatibleType.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("EqualsIncompatibleTypePositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("EqualsIncompatibleTypeNegativeCases.java").doTest(); } @Test public void negativeCase_recursive() { compilationHelper.addSourceFile("EqualsIncompatibleTypeRecursiveTypes.java").doTest(); } @Test public void primitiveBoxingIntoObject() { assumeFalse(RuntimeVersion.isAtLeast12()); // https://bugs.openjdk.java.net/browse/JDK-8028563 compilationHelper .addSourceLines( "Test.java", "class Test {", " void something(boolean b, Object o) {", " o.equals(b);", " }", "}") .setArgs(Arrays.asList("-source", "1.6", "-target", "1.6")) .doTest(); } @Test public void i547() { compilationHelper .addSourceLines( "Test.java", "class Test {", " interface B {}", " <T extends B> void t(T x) {", " // BUG: Diagnostic contains: T and String", " x.equals(\"foo\");", " }", "}") .doTest(); } @Test public void prettyNameForConflicts() { compilationHelper .addSourceLines( "Test.java", "class Test {", " interface B {}", " interface String {}", " void t(String x) {", " // BUG: Diagnostic contains: types Test.String and java.lang.String", " x.equals(\"foo\");", " }", "}") .doTest(); } @Test public void methodReference_incompatibleTypes_finding() { compilationHelper .addSourceLines( "Test.java", "import java.util.stream.Stream;", "class Test {", " boolean t(Stream<Integer> xs, String x) {", " // BUG: Diagnostic contains:", " return xs.anyMatch(x::equals);", " }", "}") .doTest(); } @Test public void methodReference_comparableTypes_noFinding() { compilationHelper .addSourceLines( "Test.java", "import java.util.stream.Stream;", "class Test {", " boolean t(Stream<Integer> xs, Object x) {", " return xs.anyMatch(x::equals);", " }", "}") .doTest(); } @Test public void wildcards_whenIncompatible() { compilationHelper .addSourceLines( "Test.java", "", "public class Test {", " public void test(Class<? extends Integer> a, Class<? extends String> b) {", " // BUG: Diagnostic contains:", " a.equals(b);", " }", "}") .doTest(); } @Test public void unconstrainedWildcard_compatibleWithAnything() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "", "public class Test {", " public void test(java.lang.reflect.Method m, Class<?> c) {", " TestProtoMessage.class.equals(m.getParameterTypes()[0]);", " TestProtoMessage.class.equals(c);", " }", "}") .doTest(); } @Test public void enumsCanBeEqual() { compilationHelper .addSourceLines( "Test.java", "class Test {", " enum E {A, B}", " public void test() {", " E.A.equals(E.B);", " }", "}") .doTest(); } @Test public void protoBuildersCannotBeEqual() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestOneOfMessage;", "", "public class Test {", " public void test() {", " // BUG: Diagnostic contains: . Though", " TestProtoMessage.newBuilder().equals(TestProtoMessage.newBuilder());", " // BUG: Diagnostic contains:", " TestProtoMessage.newBuilder().equals(TestOneOfMessage.newBuilder());", " // BUG: Diagnostic contains:", " TestProtoMessage.newBuilder().equals(TestOneOfMessage.getDefaultInstance());", " }", "}") .doTest(); } @Test public void enumsNamedBuilderCanBeEqual() { compilationHelper .addSourceLines( "Test.java", "public class Test {", " enum FooBuilder { A }", " public boolean test(FooBuilder a, FooBuilder b) {", " return a.equals(b);", " }", "}") .doTest(); } @Test public void flaggedOff_protoBuildersNotConsideredIncomparable() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "", "public class Test {", " public void test() {", " TestProtoMessage.newBuilder().equals(TestProtoMessage.newBuilder());", " TestProtoMessage.getDefaultInstance()", " .equals(TestProtoMessage.getDefaultInstance());", " }", "}") .setArgs("-XepOpt:TypeCompatibility:TreatBuildersAsIncomparable=false") .doTest(); } @Test public void protoBuilderComparedWithinAutoValue() { compilationHelper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "@AutoValue", "abstract class Test {", " abstract TestProtoMessage.Builder b();", "}") .addSourceLines( "AutoValue_Test.java", "import javax.annotation.processing.Generated;", "@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")", "abstract class AutoValue_Test extends Test {", " @Override", " public boolean equals(Object o) {", " return ((Test) o).b().equals(b());", " }", "}") .doTest(); } @Test public void predicateIsEqual_incompatible() { compilationHelper .addSourceLines( "Test.java", "import static java.util.function.Predicate.isEqual;", "import java.util.stream.Stream;", "class Test {", " boolean test(Stream<Long> xs) {", " // BUG: Diagnostic contains:", " return xs.allMatch(isEqual(1));", " }", "}") .doTest(); } @Test public void predicateIsEqual_compatible() { compilationHelper .addSourceLines( "Test.java", "import static java.util.function.Predicate.isEqual;", "import java.util.stream.Stream;", "class Test {", " boolean test(Stream<Long> xs) {", " return xs.allMatch(isEqual(1L));", " }", "}") .doTest(); } @Test public void predicateIsEqual_methodRef() { compilationHelper .addSourceLines( "Test.java", "import java.util.function.Function;", "import java.util.function.Predicate;", "import java.util.stream.Stream;", "class Test {", " boolean test(Function<Long, Predicate<Integer>> fn) {", " // BUG: Diagnostic contains:", " return test(Predicate::isEqual);", " }", "}") .doTest(); } }
9,182
30.023649
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NullTernaryTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static org.junit.Assume.assumeTrue; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link NullTernary}Test */ @RunWith(JUnit4.class) public class NullTernaryTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(NullTernary.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "Test.java", "class Test {", " void f(boolean b) {", " // BUG: Diagnostic contains:", " int x = b ? 0 : null;", " // BUG: Diagnostic contains:", " long l = b ? null : 0;", " // BUG: Diagnostic contains:", " g(\"\", b ? null : 0);", " // BUG: Diagnostic contains:", " h(\"\", 1, b ? null : 0);", " // BUG: Diagnostic contains:", " h(\"\", 1, b ? null : 0, 3);", " // BUG: Diagnostic contains:", " int z = 0 + (b ? null : 1);", " // BUG: Diagnostic contains:", " z = (b ? null : 1) + 0;", " }", " void g(String s, int y) {}", " void h(String s, int... y) {}", "}") .doTest(); } @Test public void negative() { testHelper .addSourceLines( "Test.java", "class Test {", " void f(boolean b) {", " int x = b ? 0 : 1;", " Integer y = b ? 0 : null;", " g(\"\", b ? 1 : 0);", " h(\"\", 1, b ? 1 : 0);", " h(\"\", 1, b ? 1 : 0, 3);", " int z = 0 + (b ? 0 : 1);", " boolean t = (b ? 0 : null) == Integer.valueOf(0);", " }", " void g(String s, int y) {}", " void h(String s, int... y) {}", "}") .doTest(); } @Test public void lambdas() { testHelper .addSourceLines( "Test.java", "class Test {", " interface I {", " int f();", " }", " interface J {", " Integer f();", " }", " interface K<X> {", " X f();", " }", " void f(boolean b) {", " // BUG: Diagnostic contains:", " I i = () -> { return b ? null : 1; };", " J j = () -> { return b ? null : 1; };", " K<Integer> k = () -> { return b ? null : 1; };", " // BUG: Diagnostic contains:", " i = () -> b ? null : 1;", " j = () -> b ? null : 1;", " k = () -> b ? null : 1;", " }", "}") .doTest(); } @Test public void conditionalInCondition() { testHelper .addSourceLines( "Test.java", "class Test {", " void conditionalInCondition(Object array, String input) {", " int arrayDimensions = ", " ((array!=null?input:null) == null)", " ? 0", " : (array!=null?input:null).length();", " }", "}") .doTest(); } @Test public void expressionSwitch_doesNotCrash() { assumeTrue(RuntimeVersion.isAtLeast14()); testHelper .addSourceLines( "Test.java", "class Test {", " static String doStuff(SomeEnum enumVar) {", " return switch (enumVar) {", " case A -> enumVar.name() != null ? \"AAA\" : null;", " default -> null;", " };", " }", " ", " static enum SomeEnum {", " A, B", " }", "}") .doTest(); } }
4,620
30.013423
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/GetClassOnClassTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author chy@google.com (Christine Yang) * @author kmuhlrad@google.com (Katy Muhlrad) */ @RunWith(JUnit4.class) public class GetClassOnClassTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(GetClassOnClass.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("GetClassOnClassPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("GetClassOnClassNegativeCases.java").doTest(); } }
1,340
30.186047
82
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BareDotMetacharacterTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link BareDotMetacharacter}. */ @RunWith(JUnit4.class) public class BareDotMetacharacterTest { private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(BareDotMetacharacter.class, getClass()); @Test public void positiveCase() { refactoringHelper .addInputLines( "Test.java", "import com.google.common.base.Splitter;", "class Test {", " private static final String DOT = \".\";", " Object x = \"foo.bar\".split(\".\");", " Object y = \"foo.bonk\".split(DOT);", " Object z = Splitter.onPattern(\".\");", "}") .addOutputLines( "Test.java", "import com.google.common.base.Splitter;", "class Test {", " private static final String DOT = \".\";", " Object x = \"foo.bar\".split(\"\\\\.\");", " Object y = \"foo.bonk\".split(\"\\\\.\");", " Object z = Splitter.onPattern(\"\\\\.\");", "}") .doTest(); } }
1,915
33.836364
90
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OrphanedFormatStringTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link OrphanedFormatString}Test */ @RunWith(JUnit4.class) public class OrphanedFormatStringTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(OrphanedFormatString.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "Test.java", "class Test {", " void f() {", " // BUG: Diagnostic contains:", " System.err.println(\"%s\");", " // BUG: Diagnostic contains:", " new Exception(\"%s\");", " // BUG: Diagnostic contains:", " new StringBuilder(\"%s\");", " // BUG: Diagnostic contains:", " new StringBuilder().append(\"%s\", 0, 0);", " }", "}") .doTest(); } @Test public void negative() { testHelper .addSourceLines( "Test.java", "class Test {", " static class FormatException extends Exception {", " FormatException(String f, Object... xs) {", " super(String.format(f, xs));", " }", " }", " void f() {", " String s = \"%s\";", " new FormatException(\"%s\");", " System.err.printf(\"%s\");", " }", " void appendToStringBuilder(StringBuilder b) {", " b.append(\"%s\");", " }", "}") .doTest(); } @Test public void formatMethod() { testHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "class Test {", " static class MyPrintWriter extends java.io.PrintWriter {", " MyPrintWriter() throws java.io.FileNotFoundException {super((String) null);}", " public void println(String message) {}", " @FormatMethod", " public void println(String first, Object...args) {}", " @FormatMethod", " public void print(String first," + " @FormatString String second, Object...args) {}", " }", " void f(MyPrintWriter pw) {", " // BUG: Diagnostic contains:", " pw.println(\"%s\");", " pw.println(\"%s %s\", \"\", \"\");", " pw.print(\"\", \"%s\");", // Here, %s in the first position is a non-format String arg " // BUG: Diagnostic contains: ", " pw.print(\"%s\", \"%s\");", // The first argument to the format string is another format string " // BUG: Diagnostic contains: ", " pw.print(\"\", \"%s\", \"%d\");", " }", "}") .doTest(); } // "$ f" is a valid format string, because ' ' is a flag // TODO(b/165671890): consider adding a heuristic to skip these @Test public void spaceAfterPercent() { testHelper .addSourceLines( "Test.java", "class Test {", " void f() {", " // BUG: Diagnostic contains:", " StringBuilder messageBuilder = new StringBuilder(\"more than 50% finished\");", " }", "}") .doTest(); } @Test public void assertWithMessage() { testHelper .addSourceLines( "Test.java", "import static com.google.common.truth.Truth.assertWithMessage;", "class Test {", " void test() {", " // BUG: Diagnostic contains:", " assertWithMessage(\"%s\").that(\"\").isNull();", " }", "}") .doTest(); } @Test public void flogger() { testHelper .addSourceLines( "Test.java", "import com.google.common.flogger.FluentLogger;", "class Test {", " private static final FluentLogger logger = FluentLogger.forEnclosingClass();", " public void f() {", " // BUG: Diagnostic contains:", " logger.atInfo().log(\"hello %d\");", " }", "}") .doTest(); } @Test public void negativeFlogger() { testHelper .addSourceLines( "Test.java", "import com.google.common.flogger.FluentLogger;", "class Test {", " private static final FluentLogger logger = FluentLogger.forEnclosingClass();", " public void f(String arg) {", " logger.atInfo().log(\"hello %d\", arg);", " }", "}") .doTest(); } }
5,581
32.029586
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CatchFailTest.java
/* * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link CatchFail}Test */ @RunWith(JUnit4.class) public class CatchFailTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(CatchFail.class, getClass()); @Test public void positive() { testHelper .addInputLines( "in/Foo.java", "import org.junit.Test;", "class Foo {", " @Test public void f() {", " try {", " System.err.println();", " } catch (Exception expected) {", " org.junit.Assert.fail();", " }", " }", " public void testFoo() {", " try {", " System.err.println();", " } catch (Exception expected) {", " org.junit.Assert.fail();", " }", " }", "}") .addOutputLines( "out/Foo.java", "import org.junit.Test;", "class Foo {", " @Test public void f() throws Exception {", " System.err.println();", " }", " public void testFoo() throws Exception {", " System.err.println();", " }", "}") .doTest(); } @Test public void positive_failFail() { testHelper .addInputLines( "in/Foo.java", "import org.junit.Test;", "class Foo {", " @Test public void f() {", " try {", " System.err.println();", " } catch (Exception expected) {", " org.junit.Assert.fail();", " } catch (Throwable unexpected) {", " org.junit.Assert.fail();", " }", " }", "}") .addOutputLines( "out/Foo.java", "import org.junit.Test;", "class Foo {", " @Test public void f() throws Exception, Throwable {", " System.err.println();", " }", "}") .doTest(); } @Test public void positive_finally() { testHelper .addInputLines( "in/Test.java", "class Test {", " public void test() {", " try {", " if (true) throw new NoSuchMethodException();", " if (true) throw new NoSuchFieldException();", " System.err.println();", " } catch (NoSuchMethodException | NoSuchFieldException expected) {", " org.junit.Assert.fail();", " } finally {}", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " public void test() throws NoSuchMethodException, NoSuchFieldException {", " try {", " if (true) throw new NoSuchMethodException();", " if (true) throw new NoSuchFieldException();", " System.err.println();", " } finally {}", " }", "}") .doTest(); } @Test public void positive_otherCatch() { testHelper .addInputLines( "in/Test.java", "class Test {", " public void test() {", " try {", " System.err.println();", " } catch (Exception expected) {", " org.junit.Assert.fail();", " } catch (Error e) {}", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " public void test() throws Exception {", " try {", " System.err.println();", " } catch (Error e) {}", " }", "}") .doTest(); } @Test public void negative_nonTest() { testHelper .addInputLines( "in/Foo.java", "import org.junit.Test;", "class Foo {", " public void f() {", " try {", " System.err.println();", " } catch (Exception expected) {", " // BUG: Diagnostic contains:", " org.junit.Assert.fail();", " }", " }", "}") .expectUnchanged() .doTest(); } @Test public void useException() { testHelper .addInputLines( "in/Foo.java", "import org.junit.Test;", "class Foo {", " @Test public void f() {", " try {", " System.err.println();", " } catch (Exception expected) {", " org.junit.Assert.fail(\"oh no \" + expected);", " }", " }", "}") .expectUnchanged() .doTest(); } @Test public void deleteEmptyTry() { testHelper .addInputLines( "in/Foo.java", "import org.junit.Test;", "class Foo {", " @Test public void f() {", " try {", " } catch (Exception expected) {", " org.junit.Assert.fail(\"oh no \");", " }", " }", "}") .addOutputLines( "out/Foo.java", "import org.junit.Test;", "class Foo {", " @Test public void f() {", " }", "}") .setFixChooser(FixChoosers.SECOND) .doTest(); } @Test public void failVariations() { testHelper .addInputLines( "in/Foo.java", "class Foo {", " public void f() {", " try {", " System.err.println();", " } catch (Exception expected) {", " org.junit.Assert.fail();", " }", " try {", " System.err.println();", " } catch (Exception expected) {", " org.junit.Assert.fail(\"oh no \");", " }", " }", "}") .addOutputLines( "out/Foo.java", "class Foo {", " public void f() {", " try {", " System.err.println();", " } catch (Exception expected) {", " org.junit.Assert.fail();", " }", " try {", " System.err.println();", " } catch (Exception expected) {", " throw new AssertionError(\"oh no \", expected);", " }", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void expected() { testHelper .addInputLines( "in/Foo.java", "import org.junit.Test;", "import java.io.IOException;", "class Foo {", " @Test(expected = IOException.class)", " public void f() {", " try {", " throw new IOException();", " } catch (IOException expected) {", " org.junit.Assert.fail();", " }", " }", "}") .addOutputLines( "out/Foo.java", "import org.junit.Test;", "import java.io.IOException;", "class Foo {", " @Test(expected = IOException.class)", " public void f() {", " try {", " throw new IOException();", " } catch (IOException expected) {", " org.junit.Assert.fail();", " }", " }", "}") .doTest(); } }
8,726
29.197232
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OverridesTest.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author cushon@google.com (Liam Miller-Cushon) */ @RunWith(JUnit4.class) public class OverridesTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(Overrides.class, getClass()); @Test public void positiveCase1() { compilationHelper.addSourceFile("OverridesPositiveCase1.java").doTest(); } @Test public void positiveCase2() { compilationHelper.addSourceFile("OverridesPositiveCase2.java").doTest(); } @Test public void positiveCase3() { compilationHelper.addSourceFile("OverridesPositiveCase3.java").doTest(); } @Test public void positiveCase4() { compilationHelper.addSourceFile("OverridesPositiveCase4.java").doTest(); } @Test public void positiveCase5() { compilationHelper.addSourceFile("OverridesPositiveCase5.java").doTest(); } @Test public void negativeCase1() { compilationHelper.addSourceFile("OverridesNegativeCase1.java").doTest(); } @Test public void negativeCase2() { compilationHelper.addSourceFile("OverridesNegativeCase2.java").doTest(); } @Test public void negativeCase3() { compilationHelper.addSourceFile("OverridesNegativeCase3.java").doTest(); } }
2,011
26.944444
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FallThroughTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static org.junit.Assume.assumeTrue; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link FallThrough}Test */ @RunWith(JUnit4.class) public class FallThroughTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(FallThrough.class, getClass()); @Test public void positive() { testHelper.addSourceFile("FallThroughPositiveCases.java").doTest(); } @Test public void negative() { testHelper.addSourceFile("FallThroughNegativeCases.java").doTest(); } @Test public void foreverLoop() { testHelper .addSourceLines( "Test.java", "class Test {", " void f(int x) {", " switch (x) {", " case 1:", " for (;;) {}", " case 2:", " break;", " }", " }", "}") .doTest(); } @Test public void commentInBlock() { testHelper .addSourceLines( "Test.java", "class Test {", " void f(int x) {", " switch (x) {", " case 0: {", " // fall through", " }", " case 1: {", " System.err.println();", " // fall through", " }", " case 2:", " break;", " }", " }", "}") .doTest(); } @Test public void emptyBlock() { testHelper .addSourceLines( "Test.java", "class Test {", " void f(char c, boolean b) {", " switch (c) {", " case 'a': {}", " // fall through", " default:", " }", " }", "}") .doTest(); } @Test public void arrowSwitch() { assumeTrue(RuntimeVersion.isAtLeast14()); testHelper .addSourceLines( "Test.java", "class Test {", " enum Case { ONE, TWO }", " void m(Case c) {", " switch (c) {", " case ONE -> {}", " case TWO -> {}", " default -> {}", " }", " }", "}") .doTest(); } @Ignore("https://github.com/google/error-prone/issues/2638") @Test public void i2118() { assumeTrue(RuntimeVersion.isAtLeast14()); testHelper .addSourceLines( "Test.java", "class Test {", " enum Case { ONE, TWO }", " void m(Case c) {", " switch (c) {", " case ONE:", " switch (c) {", " case ONE -> m(c);", " case TWO -> m(c);", " }", " default:", " assert false;", " }", " }", "}") .doTest(); } }
3,845
25.342466
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnsafeLocaleUsageTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link UnsafeLocaleUsage}. */ @RunWith(JUnit4.class) public class UnsafeLocaleUsageTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnsafeLocaleUsage.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(UnsafeLocaleUsage.class, getClass()); @Test public void unsafeLocaleUsageCheck_constructorUsageWithOneParam_shouldRefactorNonLiteralParam() { refactoringHelper .addInputLines( "Test.java", "import java.util.Locale;", "", "class Test {", " static class Inner {", " private Locale locale;", " Inner(String a) {", " locale = new Locale(a);", " }", " }", "", " private static final Test.Inner INNER_OBJ = new Inner(\"zh_hant_tw\");", "", "}") .addOutputLines( "Test.java", "import java.util.Locale;", "", "class Test {", " static class Inner {", " private Locale locale;", " Inner(String a) {", " locale = Locale.forLanguageTag(a.replace(\"_\", \"-\"));", " }", " }", "", " private static final Test.Inner INNER_OBJ = new Inner(\"zh_hant_tw\");", "", "}") .doTest(); } @Test public void unsafeLocaleUsageCheck_constructorUsageWithOneParam_shouldRefactorLiteralParam() { refactoringHelper .addInputLines( "Test.java", "import java.util.Locale;", "", "class Test {", " private static final Locale LOCALE = new Locale(\"zh_hant_tw\");", "}") .addOutputLines( "Test.java", "import java.util.Locale;", "", "class Test {", " private static final Locale LOCALE = Locale.forLanguageTag(\"zh-hant-tw\");", "}") .doTest(); } @Test public void unsafeLocaleUsageCheck_constructorUsageWithTwoParams_shouldRefactor() { refactoringHelper .addInputLines( "Test.java", "import java.util.Locale;", "", "class Test {", " static class Inner {", " private Locale locale;", " Inner(String a, String b) {", " locale = new Locale(a, b);", " }", " }", "", " private static final Test.Inner INNER_OBJ = new Inner(\"zh\", \"tw\");", "", "}") .addOutputLines( "Test.java", "import java.util.Locale;", "", "class Test {", " static class Inner {", " private Locale locale;", " Inner(String a, String b) {", " locale = new Locale.Builder().setLanguage(a).setRegion(b).build();", " }", " }", "", " private static final Test.Inner INNER_OBJ = new Inner(\"zh\", \"tw\");", "", "}") .doTest(); } @Test public void unsafeLocaleUsageCheck_constructorUsageWithThreeParams_shouldFlag() { compilationHelper .addSourceLines( "Test.java", "import java.util.Locale;", "", "class Test {", " static class Inner {", " private Locale locale;", " Inner(String a, String b, String c) {", " // BUG: Diagnostic contains: forLanguageTag(String)", " locale = new Locale(a, b, c);", " }", " }", "", " private static final Test.Inner INNER_OBJ = new Inner(\"zh\", \"tw\", \"hant\");", "", "}") .doTest(); } @Test public void unsafeLocaleUsageCheck_toStringUsage_shouldRefactor() { refactoringHelper .addInputLines( "Test.java", "import java.util.Locale;", "", "class Test {", " static class Inner {", " private Locale locale;", " Inner(String a) {", " locale = Locale.forLanguageTag(a);", " }", "", " String getLocaleDisplayString() {", " return locale.toString();", " }", " }", "", " private static final Test.Inner INNER_OBJ = new Inner(\"zh_hant_tw\");", "}") .addOutputLines( "Test.java", "import java.util.Locale;", "", "class Test {", " static class Inner {", " private Locale locale;", " Inner(String a) {", " locale = Locale.forLanguageTag(a);", " }", "", " String getLocaleDisplayString() {", " return locale.toLanguageTag();", " }", " }", "", " private static final Test.Inner INNER_OBJ = new Inner(\"zh_hant_tw\");", "}") .doTest(); } @Test public void unsafeLocaleUsageCheck_multipleErrors_shouldFlag() { compilationHelper .addSourceLines( "Test.java", "import java.util.Locale;", "class Test {", " // BUG: Diagnostic contains: forLanguageTag(String)", " private static final Locale LOCALE = new Locale(", " // BUG: Diagnostic contains: toLanguageTag()", " Locale.TAIWAN.toString());", "}") .doTest(); } @Test public void unsafeLocaleUsageCheck_instanceMethodUsage_shouldNotFlag() { compilationHelper .addSourceLines( "Test.java", "import java.util.Locale;", "import com.google.common.collect.ImmutableMap;", "class Test {", " private static final ImmutableMap<String, Locale> INTERNAL_COUNTRY_CODE_TO_LOCALE =", " ImmutableMap.of(\"abc\", Locale.KOREAN);", " private static final String DISPLAY_NAME = getLocaleDisplayNameFromCode(\"abc\");", "", " public static final String getLocaleDisplayNameFromCode(String code) {", " return INTERNAL_COUNTRY_CODE_TO_LOCALE.get(code).getDisplayName();", " }", "}") .doTest(); } }
7,542
32.674107
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IsInstanceOfClassTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link IsInstanceOfClass}Test */ @RunWith(JUnit4.class) public class IsInstanceOfClassTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(IsInstanceOfClass.class, getClass()); @Test public void positive_clazz_enclosingClass() { compilationHelper .addSourceLines( "pkg/A.java", "class A {", " boolean m(Class<?> clazz) {", " // BUG: Diagnostic contains: clazz.isAssignableFrom(getClass())", " return getClass().isInstance(clazz);", " }", "}") .doTest(); } @Test public void positive_enclosingClass_clazz() { compilationHelper .addSourceLines( "pkg/A.java", "class A {", " boolean m(Class<?> clazz) {", " // BUG: Diagnostic contains: getClass().isAssignableFrom(clazz)", " return clazz.isInstance(getClass());", " }", "}") .doTest(); } @Test public void positive_getClass_getClass() { compilationHelper .addSourceLines( "pkg/A.java", "class A {", " boolean m(Object a, Object b) {", " // BUG: Diagnostic contains: b.getClass().isInstance(a)", " return a.getClass().isInstance(b.getClass());", " }", "}") .doTest(); } @Test public void positive_getClass_literal() { compilationHelper .addSourceLines( "pkg/A.java", "class A {", " boolean m(Object obj) {", " // BUG: Diagnostic contains: obj instanceof String", " return obj.getClass().isInstance(String.class);", " }", "}") .doTest(); } @Test public void positive_literal_getClass() { compilationHelper .addSourceLines( "pkg/A.java", "class A {", " boolean m(Object obj) {", " // BUG: Diagnostic contains: obj instanceof String", " return String.class.isInstance(obj.getClass());", " }", "}") .doTest(); } @Test public void positive_literal_literal() { compilationHelper .addSourceLines( "pkg/A.java", "class A {", " boolean m(Object obj) {", " // BUG: Diagnostic contains: String.class == Class.class", " return Number.class.isInstance(String.class);", " }", "}") .doTest(); } @Test public void positive_clazz_getClass() { compilationHelper .addSourceLines( "pkg/A.java", "class A {", " boolean m(Object o, Class<?> clazz) {", " // BUG: Diagnostic contains: clazz.isInstance(o)", " return clazz.isInstance(o.getClass());", " }", "}") .doTest(); } @Test public void positive_getClass_clazz() { compilationHelper .addSourceLines( "pkg/A.java", "class A {", " boolean m(Object o, Class<?> clazz) {", " // BUG: Diagnostic contains: clazz.isInstance(o)", " return o.getClass().isInstance(clazz);", " }", "}") .doTest(); } @Test public void positive_clazz_clazz() { compilationHelper .addSourceLines( "pkg/A.java", "class A {", " boolean m(Class<?> a, Class<?> b) {", " // BUG: Diagnostic contains: b.isAssignableFrom(a)", " return a.isInstance(b);", " }", "}") .doTest(); } }
4,542
28.121795
82
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ReturnsNullCollectionTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ReturnsNullCollection}Test */ @RunWith(JUnit4.class) public class ReturnsNullCollectionTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ReturnsNullCollection.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.Multimap;", "import java.util.Collection;", "import java.util.ArrayList;", "import java.util.List;", "import java.util.Map;", "class Test {", " Collection<String> methodReturnsNullCollection() {", " // BUG: Diagnostic contains: ReturnsNullCollection", " return null;", " }", " List<String> methodReturnsNullList() {", " // BUG: Diagnostic contains: ReturnsNullCollection", " return null;", " }", " Map<String, String> methodReturnsNullMap() {", " // BUG: Diagnostic contains: ReturnsNullCollection", " return null;", " }", " Multimap<String, String> methodReturnsNullMultimap() {", " // BUG: Diagnostic contains: ReturnsNullCollection", " return null;", " }", " List<String> methodReturnsNullListConditionally(boolean foo) {", " if (foo) {", " // BUG: Diagnostic contains: ReturnsNullCollection", " return null;", " }", " return new ArrayList();", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.Collection;", "import java.util.HashMap;", "import java.util.List;", "import java.util.Map;", "import javax.annotation.Nullable;", "class Test {", " @Nullable", " Collection<String> methodReturnsNullCollection() {", " return null;", " }", " @Nullable", " List<String> methodReturnsNullList() {", " return null;", " }", " @Nullable", " Map<String, String> methodReturnsNullMap() {", " return null;", " }", " @Nullable", " HashMap<String, String> methodReturnsNullHashMap() {", " return null;", " }", "}") .doTest(); } }
3,425
33.26
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ProtoRedundantSetTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link ProtoRedundantSet} bugpattern. * * @author ghm@google.com (Graeme Morgan) */ @RunWith(JUnit4.class) @Ignore("b/130670719") public final class ProtoRedundantSetTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ProtoRedundantSet.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceLines( "ProtoRedundantSetPositiveCases.java", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "final class ProtoRedundantSetPositiveCases {", " private static final TestFieldProtoMessage foo =", " TestFieldProtoMessage.getDefaultInstance();", " private static final TestFieldProtoMessage bar =", " TestFieldProtoMessage.getDefaultInstance();", " private void singleField() {", " TestProtoMessage twice =", " TestProtoMessage.newBuilder()", " .setMessage(foo)", " .addMultiField(bar)", " // BUG: Diagnostic contains: setMessage", " .setMessage(foo)", " .addMultiField(bar)", " .build();", " TestProtoMessage nestedField =", " TestProtoMessage.newBuilder()", " .setMessage(", " // BUG: Diagnostic contains: setField", " TestFieldProtoMessage.newBuilder().setField(foo).setField(foo))", " .addMultiField(bar)", " .build();", " }", " private void repeatedField() {", " TestProtoMessage.Builder again =", " TestProtoMessage.newBuilder()", " .setMessage(foo)", " .setMessage(foo)", " // BUG: Diagnostic contains: setMessage", " .setMessage(foo)", " .setMultiField(0, bar)", " .setMultiField(1, foo)", " // BUG: Diagnostic contains: setMultiField", " .setMultiField(1, bar);", " }", "}") .doTest(); } @Test public void singleField() { compilationHelper .addSourceLines( "SingleField.java", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "final class ProtoRedundantSetNegativeCases {", " private void singleField() {", " TestProtoMessage.Builder builder =", " TestProtoMessage.newBuilder()", " .setMessage(TestFieldProtoMessage.getDefaultInstance())", " .addMultiField(TestFieldProtoMessage.getDefaultInstance())", " .addMultiField(TestFieldProtoMessage.getDefaultInstance());", " }", "}") .doTest(); } @Test public void repeatedField() { compilationHelper .addSourceLines( "RepeatedField.java", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "final class ProtoRedundantSetNegativeCases {", " private void repeatedField() {", " TestProtoMessage.Builder builder =", " TestProtoMessage.newBuilder()", " .setMessage(TestFieldProtoMessage.getDefaultInstance())", " .setMultiField(0, TestFieldProtoMessage.getDefaultInstance())", " .setMultiField(1, TestFieldProtoMessage.getDefaultInstance());", " }", "}") .doTest(); } @Test public void complexChaining() { compilationHelper .addSourceLines( "ComplexChaining.java", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "final class ProtoRedundantSetNegativeCases {", " private void intermediateBuild() {", " TestProtoMessage message =", " TestProtoMessage.newBuilder()", " .setMessage(TestFieldProtoMessage.getDefaultInstance())", " .build()", " .toBuilder()", " .setMessage(TestFieldProtoMessage.getDefaultInstance())", " .build();", " }", "}") .doTest(); } @Test public void fixes() { BugCheckerRefactoringTestHelper.newInstance(ProtoRedundantSet.class, getClass()) .addInputLines( "ProtoRedundantSetPositiveCases.java", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "final class ProtoRedundantSetPositiveCases {", " private static final TestFieldProtoMessage foo =", " TestFieldProtoMessage.getDefaultInstance();", " private static final TestFieldProtoMessage bar =", " TestFieldProtoMessage.getDefaultInstance();", " private void singleField() {", " TestProtoMessage twice =", " TestProtoMessage.newBuilder()", " .setMessage(foo)", " .addMultiField(bar)", " .setMessage(foo)", " .addMultiField(bar)", " .build();", " }", " private void repeatedField() {", " TestProtoMessage.Builder again =", " TestProtoMessage.newBuilder()", " .setMessage(foo)", " .setMessage(foo)", " .setMessage(foo)", " .setMultiField(0, bar)", " .setMultiField(1, foo)", " .setMultiField(1, bar);", " }", "}") .addOutputLines( "ProtoRedundantSetExpected.java", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;", "import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;", "final class ProtoRedundantSetPositiveCases {", " private static final TestFieldProtoMessage foo =", " TestFieldProtoMessage.getDefaultInstance();", " private static final TestFieldProtoMessage bar =", " TestFieldProtoMessage.getDefaultInstance();", " private void singleField() {", " TestProtoMessage twice =", " TestProtoMessage.newBuilder()", " .addMultiField(bar)", " .setMessage(foo)", " .addMultiField(bar)", " .build();", " }", " private void repeatedField() {", " TestProtoMessage.Builder again =", " TestProtoMessage.newBuilder()", " .setMessage(foo)", " .setMultiField(0, bar)", " .setMultiField(1, foo)", " .setMultiField(1, bar);", " }", "}") .doTest(TestMode.AST_MATCH); } }
8,827
42.487685
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StaticMockMemberTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link StaticMockMember} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class StaticMockMemberTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(StaticMockMember.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(StaticMockMember.class, getClass()); @Test public void positiveCases() { testHelper .addInputLines( "in/Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.mockito.Mock;", "@RunWith(JUnit4.class)", "public class Test {", " @Mock private static String mockedPrivateString;", " @Mock static String mockedString;", "}") .addOutputLines( "out/Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.mockito.Mock;", "@RunWith(JUnit4.class)", "public class Test {", " @Mock private String mockedPrivateString;", " @Mock String mockedString;", "}") .doTest(); } @Test public void negativeCases() { compilationHelper .addSourceLines( "in/Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.mockito.Mock;", "@RunWith(JUnit4.class)", "public class Test {", " @Mock private String mockedPrivateString;", " @Mock String mockedString;", "}") .doTest(); } @Test public void memberSuppression() { compilationHelper .addSourceLines( "in/Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.mockito.Mock;", "@RunWith(JUnit4.class)", "public class Test {", " @SuppressWarnings(\"StaticMockMember\")", " @Mock private static String mockedPrivateString;", "}") .doTest(); } @Test public void flagIfRemovingStaticWontCompile() { compilationHelper .addSourceLines( "in/Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.mockito.Mock;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: StaticMockMember", " @Mock private static String mockedPrivateString;", " static String someStaticMethod() {", " return mockedPrivateString;", " }", "}") .doTest(); } }
3,763
32.017544
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MisusedWeekYearTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test cases for {@link MisusedWeekYear}. */ @RunWith(JUnit4.class) public class MisusedWeekYearTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MisusedWeekYear.class, getClass()); @Test public void positiveCases() { compilationHelper.addSourceFile("MisusedWeekYearPositiveCases.java").doTest(); } @Test public void positiveCases2() { compilationHelper.addSourceFile("MisusedWeekYearPositiveCases2.java").doTest(); } @Test public void negativeCases() { compilationHelper.addSourceFile("MisusedWeekYearNegativeCases.java").doTest(); } @Test public void refactoring() { BugCheckerRefactoringTestHelper.newInstance(MisusedWeekYear.class, getClass()) .addInputLines( "Test.java", "import java.time.format.DateTimeFormatter;", "class Test {", // " private static final String PATTERN = \"YYYY\";", " static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);", "}") .addOutputLines( "Test.java", "import java.time.format.DateTimeFormatter;", "class Test {", // " private static final String PATTERN = \"yyyy\";", " static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);", "}") .doTest(); } }
2,267
32.850746
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UndefinedEqualsTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.common.base.Joiner; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; /** * Unit tests for {@link UndefinedEquals} * * @author eleanorh@google.com (Eleanor Harris) */ @RunWith(JUnitParamsRunner.class) public final class UndefinedEqualsTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UndefinedEquals.class, getClass()); @Test public void positiveInstanceEquals() { compilationHelper .addSourceLines( "Test.java", "import java.util.Queue;", "class Test {", " void f(Queue a, Queue b) {", " // BUG: Diagnostic contains: Subtypes of Queue are not guaranteed", " a.equals(b);", " }", "}") .doTest(); } @Test public void positiveStaticEquals() { compilationHelper .addSourceLines( "Test.java", "import java.util.Collection;", "import java.util.Objects;", "class Test {", " void f(Collection a, Collection b) {", " // BUG: Diagnostic contains: Collection", " Objects.equals(a,b);", " }", "}") .doTest(); } @Test public void immutableCollection() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableCollection;", "import java.util.Objects;", "class Test {", " void f(ImmutableCollection a, ImmutableCollection b) {", " // BUG: Diagnostic contains: ImmutableCollection", " Objects.equals(a,b);", " }", "}") .doTest(); } @Test public void positiveAssertEquals() { compilationHelper .addSourceLines( "Test.java", "import java.util.List;", "import com.google.common.collect.FluentIterable;", "import com.google.common.collect.Iterables;", "import static org.junit.Assert.assertEquals;", "import static org.junit.Assert.assertNotEquals;", "class Test {", " void test(List myList, List otherList) {", " // BUG: Diagnostic contains: Iterable", " assertEquals(FluentIterable.of(1), FluentIterable.of(1));", " // BUG: Diagnostic contains: Iterable", " assertEquals(Iterables.skip(myList, 1), Iterables.skip(myList, 2));", " // BUG: Diagnostic contains: Iterable", " assertNotEquals(Iterables.skip(myList, 1), Iterables.skip(myList, 2));", " // BUG: Diagnostic contains: Iterable", " assertEquals(\"foo\", Iterables.skip(myList, 1), Iterables.skip(myList, 2));", " }", "}") .doTest(); } @Test public void positiveWithGenerics() { compilationHelper .addSourceLines( "Test.java", "import java.util.Queue;", "class Test {", " <T> void f(Queue<String> a, Queue<T> b) {", " // BUG: Diagnostic contains: Queue", " a.equals(b);", " }", "}") .doTest(); } @Test public void positiveTruth() { compilationHelper .addSourceLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import java.util.Queue;", "class Test {", " <T> void f(Queue<String> a, Queue<T> b) {", " // BUG: Diagnostic contains: Queue", " assertThat(a).isEqualTo(b);", " // BUG: Diagnostic contains: Queue", " assertThat(a).isNotEqualTo(b);", " }", "}") .doTest(); } @Test @Parameters(method = "truthFixParameters") public void truthFixParameterized(String input, String output) { BugCheckerRefactoringTestHelper.newInstance(UndefinedEquals.class, getClass()) .addInputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import com.google.common.collect.ImmutableCollection;", "import com.google.common.collect.Multimap;", "import java.lang.Iterable;", "import java.util.Collection;", "import java.util.Queue;", "class Test {", input, "}") .addOutputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import com.google.common.collect.ImmutableCollection;", "import com.google.common.collect.Multimap;", "import java.lang.Iterable;", "import java.util.Collection;", "import java.util.Queue;", "class Test {", output, "}") .doTest(); } private static Object truthFixParameters() { return new Object[] { new String[] { lines( " void f1(Multimap a, Multimap b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f1(Multimap a, Multimap b) {", // " assertThat(a).containsExactlyEntriesIn(b);", " }") }, new String[] { lines( " void f2(Multimap a, Collection b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f2(Multimap a, Collection b) {", " assertThat(a).isEqualTo(b);", // no fix " }") }, new String[] { lines( " void f3(Multimap a, Iterable b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f3(Multimap a, Iterable b) {", " assertThat(a).isEqualTo(b);", // no fix " }") }, new String[] { lines( " void f4(Multimap a, Queue b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f4(Multimap a, Queue b) {", " assertThat(a).isEqualTo(b);", // no fix " }") }, new String[] { lines( " void f5(Collection a, Multimap b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f5(Collection a, Multimap b) {", " assertThat(a).isEqualTo(b);", // no fix " }") }, new String[] { lines( " void f6(Collection a, Collection b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f6(Collection a, Collection b) {", // " assertThat(a).containsExactlyElementsIn(b);", " }") }, new String[] { lines( " void f7(Collection a, Iterable b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f7(Collection a, Iterable b) {", // " assertThat(a).containsExactlyElementsIn(b);", " }") }, new String[] { lines( " void f8(Collection a, Queue b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f8(Collection a, Queue b) {", // " assertThat(a).containsExactlyElementsIn(b);", " }") }, new String[] { lines( " void f9(Iterable a, Multimap b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f9(Iterable a, Multimap b) {", " assertThat(a).isEqualTo(b);", // no fix " }") }, new String[] { lines( " void f10(Iterable a, Collection b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f10(Iterable a, Collection b) {", // " assertThat(a).containsExactlyElementsIn(b);", " }") }, new String[] { lines( " void f11(Iterable a, Iterable b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f11(Iterable a, Iterable b) {", // " assertThat(a).containsExactlyElementsIn(b);", " }") }, new String[] { lines( " void f12(Iterable a, Queue b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f12(Iterable a, Queue b) {", // " assertThat(a).containsExactlyElementsIn(b);", " }") }, new String[] { lines( " void f13(Queue a, Multimap b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f13(Queue a, Multimap b) {", " assertThat(a).isEqualTo(b);", // no fix " }") }, new String[] { lines( " void f14(Queue a, Collection b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f14(Queue a, Collection b) {", // " assertThat(a).containsExactlyElementsIn(b);", " }") }, new String[] { lines( " void f15(Queue a, Iterable b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f15(Queue a, Iterable b) {", // " assertThat(a).containsExactlyElementsIn(b);", " }") }, new String[] { lines( " void f16(Queue a, Queue b) {", // " assertThat(a).isEqualTo(b);", " }"), lines( " void f16(Queue a, Queue b) {", // " assertThat(a).containsExactlyElementsIn(b);", " }") } }; } private static String lines(String... lines) { return Joiner.on('\n').join(lines); } @Test public void truthFixAssertWithMessage() { BugCheckerRefactoringTestHelper.newInstance(UndefinedEquals.class, getClass()) .addInputLines( "Test.java", "import static com.google.common.truth.Truth.assertWithMessage;", "import java.lang.Iterable;", "class Test {", " void f(Iterable a, Iterable b) {", " assertWithMessage(\"message\").that(a).isEqualTo(b);", " }", "}") .addOutputLines( "Test.java", "import static com.google.common.truth.Truth.assertWithMessage;", "import java.lang.Iterable;", "class Test {", " void f(Iterable a, Iterable b) {", " assertWithMessage(\"message\").that(a).containsExactlyElementsIn(b);", " }", "}") .doTest(); } @Test public void truthFixDontRewriteIsNotEqualTo() { BugCheckerRefactoringTestHelper.newInstance(UndefinedEquals.class, getClass()) .addInputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import java.lang.Iterable;", "class Test {", " void f(Iterable a, Iterable b) {", " assertThat(a).isNotEqualTo(b);", " }", "}") .addOutputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import java.lang.Iterable;", "class Test {", " void f(Iterable a, Iterable b) {", " assertThat(a).isNotEqualTo(b);", " }", "}") .doTest(); } @Test public void truthFixAcrossMultipleLinesAndPoorlyFormatted() { BugCheckerRefactoringTestHelper.newInstance(UndefinedEquals.class, getClass()) .addInputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import java.lang.Iterable;", "class Test {", " void f(Iterable a, Iterable b) {", " assertThat(a).", // period should be on following line per style guide " isEqualTo(b);", " }", "}") .addOutputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import java.lang.Iterable;", "class Test {", " void f(Iterable a, Iterable b) {", " assertThat(a).", " containsExactlyElementsIn(b);", " }", "}") .doTest(); } @Test public void positiveSparseArray() { compilationHelper .addSourceLines( "SparseArray.java", // "package android.util;", "public class SparseArray <T> {}") .addSourceLines( "Test.java", "import android.util.SparseArray;", "class Test {", " <T> boolean f(SparseArray<T> a, SparseArray<T> b) {", " // BUG: Diagnostic contains: SparseArray", " return a.equals(b);", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.PriorityQueue;", "class Test {", " void f(PriorityQueue a, PriorityQueue b) {", " a.equals(b);", " }", "}") .doTest(); } @Test public void charSequenceFix() { BugCheckerRefactoringTestHelper.newInstance(UndefinedEquals.class, getClass()) .addInputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "class Test {", " void f(CharSequence a, String b) {", " assertThat(a).isEqualTo(b);", " assertThat(b).isEqualTo(a);", " }", "}") .addOutputLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "class Test {", " void f(CharSequence a, String b) {", " assertThat(a.toString()).isEqualTo(b);", " assertThat(b).isEqualTo(a.toString());", " }", "}") .doTest(); } }
15,355
31.602972
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnicodeInCodeTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.truth.Truth.assertWithMessage; import static java.util.Locale.ENGLISH; import static java.util.stream.Collectors.joining; import com.google.common.collect.ImmutableList; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.FileManagers; import com.sun.source.util.JavacTask; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.file.JavacFileManager; import java.net.URI; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link UnicodeInCode}. */ @RunWith(JUnit4.class) public final class UnicodeInCodeTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(UnicodeInCode.class, getClass()); @Test public void negative() { helper .addSourceLines( "Test.java", // "class Test {", " final int noUnicodeHereBoss = 1;", "}") .doTest(); } @Test public void negativeInComment() { helper .addSourceLines( "Test.java", // "/** \u03C0 */", "class Test {", " final int noUnicodeHereBoss = 1; // roughly \u03C0", "}") .doTest(); } @Test public void negativeInStringLiteral() { helper .addSourceLines( "Test.java", // "class Test {", " static final String pi = \"\u03C0\";", "}") .doTest(); } @Test public void negativeInCharLiteral() { helper .addSourceLines( "Test.java", // "class Test {", " static final char pi = '\u03C0';", "}") .doTest(); } @Test public void positive() { helper .addSourceLines( "Test.java", // "class Test {", " // BUG: Diagnostic contains: Unicode character (\\u03c0)", " static final double \u03C0 = 3;", "}") .doTest(); } @Test public void positiveMultiCharacterGivesOneFinding() { helper .addSourceLines( "Test.java", // "class Test {", " // BUG: Diagnostic contains: Unicode character (\\u03c0\\u03c0)", " static final double \u03C0\u03C0 = 3;", "}") .doTest(); } @Test public void suppressibleAtClassLevel() { helper .addSourceLines( "Test.java", // "@SuppressWarnings(\"UnicodeInCode\")", "class Test {", " static final double \u03C0 = 3;", "}") .doTest(); } @Test public void suppressibleAtMethodLevel() { helper .addSourceLines( "Test.java", // "class Test {", " @SuppressWarnings(\"UnicodeInCode\")", " void test() {", " double \u03C0 = 3;", " }", "}") .doTest(); } @Test public void asciiSub() { JavacFileManager fileManager = FileManagers.testFileManager(); DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>(); JavacTask task = JavacTool.create() .getTask( null, fileManager, diagnosticCollector, ImmutableList.of("-Xplugin:ErrorProne", "-XDcompilePolicy=simple"), ImmutableList.of(), ImmutableList.of( new SimpleJavaFileObject( URI.create("file:///Test.java"), JavaFileObject.Kind.SOURCE) { @Override public String getCharContent(boolean ignoreEncodingErrors) { return "class Test {}" + ((char) 0x1a); } })); boolean ok = task.call(); assertWithMessage( diagnosticCollector.getDiagnostics().stream() .filter(d -> d.getKind() == Diagnostic.Kind.ERROR) .map(d -> d.getMessage(ENGLISH)) .collect(joining("\n"))) .that(ok) .isTrue(); } }
4,936
28.213018
90
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SizeGreaterThanOrEqualsZeroTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link com.google.errorprone.bugpatterns.SizeGreaterThanOrEqualsZero} */ @RunWith(JUnit4.class) @Ignore("b/130669807") public class SizeGreaterThanOrEqualsZeroTest { CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(SizeGreaterThanOrEqualsZero.class, getClass()); } @Test public void collectionSizePositiveCases() { compilationHelper.addSourceFile("SizeGreaterThanOrEqualsZeroPositiveCases.java").doTest(); } @Test public void collectionSizeNegativeCases() { compilationHelper.addSourceFile("SizeGreaterThanOrEqualsZeroNegativeCases.java").doTest(); } }
1,536
31.020833
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TooManyParametersTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.bugpatterns.TooManyParameters.TOO_MANY_PARAMETERS_FLAG_NAME; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.ErrorProneFlags; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link TooManyParameters}. */ @RunWith(JUnit4.class) public class TooManyParametersTest { private CompilationTestHelper compilationHelper; @Before public void setup() { compilationHelper = CompilationTestHelper.newInstance(TooManyParameters.class, getClass()); } @Test public void zeroLimit() { assertThrows( IllegalArgumentException.class, () -> new TooManyParameters( ErrorProneFlags.builder().putFlag(TOO_MANY_PARAMETERS_FLAG_NAME, "0").build())); } @Test public void negativeLimit() { assertThrows( IllegalArgumentException.class, () -> new TooManyParameters( ErrorProneFlags.builder().putFlag(TOO_MANY_PARAMETERS_FLAG_NAME, "-1").build())); } @Test public void constructor() { compilationHelper .setArgs(ImmutableList.of("-XepOpt:" + TOO_MANY_PARAMETERS_FLAG_NAME + "=3")) .addSourceLines( "ConstructorTest.java", "public class ConstructorTest {", " public ConstructorTest() {", " }", " public ConstructorTest(int a) {", " }", " public ConstructorTest(int a, int b) {", " }", " public ConstructorTest(int a, int b, int c) {", " }", " // BUG: Diagnostic contains: 4 parameters", " public ConstructorTest(int a, int b, int c, int d) {", " }", " // BUG: Diagnostic contains: 5 parameters", " public ConstructorTest(int a, int b, int c, int d, int e) {", " }", " // BUG: Diagnostic contains: 6 parameters", " public ConstructorTest(int a, int b, int c, int d, int e, int f) {", " }", " private ConstructorTest(int a, int b, int c, int d, int e, int f, int g) {", " }", "}") .doTest(); } @Test public void constructor_withAtInject() { compilationHelper .setArgs(ImmutableList.of("-XepOpt:" + TOO_MANY_PARAMETERS_FLAG_NAME + "=3")) .addSourceLines( "ConstructorTest.java", "import javax.inject.Inject;", "public class ConstructorTest {", " public ConstructorTest() {", " }", " public ConstructorTest(int a) {", " }", " public ConstructorTest(int a, int b) {", " }", " public ConstructorTest(int a, int b, int c) {", " }", " @Inject ConstructorTest(int a, int b, int c, int d) {", " }", "}") .doTest(); } @Test public void method() { compilationHelper .setArgs(ImmutableList.of("-XepOpt:" + TOO_MANY_PARAMETERS_FLAG_NAME + "=3")) .addSourceLines( "MethodTest.java", "public class MethodTest {", " public void foo() {", " }", " public void foo(int a) {", " }", " public void foo(int a, int b) {", " }", " public void foo(int a, int b, int c) {", " }", " // BUG: Diagnostic contains: 4 parameters", " public void foo(int a, int b, int c, int d) {", " }", " // BUG: Diagnostic contains: 5 parameters", " public void foo(int a, int b, int c, int d, int e) {", " }", " // BUG: Diagnostic contains: 6 parameters", " public void foo(int a, int b, int c, int d, int e, int f) {", " }", " private void foo(int a, int b, int c, int d, int e, int f, int g) {", " }", "}") .doTest(); } }
4,818
33.177305
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MultiVariableDeclarationTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link MultiVariableDeclaration}Test */ @RunWith(JUnit4.class) public class MultiVariableDeclarationTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MultiVariableDeclaration.class, getClass()); @Test public void positivePosition() { compilationHelper .addSourceLines( "A.java", // "package a;", "public class A {", " int a;", " // BUG: Diagnostic contains:", " int x = 1, y = 2;", "}") .doTest(); } @Test public void positive() { BugCheckerRefactoringTestHelper.newInstance(MultiVariableDeclaration.class, getClass()) .addInputLines( "in/A.java", // "package a;", "public class A {", " int x = 1, y = 2;", "}") .addOutputLines( "out/A.java", // "package a;", "public class A {", " int x = 1; int y = 2;", "}") .doTest(TEXT_MATCH); } @Test public void positiveWithNeighbours() { BugCheckerRefactoringTestHelper.newInstance(MultiVariableDeclaration.class, getClass()) .addInputLines( "in/A.java", "package a;", "public class A {", " int a = 1;", " int x = 1, y = 2;", " int b = 1;", "}") .addOutputLines( "out/A.java", "package a;", "public class A {", " int a = 1;", " int x = 1; int y = 2;", " int b = 1;", "}") .doTest(TEXT_MATCH); } @Test public void positiveWithNeighbouringScopes() { BugCheckerRefactoringTestHelper.newInstance(MultiVariableDeclaration.class, getClass()) .addInputLines( "in/A.java", "package a;", "public class A {", " {", " int a = 1;", " }", " int x = 1, y = 2;", " {", " int a = 1;", " }", "}") .addOutputLines( "out/A.java", "package a;", "public class A {", " {", " int a = 1;", " }", " int x = 1; int y = 2;", " {", " int a = 1;", " }", "}") .doTest(TEXT_MATCH); } @Test public void positiveCinit() { BugCheckerRefactoringTestHelper.newInstance(MultiVariableDeclaration.class, getClass()) .addInputLines( "in/A.java", // "package a;", "public class A {", " { int x = 1, y = 2; }", "}") .addOutputLines( "out/A.java", // "package a;", "public class A {", " { int x = 1; int y = 2; }", "}") .doTest(TEXT_MATCH); } @Test public void negative() { compilationHelper .addSourceLines( "a/A.java", // "package a;", "public class A {", " int x = 1;", "int y = 2;", "}") .doTest(); } @Test public void negativeForLoop() { compilationHelper .addSourceLines( "a/A.java", "package a;", "public class A {", " void f() {", " for (int x = 1, y = 2;;) { }", " }", "}") .doTest(); } @Test public void positiveAnnotation() { BugCheckerRefactoringTestHelper.newInstance(MultiVariableDeclaration.class, getClass()) .addInputLines( "in/A.java", // "package a;", "public class A {", " @Deprecated int x = 1, y = 2;", "}") .addOutputLines( "out/A.java", "package a;", "public class A {", " @Deprecated int x = 1;", " @Deprecated int y = 2;", "}") .doTest(TEXT_MATCH); } @Test public void positiveArrayDimensions() { BugCheckerRefactoringTestHelper.newInstance(MultiVariableDeclaration.class, getClass()) .addInputLines( "in/A.java", // "package a;", "public class A {", " int[] x = {0}, y[] = {{0}};", "}") .addOutputLines( "out/A.java", "package a;", "public class A {", " int[] x = {0}; int[][] y = {{0}};", "}") .doTest(TEXT_MATCH); } @Test public void positiveNoInitializer() { BugCheckerRefactoringTestHelper.newInstance(MultiVariableDeclaration.class, getClass()) .addInputLines( "in/A.java", // "package a;", "public class A {", " int x, y;", "}") .addOutputLines( "out/A.java", // "package a;", "public class A {", " int x; int y;", "}") .doTest(TEXT_MATCH); } }
6,041
26.715596
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ArrayFillIncompatibleTypeTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static org.junit.Assume.assumeFalse; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link ArrayFillIncompatibleType} */ @RunWith(JUnit4.class) public class ArrayFillIncompatibleTypeTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ArrayFillIncompatibleType.class, getClass()); @Test public void primitiveBoxingIntoObject() { assumeFalse(RuntimeVersion.isAtLeast12()); // https://bugs.openjdk.java.net/browse/JDK-8028563 compilationHelper .addSourceLines( "Test.java", "import java.util.Arrays;", "class Test {", " void something(boolean b, Object[] o) {", " Arrays.fill(o, b);", " }", "}") .setArgs(Arrays.asList("-source", "1.6", "-target", "1.6")) .doTest(); } @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import java.util.Arrays;", "class Test {", " void something(String b, Integer[] o, Number n) {", " // BUG: Diagnostic contains: ", " Arrays.fill(o, b);", " // BUG: Diagnostic contains: ", " Arrays.fill(o, 2.0d);", " // BUG: Diagnostic contains: ", " Arrays.fill(o, n);", " }", "}") .doTest(); } @Test public void ternary() { compilationHelper .addSourceLines( "Test.java", "import java.util.Arrays;", "class Test {", " enum Foo {BAR, BAZ};", " void something(Foo[] o, String[] s) {", " Arrays.fill(o, true ? Foo.BAR : Foo.BAZ);", " Arrays.fill(s, true ? \"a\" : \"b\");", " // BUG: Diagnostic contains: ", " Arrays.fill(s, true ? \"a\" : 123);", " }", "}") .doTest(); } @Test public void boxing() { compilationHelper .addSourceLines( "Test.java", "import java.util.Arrays;", "class Test {", " void something(int i, long l, Integer[] o) {", " Arrays.fill(o, 1);", " Arrays.fill(o, i);", " Arrays.fill(o, 0, 4, i);", " // BUG: Diagnostic contains: ", " Arrays.fill(o, l);", " // BUG: Diagnostic contains: ", " Arrays.fill(o, 4L);", " // BUG: Diagnostic contains: ", " Arrays.fill(o, 0, 4, l);", " }", "}") .doTest(); } }
3,512
31.229358
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SystemOutTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link SystemOut}. */ @RunWith(JUnit4.class) public class SystemOutTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(SystemOut.class, getClass()); @Test public void positive() { helper .addSourceLines( "Test.java", "import java.io.PrintStream;", "", "class Test {", " void f() {", " // BUG: Diagnostic contains: SystemOut", " System.out.println();", " // BUG: Diagnostic contains: SystemOut", " System.err.println();", " // BUG: Diagnostic contains: SystemOut", " p(System.out);", " // BUG: Diagnostic contains: SystemOut", " p(System.err);", " // BUG: Diagnostic contains: SystemOut", " Thread.dumpStack();", " // BUG: Diagnostic contains: SystemOut", " new Exception().printStackTrace();", " }", " private void p(PrintStream ps) {}", "}") .doTest(); } @Test public void negative() { helper .addSourceLines( "Test.java", "import java.io.*;", "", "class Test {", " void f() {", " new Exception().printStackTrace(new PrintStream((OutputStream) null));", " new Exception().printStackTrace(new PrintWriter((OutputStream) null));", " }", "}") .doTest(); } }
2,357
30.864865
89
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UngroupedOverloadsTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static org.junit.Assume.assumeTrue; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ @RunWith(JUnit4.class) public final class UngroupedOverloadsTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UngroupedOverloads.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(UngroupedOverloads.class, getClass()); @Test public void ungroupedOverloadsPositiveCasesSingle() { compilationHelper.addSourceFile("UngroupedOverloadsPositiveCasesSingle.java").doTest(); } @Test public void ungroupedOverloadsPositiveCasesMultiple() { compilationHelper.addSourceFile("UngroupedOverloadsPositiveCasesMultiple.java").doTest(); } @Test public void ungroupedOverloadsPositiveCasesInterleaved() { compilationHelper.addSourceFile("UngroupedOverloadsPositiveCasesInterleaved.java").doTest(); } @Test public void ungroupedOverloadsPositiveCasesCovering() { compilationHelper.addSourceFile("UngroupedOverloadsPositiveCasesCovering.java").doTest(); } @Test public void ungroupedOverloadsPositiveCasesCoveringOnlyFirstOverload() { compilationHelper .addSourceFile("UngroupedOverloadsPositiveCasesCoveringOnlyOnFirst.java") .setArgs(ImmutableList.of("-XepOpt:UngroupedOverloads:BatchFindings")) .doTest(); } @Test public void ungroupedOverloadsNegativeCases() { compilationHelper.addSourceFile("UngroupedOverloadsNegativeCases.java").doTest(); } @Test public void ungroupedOverloadsRefactoringComments() { refactoringHelper .addInput("UngroupedOverloadsRefactoringComments.java") .addOutput("UngroupedOverloadsRefactoringComments_expected.java") .doTest(); } @Test public void ungroupedOverloadsRefactoringMultiple() { refactoringHelper .addInput("UngroupedOverloadsRefactoringMultiple.java") .addOutput("UngroupedOverloadsRefactoringMultiple_expected.java") .doTest(); } @Test public void ungroupedOverloadsRefactoringInterleaved() { refactoringHelper .addInput("UngroupedOverloadsRefactoringInterleaved.java") .addOutput("UngroupedOverloadsRefactoringInterleaved_expected.java") .doTest(); } @Test public void ungroupedOverloadsRefactoringBelowCutoffLimit() { // Here we have 4 methods so refactoring should be applied. refactoringHelper .addInputLines( "in/BelowLimit.java", "class BelowLimit {", " BelowLimit() {}", " void foo() {}", " void bar() {}", " void foo(int x) {}", "}") .addOutputLines( "out/BelowLimit.java", "class BelowLimit {", " BelowLimit() {}", " void foo() {}", " void foo(int x) {}", " void bar() {}", "}") .doTest(); } @Test public void ungroupedOverloadsRefactoring_fiveMethods() { refactoringHelper .addInputLines( "in/AboveLimit.java", "class AboveLimit {", " AboveLimit() {}", " void foo() {}", " void bar() {}", " void foo(int x) {}", " void baz() {}", "}") .addOutputLines( "out/AboveLimit.java", "class AboveLimit {", " AboveLimit() {}", " void foo() {}", " void foo(int x) {}", " void bar() {}", " void baz() {}", "}") .doTest(); } @Ignore // TODO(b/71818169): fix and re-enable @Test public void staticAndNonStatic() { refactoringHelper .addInputLines( "Test.java", "class Test {", " void foo() {}", " void bar() {}", " static void foo(int x) {}", "}") .expectUnchanged() .doTest(); } @Test public void staticAndNonStaticInterspersed() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private void foo(int x) {}", " private static void foo(int x, int y, int z) {}", " private void foo(int x, int y) {}", "}") .doTest(); } @Test public void suppressOnAnyMethod() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void foo() {}", " void bar() {}", " @SuppressWarnings(\"UngroupedOverloads\") void foo(int x) {}", "}") .doTest(); } @Test public void javadoc() { refactoringHelper .addInputLines( "in/Test.java", "class Test {", " void foo() {}", " void bar() {}", " /** doc */", " void foo(int x) {}", "}") .addOutputLines( "out/Test.java", "class Test {", "", " void foo() {}", " /** doc */", " void foo(int x) {}", "", " void bar() {}", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void diagnostic() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: ungrouped overloads of 'foo' on line(s): 8, 10, 12", " private void foo() {}", " // BUG: Diagnostic contains: ungrouped overloads of 'foo' on line(s): 8, 10, 12", " private void foo(int a) {}", " private void bar() {}", " // BUG: Diagnostic contains: ungrouped overloads of 'foo' on line(s): 3, 5", " private void foo(int a, int b) {}", " // BUG: Diagnostic contains: ungrouped overloads of 'foo' on line(s): 3, 5", " private void foo(int a, int b, int c) {}", " // BUG: Diagnostic contains: ungrouped overloads of 'foo' on line(s): 3, 5", " private void foo(int a, int b, int c, int d) {}", "}") .doTest(); } @Test public void interleavedUngroupedOverloads() { refactoringHelper .addInputLines( "in/Test.java", "class Test {", " void foo() {", " System.err.println();", " }", "", " void bar() {", " System.err.println();", " }", "", " void foo(int x) {", " System.err.println();", " }", "", " void bar(int x) {", " System.err.println();", " }", "}") .addOutputLines( "out/Test.java", "class Test {", "", " void foo() {", " System.err.println();", " }", "", " void foo(int x) {", " System.err.println();", " }", "", " void bar() {", " System.err.println();", " }", "", " void bar(int x) {", " System.err.println();", " }", "}") .setArgs("-XepOpt:UngroupedOverloads:BatchFindings") .doTest(TestMode.TEXT_MATCH); } @Test public void describingConstructors() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: constructor overloads", " Test() {}", " private void bar() {}", " // BUG: Diagnostic contains: constructor overloads", " Test(int i) {}", "}") .doTest(); } @Test public void recordConstructor() { assumeTrue(RuntimeVersion.isAtLeast16()); compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "import java.util.Set;", "", "record MyRecord(ImmutableSet<String> strings) {", " MyRecord(Set<String> strings) {", " this(strings == null ? ImmutableSet.of() : ImmutableSet.copyOf(strings));", " }", "}") .doTest(); } }
9,468
29.349359
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/HidingFieldTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author mariasam@google.com (Maria Sam) * @author sulku@google.com (Marsela Sulku) */ @RunWith(JUnit4.class) public class HidingFieldTest { CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(HidingField.class, getClass()); } @Test public void hidingFieldPositiveCases() { compilationHelper .addSourceFile("HidingFieldPositiveCases1.java") .addSourceFile("HidingFieldPositiveCases2.java") .doTest(); } @Test public void hidingFieldNegativeCases() { compilationHelper.addSourceFile("HidingFieldNegativeCases.java").doTest(); } }
1,488
28.78
89
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnusedMethodTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link UnusedMethod}. */ @RunWith(JUnit4.class) public final class UnusedMethodTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(UnusedMethod.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(UnusedMethod.class, getClass()); @Test public void unusedNative() { helper .addSourceLines( "UnusedNative.java", "package unusedvars;", "public class UnusedNative {", " private native void aNativeMethod();", "}") .doTest(); } @Test public void unusedPrivateMethod() { helper .addSourceLines( "UnusedPrivateMethod.java", "package unusedvars;", "import com.google.errorprone.annotations.Keep;", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Retention;", "import java.lang.annotation.RetentionPolicy;", "import java.lang.annotation.Target;", "import javax.inject.Inject;", "public class UnusedPrivateMethod {", " public void test() {", " used();", " }", " private void used() {}", " // BUG: Diagnostic contains: Method 'notUsed' is never used.", " private void notUsed() {}", " @Inject", " private void notUsedExempted() {}", " @Keep", " @Target(ElementType.METHOD)", " @Retention(RetentionPolicy.SOURCE)", " private @interface ProvidesCustom {}", "}") .doTest(); } @Test public void unuseds() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "import java.io.IOException;", "import java.io.ObjectStreamException;", "import java.util.List;", "import javax.inject.Inject;", "public class Unuseds {", " // BUG: Diagnostic contains:", " private void notUsedMethod() {}", " // BUG: Diagnostic contains:", " private static void staticNotUsedMethod() {}", " @SuppressWarnings({\"deprecation\", \"unused\"})", " class UsesSuppressWarning {", " private int f1;", " private void test1() {", " int local;", " }", " @SuppressWarnings(value = \"unused\")", " private void test2() {", " int local;", " }", " }", "}") .doTest(); } @Test public void exemptedMethods() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "import java.io.IOException;", "import java.io.ObjectStreamException;", "public class Unuseds implements java.io.Serializable {", " private void readObject(java.io.ObjectInputStream in) throws IOException {", " in.hashCode();", " }", " private void writeObject(java.io.ObjectOutputStream out) throws IOException {", " out.writeInt(123);", " }", " private Object readResolve() {", " return null;", " }", " private void readObjectNoData() throws ObjectStreamException {}", "}") .doTest(); } @Test public void exemptedByName() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "class ExemptedByName {", " private void unused1(int a, int unusedParam) {", " int unusedLocal = a;", " }", "}") .doTest(); } @Test public void exemptedByCustomAnnotation() { helper .addSourceLines( "Foo.java", // "package example;", "@interface Foo {}") .addSourceLines( "ExemptedByCustomAnnotation.java", "package example;", "class ExemptedByCustomAnnotation {", " @Foo", " private void bar() {}", "}") .setArgs("-XepOpt:UnusedMethod:ExemptingMethodAnnotations=example.Foo") .doTest(); } @Test public void suppressions() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "class Suppressed {", " @SuppressWarnings({\"deprecation\", \"unused\"})", " class UsesSuppressWarning {", " private void test1() {", " int local;", " }", " @SuppressWarnings(value = \"unused\")", " private void test2() {", " int local;", " }", " }", "}") .doTest(); } @Test public void removal_javadocsAndNonJavadocs() { refactoringHelper .addInputLines( "UnusedWithComment.java", "package unusedvars;", "public class UnusedWithComment {", " /**", " * Method comment", " */private void test1() {", " }", " /** Method comment */", " private void test2() {", " }", " // Non javadoc comment", " private void test3() {", " }", "}") .addOutputLines( "UnusedWithComment.java", // "package unusedvars;", "public class UnusedWithComment {", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void usedInLambda() { helper .addSourceLines( "UsedInLambda.java", "package unusedvars;", "import java.util.Arrays;", "import java.util.List;", "import java.util.function.Function;", "import java.util.stream.Collectors;", "/** Method parameters used in lambdas and anonymous classes */", "public class UsedInLambda {", " private Function<Integer, Integer> usedInLambda() {", " return x -> 1;", " }", " private String print(Object o) {", " return o.toString();", " }", " public List<String> print(List<Object> os) {", " return os.stream().map(this::print).collect(Collectors.toList());", " }", " public static void main(String[] args) {", " System.err.println(new UsedInLambda().usedInLambda());", " System.err.println(new UsedInLambda().print(Arrays.asList(1, 2, 3)));", " }", "}") .doTest(); } @Test public void onlyForMethodReference() { helper .addSourceLines( "Test.java", "import java.util.function.Predicate;", "class Test {", " private static boolean foo(int a) {", " return true;", " }", " Predicate<Integer> pred = Test::foo;", "}") .doTest(); } @Test public void methodSource() { helper .addSourceLines( "MethodSource.java", "package org.junit.jupiter.params.provider;", "public @interface MethodSource {", " String[] value();", "}") .addSourceLines( "Test.java", "import java.util.stream.Stream;", "import org.junit.jupiter.params.provider.MethodSource;", "class Test {", " @MethodSource(\"parameters\")", " void test() {}", "", " private static Stream<String> parameters() {", " return Stream.of();", " }", "}") .doTest(); } @Test public void qualifiedMethodSource() { helper .addSourceLines( "MethodSource.java", "package org.junit.jupiter.params.provider;", "public @interface MethodSource {", " String[] value();", "}") .addSourceLines( "Test.java", "import java.util.stream.Stream;", "import org.junit.jupiter.params.provider.MethodSource;", "class Test {", " @MethodSource(\"Test#parameters\")", " void test() {}", "", "", " private static Stream<String> parameters() {", " return Stream.of();", " }", "}") .doTest(); } @Test public void nestedQualifiedMethodSource() { helper .addSourceLines( "MethodSource.java", "package org.junit.jupiter.params.provider;", "public @interface MethodSource {", " String[] value();", "}") .addSourceLines( "Test.java", "import java.util.stream.Stream;", "import org.junit.jupiter.params.provider.MethodSource;", "class Test {", " // @Nested", " public class NestedTest {", " @MethodSource(\"Test#parameters\")", " void test() {}", " }", "", " private static Stream<String> parameters() {", " return Stream.of();", " }", "}") .doTest(); } @Test public void overriddenMethodNotCalledWithinClass() { helper .addSourceLines( "Test.java", "class Test {", " private class Inner {", " @Override public String toString() { return null; }", " }", "}") .doTest(); } @Test public void methodWithinPrivateInnerClass_isEligible() { helper .addSourceLines( "Test.java", "class Test {", " private class Inner {", " // BUG: Diagnostic contains:", " public void foo() {}", " }", "}") .doTest(); } @Test public void unusedConstructor() { helper .addSourceLines( "Test.java", // "class Test {", " // BUG: Diagnostic contains: Constructor 'Test'", " private Test(int a) {}", "}") .doTest(); } @Test public void unusedConstructor_refactoredToPrivateNoArgVersion() { refactoringHelper .addInputLines( "Test.java", // "class Test {", " private Test(int a) {}", "}") .addOutputLines( "Test.java", // "class Test {", " private Test() {}", "}") .doTest(); } @Test public void unusedConstructor_finalFieldsLeftDangling_noFix() { refactoringHelper .addInputLines( "Test.java", // "class Test {", " private final int a;", " private Test(int a) {", " this.a = a;", " }", "}") .expectUnchanged() .doTest(); } @Test public void unusedConstructor_nonFinalFields_stillRefactored() { refactoringHelper .addInputLines( "Test.java", // "class Test {", " private int a;", " private Test(int a) {}", "}") .addOutputLines( "Test.java", // "class Test {", " private int a;", " private Test() {}", "}") .doTest(); } @Test public void unusedConstructor_removed() { refactoringHelper .addInputLines( "Test.java", // "class Test {", " private Test(int a) {}", " private Test(String a) {}", " public Test of() { return new Test(1); }", "}") .addOutputLines( "Test.java", // "class Test {", " private Test(int a) {}", " public Test of() { return new Test(1); }", "}") .doTest(); } @Test public void privateConstructor_calledWithinClass() { helper .addSourceLines( "Test.java", // "class Test {", " private Test(int a) {}", " public Test of(int a) {", " return new Test(a);", " }", "}") .doTest(); } @Test public void zeroArgConstructor_notFlagged() { helper .addSourceLines( "Test.java", // "class Test {", " private Test() {}", "}") .doTest(); } @Test public void annotationProperty_assignedByname() { helper .addSourceLines( "Test.java", "class Test {", " private @interface Anno {", " int value() default 1;", " }", " @Anno(value = 1) int b;", "}") .doTest(); } @Test public void annotationProperty_assignedAsDefault() { helper .addSourceLines( "Test.java", "class Test {", " private @interface Anno {", " int value();", " }", " @Anno(1) int a;", "}") .doTest(); } @Test public void effectivelyPrivateMethodMadeVisible() { helper .addSourceLines( "Test.java", "class Test {", " private class A {", " public void foo() {}", " }", " public class B extends A {}", "}") .doTest(); } @Test public void effectivelyPrivateMethodMadeVisible_bySubclassImplementingPublicInterface() { helper .addSourceLines( "Test.java", "class Test {", " private static class A {", " public void a() {}", " }", " public interface B {", " public void a();", " }", " public static final class C extends A implements B {}", "}") .doTest(); } }
15,226
28.452611
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ArraysAsListPrimitiveArrayTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ArraysAsListPrimitiveArray}Test */ @RunWith(JUnit4.class) public class ArraysAsListPrimitiveArrayTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ArraysAsListPrimitiveArray.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import java.util.Arrays;", "class Test {", "void f() {", " // BUG: Diagnostic contains: Booleans.asList(new boolean[0]);", " Arrays.asList(new boolean[0]);", " // BUG: Diagnostic contains: Bytes.asList(new byte[0]);", " Arrays.asList(new byte[0]);", " // BUG: Diagnostic contains: Shorts.asList(new short[0]);", " Arrays.asList(new short[0]);", " // BUG: Diagnostic contains: Chars.asList(new char[0]);", " Arrays.asList(new char[0]);", " // BUG: Diagnostic contains: Ints.asList(new int[0]);", " Arrays.asList(new int[0]);", " // BUG: Diagnostic contains: Longs.asList(new long[0]);", " Arrays.asList(new long[0]);", " // BUG: Diagnostic contains: Doubles.asList(new double[0]);", " Arrays.asList(new double[0]);", " // BUG: Diagnostic contains: Floats.asList(new float[0]);", " Arrays.asList(new float[0]);", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.Arrays;", "class Test {", "void f() {", " Arrays.asList(new Object());", " Arrays.asList(new Object[0]);", " Arrays.asList(new Integer[0]);", " }", "}") .doTest(); } }
2,683
34.315789
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AlwaysThrowsTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link AlwaysThrows}Test */ @RunWith(JUnit4.class) public class AlwaysThrowsTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(AlwaysThrows.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "Test.java", "import java.time.Instant;", "class T { ", " void f() {", " // BUG: Diagnostic contains: will fail at runtime with a DateTimeParseException", " Instant.parse(\"2007-12-3T10:15:30.00Z\");", " }", "}") .doTest(); } @Test public void immutableMapThrows() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "class Test {", " private static final ImmutableMap<Integer, Integer> xs =", " ImmutableMap.<Integer, Integer>builder()", " .put(1, 1)", " // BUG: Diagnostic contains:", " .put(1, 2)", " .buildOrThrow();", "}") .doTest(); } @Test public void immutableBiMapThrows() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableBiMap;", "class Test {", " private static final ImmutableBiMap<Integer, Integer> xs =", " ImmutableBiMap.<Integer, Integer>builder()", " .put(1, 1)", " // BUG: Diagnostic contains:", " .put(2, 1)", " .buildOrThrow();", "}") .doTest(); } @Test public void immutableMapDoesNotThrow() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "class Test {", " private static final ImmutableMap<Integer, Integer> xs =", " ImmutableMap.<Integer, Integer>builder()", " .put(1, 1)", " .put(2, 2)", " .buildOrThrow();", "}") .doTest(); } @Test public void immutableMapOfThrows() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "class Test {", " private static final ImmutableMap<Integer, Integer> xs =", " // BUG: Diagnostic contains:", " ImmutableMap.of(1, 1, 1, 2);", "}") .doTest(); } @Test public void immutableMapOfThrowsWithEnums() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "class Test {", " private enum E {A, B}", " private static final ImmutableMap<E, Integer> xs =", " // BUG: Diagnostic contains:", " ImmutableMap.of(E.A, 1, E.A, 2);", "}") .doTest(); } @Test public void immutableBiMapOfThrowsWithEnums() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "class Test {", " private enum E {A, B}", " private static final ImmutableMap<E, Integer> xs =", " // BUG: Diagnostic contains:", " ImmutableMap.of(E.A, 1, E.A, 2);", "}") .doTest(); } @Test public void immutableMapOfThrowsWithRepeatedFinalVariable() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableBiMap;", "class Test {", " ImmutableBiMap<String, Integer> map(String s) {", " // BUG: Diagnostic contains:", " return ImmutableBiMap.of(s, 1, s, 2);", " }", " ImmutableBiMap<Integer, String> values(String s) {", " // BUG: Diagnostic contains:", " return ImmutableBiMap.of(1, s, 2, s);", " }", "}") .doTest(); } @Test public void immutableMapWithComplexKeys() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "import java.time.Duration;", "class Test {", " private static final ImmutableMap<Duration, Integer> xs =", " // BUG: Diagnostic contains: Duration.ofMillis(1)", " ImmutableMap.of(Duration.ofMillis(1), 1, Duration.ofMillis(1), 2);", "}") .doTest(); } @Test public void uuidFromString() { testHelper .addSourceLines( "Test.java", "import java.util.UUID;", "class Test {", " // BUG: Diagnostic contains:", " private final UUID uuid = UUID.fromString(\"foo\");", "}") .doTest(); } }
5,805
30.215054
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BanSerializableReadTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link BanSerializableRead}Test */ @RunWith(JUnit4.class) public class BanSerializableReadTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(BanSerializableRead.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(BanSerializableRead.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("BanSerializableReadPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("BanSerializableReadNegativeCases.java").doTest(); } @Test public void negativeCaseUnchanged() { refactoringHelper .addInput("BanSerializableReadNegativeCases.java") .expectUnchanged() .setArgs("-XepCompilingTestOnlyCode") .doTest(); } }
1,745
31.943396
89
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MissingOverrideTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.common.collect.ImmutableList; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link MissingOverride}Test */ @RunWith(JUnit4.class) public class MissingOverrideTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MissingOverride.class, getClass()); @Test public void simple() { compilationHelper .addSourceLines( "Super.java", // "public class Super {", " void f() {}", "}") .addSourceLines( "Test.java", "public class Test extends Super {", " // BUG: Diagnostic contains: f overrides method in Super; expected @Override", " public void f() {}", "}") .doTest(); } @Test public void abstractMethod() { compilationHelper .addSourceLines( "Super.java", // "public abstract class Super {", " abstract void f();", "}") .addSourceLines( "Test.java", "public class Test extends Super {", " // BUG: Diagnostic contains: f implements method in Super; expected @Override", " public void f() {}", "}") .doTest(); } @Test public void generatedMethod() { compilationHelper .addSourceLines( "Test.java", // "import javax.annotation.processing.Generated;", "@Generated(\"foo\")", "public abstract class Test {", " public abstract int hashCode();", "}") .doTest(); } @Test public void interfaceMethod() { compilationHelper .addSourceLines( "Super.java", // "interface Super {", " void f();", "}") .addSourceLines( "Test.java", "public class Test implements Super {", " // BUG: Diagnostic contains: f implements method in Super; expected @Override", " public void f() {}", "}") .doTest(); } @Test public void bothStatic() { compilationHelper .addSourceLines( "Super.java", // "public class Super {", " static void f() {}", "}") .addSourceLines( "Test.java", // "public class Test extends Super {", " static public void f() {}", "}") .doTest(); } @Test public void deprecatedMethod() { compilationHelper .addSourceLines( "Super.java", // "public class Super {", " @Deprecated void f() {}", "}") .addSourceLines( "Test.java", // "public class Test extends Super {", " public void f() {}", "}") .doTest(); } @Test public void interfaceOverride() { compilationHelper .addSourceLines( "Super.java", // "interface Super {", " void f();", "}") .addSourceLines( "Test.java", "public interface Test extends Super {", " // BUG: Diagnostic contains: f implements method in Super; expected @Override", " void f();", "}") .doTest(); } @Test public void ignoreInterfaceOverride() { compilationHelper .setArgs(ImmutableList.of("-XepOpt:MissingOverride:IgnoreInterfaceOverrides=true")) .addSourceLines( "Super.java", // "interface Super {", " void f();", "}") .addSourceLines( "Test.java", // "public interface Test extends Super {", " void f();", "}") .doTest(); } }
4,548
27.080247
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ParameterNameTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ParameterName}Test */ @RunWith(JUnit4.class) public class ParameterNameTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(ParameterName.class, getClass()); @Test public void positive() { BugCheckerRefactoringTestHelper.newInstance(ParameterName.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " void f(int foo, int bar) {}", " {", " f(/* bar= */ 1, /* foo= */ 2);", " f(/** bar= */ 3, /** foo= */ 4);", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " void f(int foo, int bar) {}", " {", " f(/* foo= */ 1, /* bar= */ 2);", " f(/* foo= */ 3, /* bar= */ 4);", " }", "}") .doTest(TEXT_MATCH); } @Test public void negative() { testHelper .addSourceLines( "Test.java", "class Test {", " void f(int foo, int bar) {}", " {", " f(/* foo= */ 1, 2);", " }", "}") .doTest(); } @Test public void issue781() { testHelper .addSourceLines( "a/Baz.java", "package a.b;", "import a.AbstractFoo;", "class Baz extends AbstractFoo {", " @Override", " protected String getFoo() {", " return \"foo\";", " }", "}") .addSourceLines( "a/AbstractFoo.java", "package a;", "import java.util.function.Function;", "class Bar {", " private final Function<String, String> args;", " public Bar(Function<String, String> args) {", " this.args = args;", " }", "}", "public abstract class AbstractFoo {", " protected abstract String getFoo();", " private String getCommandArguments(String parameters) {", " return null;", " }", " public AbstractFoo() {", " new Bar(this::getCommandArguments);", " }", "}") .doTest(); } @Test public void issue792() { testHelper .addSourceLines( "a/Foo.java", "package a;", "class Bar {", "}", "public class Foo {", " public void setInteger(Integer i) {", " }", " public void callSetInteger() {", " setInteger(0);", " }", "}") .addSourceLines("a/Baz.java", "package a;", "public class Baz extends Foo {", "}") .doTest(); } @Test public void namedParametersChecker_ignoresCall_withNoComments() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " target(arg1, arg2);", " }", "}") .doTest(); } @Test public void namedParametersChecker_findsError_withOneBadComment() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " // BUG: Diagnostic contains: 'target(/* param1= */arg1, arg2);'", " target(/* param2= */arg1, arg2);", " }", "}") .doTest(); } @Test // not allowed by Google style guide, but other styles may want this public void namedParametersChecker_findsError_withUnusualIdentifier() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object $param$);", " void test(Object arg) {", " // BUG: Diagnostic contains: 'target(/* $param$= */arg);'", " target(/* param= */arg);", " }", "}") .doTest(); } @Test public void namedParametersChecker_suggestsSwap_withSwappedArgs() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " // BUG: Diagnostic contains: 'target(/* param1= */arg2", " target(/* param2= */arg2, /* param1= */arg1);", " }", "}") .doTest(); } @Test public void namedParametersChecker_suggestsSwap_withOneCommentedSwappedArgs() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " // BUG: Diagnostic contains: 'target(/* param1= */arg2, arg1);'", " target(/* param2= */arg2, arg1);", " }", "}") .doTest(); } @Test public void namedParametersChecker_toleratesApproximateComment_onRequiredNamesMethod() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(/*note param = */arg);", " }", "}") .doTest(); } @Test public void namedParametersChecker_tolerateComment_withNoEquals() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(/*param*/arg);", " }", "}") .doTest(); } @Test public void namedParametersChecker_toleratesMatchingComment_blockAfter() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(arg/*param*/);", " }", "}") .doTest(); } @Test public void namedParametersChecker_toleratesApproximateComment_blockAfter() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(arg/*imprecise match for param*/);", " }", "}") .doTest(); } @Test public void namedParametersChecker_toleratesMatchingComment_lineAfter() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(arg); //param", " }", "}") .doTest(); } /** * We allow multiple comments if any one of them is right. This helps libraries migrate to a new * parameter name gradually without breaking any builds: update the caller to use both names, then * update the API, then remove the old name. */ @Test public void namedParametersChecker_multipleComments_allowedIfAnyMatch() { testHelper .addSourceLines( "Test.java", "class Test {", " void test(Object x) {", " test(/* y= */ /* x= */ x);", " test(/* x= */ /* y= */ x);", " }", "}") .doTest(); } @Test public void namedParametersChecker_multipleComments_flaggedIfNoneMatch() { testHelper .addSourceLines( "Test.java", "class Test {", " void test(Object x) {", " // BUG: Diagnostic contains: does not match", " test(/* y= */ /* z= */ x);", " }", "}") .doTest(); } @Test public void namedParametersChecker_ignoresComment_nonMatchinglineAfter() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(arg); // some_other_comment", " }", "}") .doTest(); } @Test public void namedParametersChecker_ignoresComment_markedUpDelimiter() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " target(arg1,", " /* ---- param1 <-> param2 ---- */", " arg2);", " }", "}") .doTest(); } @Test public void namedParametersChecker_ignoresLineComments() { testHelper .addSourceLines( "Test.java", "class Test {", " void test(int x) {", " test(", " // newX =", " // (x ^ 2)", " x * x);", " }", "}") .doTest(); } @Test public void namedParametersChecker_ignoresComment_wrongNameWithNoEquals() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(/* some_other_comment */arg);", " }", "}") .doTest(); } @Test public void namedParametersChecker_ignoresComment_wrongVarargs() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object... param);", " void test(Object arg) {", " target(/* param.!.= */arg);", " }", "}") .doTest(); } @Test public void namedParametersChecker_matchesComment_withChainedMethod() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract Test getTest(Object param);", " abstract void target(Object param2);", " void test(Object arg, Object arg2) {", " getTest(/* param= */arg).target(arg2);", " }", "}") .doTest(); } @Test public void namedParametersChecker_suggestsChangeComment_whenNoMatchingNames() { testHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " // BUG: Diagnostic contains:", " // target(/* param1= */arg1, arg2)", " // `/* notMatching= */` does not match formal parameter name `param1`", " target(/* notMatching= */arg1, arg2);", " }", "}") .doTest(); } /** A test for inner class constructor parameter names across compilation boundaries. */ public static class InnerClassTest { /** An inner class. */ public class Inner { public Inner(int foo, int bar) {} // this is a (non-static) inner class on purpose { System.err.println(InnerClassTest.this); } } } @Test public void innerClassNegative() { testHelper .addSourceLines( "Test.java", "import " + InnerClassTest.class.getCanonicalName() + ";", "class Test {", " {", " new InnerClassTest().new Inner(/* foo= */ 1, /* bar= */ 2);", " }", "}") .doTest(); } @Ignore // see b/64954766 @Test public void innerClassPositive() { testHelper .addSourceLines( "Test.java", "import " + InnerClassTest.class.getCanonicalName() + ";", "class Test {", " {", " // BUG: Diagnostic contains:", " new InnerClassTest().new Inner(/* bar= */ 1, /* foo= */ 2);", " }", "}") .doTest(); } /** A test for anonymous class constructors across compilation boundaries. */ public static class Foo { public Foo(int foo, int bar) {} } @Test public void anonymousClassConstructorNegative() { testHelper .addSourceLines( "Test.java", "import " + Foo.class.getCanonicalName() + ";", "class Test {", " {", " new Foo(/* foo= */ 1, /* bar= */ 2) {", " };", " }", "}") .doTest(); } @Ignore // see b/65065109 @Test public void anonymousClassConstructor() { testHelper .addSourceLines( "Test.java", "import " + Foo.class.getCanonicalName() + ";", "class Test {", " {", " // BUG: Diagnostic contains:", " new Foo(/* bar= */ 1, /* foo= */ 2) {", " };", " }", "}") .doTest(); } @Test public void internalAnnotatedParameterNegative() { testHelper .addSourceLines( "Test.java", "class Test {", " public static class AnnotatedParametersTestClass {", " public @interface Annotated {}", " public static void target(@Annotated int foo) {}", " }", " void test() {", " AnnotatedParametersTestClass.target(/* foo= */ 1);", " }", "}") .doTest(); } @Test public void internalAnnotatedParameterPositive() { testHelper .addSourceLines( "Test.java", "class Test {", " public static class AnnotatedParametersTestClass {", " public @interface Annotated {}", " public static void target(@Annotated int foo) {}", " }", " void test() {", " // BUG: Diagnostic contains: target(/* foo= */ 1)", " AnnotatedParametersTestClass.target(/* bar= */ 1);", " }", "}") .doTest(); } /** A test for annotated parameters across compilation boundaries. */ public static final class AnnotatedParametersTestClass { /** An annotation to apply to method parameters. */ public @interface Annotated {} public static void target(@Annotated int foo) {} private AnnotatedParametersTestClass() {} } @Test public void externalAnnotatedParameterNegative() { testHelper .addSourceLines( "Test.java", "import " + AnnotatedParametersTestClass.class.getCanonicalName() + ";", "class Test {", " void test() {", " AnnotatedParametersTestClass.target(/* foo= */ 1);", " }", "}") .doTest(); } @Ignore // TODO(b/67993065): remove @Ignore after the issue is fixed. @Test public void externalAnnotatedParameterPositive() { testHelper .addSourceLines( "Test.java", "import " + AnnotatedParametersTestClass.class.getCanonicalName() + ";", "class Test {", " void test() {", " // BUG: Diagnostic contains: target(/* foo= */ 1)", " AnnotatedParametersTestClass.target(/* bar= */ 1);", " }", "}") .doTest(); } @Test public void positiveVarargs() { testHelper .addSourceLines( "Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " // BUG: Diagnostic contains: /* args...= */", " // /* argh */", " foo(/* argh...= */ 1, 2, 3);", " }", "}") .doTest(); } @Test public void emptyVarargs_shouldNotCrash() { testHelper .addSourceLines( "Test.java", "class Test {", " void foo(int first, int... rest) {}", "", " void bar() {", " foo(/* first= */ 1);", " // BUG: Diagnostic contains: /* first= */", " foo(/* second= */ 1);", " }", "}") .doTest(); } @Test public void negativeVarargs() { testHelper .addSourceLines( "Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " foo(/* args...= */ 1, 2);", " }", "}") .doTest(); } @Test public void varargsCommentAllowedWithArraySyntax() { testHelper .addSourceLines( "Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " int[] myInts = {1, 2, 3};", " foo(/* args...= */ myInts);", " }", "}") .doTest(); } // TODO(b/144728869): clean up existing usages with non-"..." syntax @Test public void normalCommentNotAllowedWithVarargsArraySyntax() { testHelper .addSourceLines( "Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " int[] myInts = {1, 2, 3};", " // BUG: Diagnostic contains: /* args...= */", " foo(/* args= */ myInts);", " }", "}") .doTest(); } @Test public void varargsCommentAllowedOnOnlyFirstArg() { testHelper .addSourceLines( "Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " // BUG: Diagnostic contains: parameter name comment only allowed on first varargs" + " argument", " foo(1, /* args...= */ 2);", " }", "}") .doTest(); } @Test public void varargsWrongFormat() { BugCheckerRefactoringTestHelper.newInstance(ParameterName.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " foo(/* args= */ 1, 2);", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " foo(/* args...= */ 1, 2);", " }", "}") .doTest(TEXT_MATCH); } @Test public void varargsTrailing() { BugCheckerRefactoringTestHelper.newInstance(ParameterName.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " foo(1, /* foo= */ 2);", " foo(1, /* foo...= */ 2);", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " foo(1, /* foo */ 2);", " foo(1, /* foo... */ 2);", " }", "}") .doTest(TEXT_MATCH); } @Test public void varargsIgnoreNonParameterNameComments() { testHelper .addSourceLines( "Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " foo(/* fake */ 1, 2);", " }", "}") .doTest(); } @Test public void varargsWrongNameAndWrongFormat() { testHelper .addSourceLines( "Test.java", "class Test {", " void foo(int... args) {}", "", " void bar() {", " // BUG: Diagnostic contains: /* args...= */", " // /* argh */", " foo(/* argh= */ 1, 2);", " }", "}") .doTest(); } @Test public void varargsCommentNotAllowedOnNormalArg() { testHelper .addSourceLines( "Test.java", "class Test {", " void foo(int i) {}", "", " void bar() {", " // BUG: Diagnostic contains: /* i= */", " foo(/* i...= */ 1);", " }", "}") .doTest(); } /** A test input for separate compilation. */ public static final class Holder { public static void varargsMethod(int... values) {} private Holder() {} } /** Regression test for b/147344912. */ @Test public void varargsSeparateCompilation() { testHelper .addSourceLines( "Test.java", "import " + Holder.class.getCanonicalName() + ";", "class Test {", " void bar() {", " Holder.varargsMethod(/* values...= */ 1, 1, 1);", " }", "}") .withClasspath(Holder.class, ParameterNameTest.class) .doTest(); } @Test public void exemptPackage() { CompilationTestHelper.newInstance(ParameterName.class, getClass()) .addSourceLines( "test/a/A.java", "package test.a;", "public class A {", " public static void f(int value) {}", "}") .addSourceLines( "test/b/nested/B.java", "package test.b.nested;", "public class B {", " public static void f(int value) {}", "}") .addSourceLines( "test/c/C.java", "package test.c;", "public class C {", " public static void f(int value) {}", "}") .addSourceLines( "Test.java", "import test.a.A;", "import test.b.nested.B;", "import test.c.C;", "class Test {", " void f() {", " A.f(/* typo= */ 1);", " B.f(/* typo= */ 1);", " // BUG: Diagnostic contains: 'C.f(/* value= */ 1);'", " C.f(/* typo= */ 1);", " }", "}") .setArgs(ImmutableList.of("-XepOpt:ParameterName:exemptPackagePrefixes=test.a,test.b")) .doTest(); } }
23,935
28.013333
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryTestMethodPrefixTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class UnnecessaryTestMethodPrefixTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(UnnecessaryTestMethodPrefix.class, getClass()); @Test public void positive() { helper .addInputLines( "T.java", "import org.junit.Test;", "class T {", " @Test public void testFoo() {}", "}") .addOutputLines( "T.java", // "import org.junit.Test;", "class T {", " @Test public void foo() {}", "}") .doTest(); } @Test public void negative() { helper .addInputLines( "T.java", // "import org.junit.Test;", "class T {", " @Test public void foo() {}", "}") .addOutputLines( "T.java", // "import org.junit.Test;", "class T {", " @Test public void foo() {}", "}") .doTest(); } @Test public void namedTest_noRename() { helper .addInputLines( "T.java", // "import org.junit.Test;", "class T {", " @Test public void test() {}", "}") .expectUnchanged() .doTest(); } }
2,154
26.628205
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LambdaFunctionalInterfaceTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link LambdaFunctionalInterface}Test */ @RunWith(JUnit4.class) public class LambdaFunctionalInterfaceTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(LambdaFunctionalInterface.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(LambdaFunctionalInterface.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("LambdaFunctionalInterfacePositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("LambdaFunctionalInterfaceNegativeCases.java").doTest(); } @Test public void refactoringTwo() { refactoringHelper .addInputLines( "in/TwoLambdaFunctions.java", "import java.util.function.Function;", " public class TwoLambdaFunctions {", " private static double find(Function<Double, Long> firstSpecial, ", " Function<Integer, Long> secondSpecial, double mid) {", " secondSpecial.apply(2);", " return firstSpecial.apply(mid);", " }", " public Double getMu() {", " return find(mu -> 0L, nu -> 1L, 3.0);", " }", " public Double getTu() {", " return find(mu -> 2L, nu -> 3L,4.0);", " }", " }") .addOutputLines( "out/TwoLambdaFunctions.java", "import java.util.function.DoubleToLongFunction;", " import java.util.function.Function;", " import java.util.function.IntToLongFunction;", " public class TwoLambdaFunctions {", " private static double find(DoubleToLongFunction firstSpecial, ", " IntToLongFunction secondSpecial, double mid) {", " secondSpecial.applyAsLong(2);", " return firstSpecial.applyAsLong(mid);", " }", " public Double getMu() {", " return find(mu -> 0L, nu -> 1L, 3.0);", " }", " public Double getTu() {", " return find(mu -> 2L, nu -> 3L,4.0);", " }", " }") .setFixChooser(FixChoosers.FIRST) .doTest(); } @Test public void refactoringInteger() { refactoringHelper .addInputLines( "in/TwoLambdaFunctions.java", "import java.util.function.Function;", " public class TwoLambdaFunctions {", " private static int find(Function<Integer, Integer> firstSpecial, ", "Function<Integer, Double> secondSpecial, int mid) {", " secondSpecial.apply(2);", " return firstSpecial.apply(mid);", " }", " public Integer getMu() {", " return find(mu -> 0, nu -> 1.1, 3);", " }", " public Integer getTu() {", " return find(mu -> 2, nu -> 3.2, 4);", " }", " }") .addOutputLines( "out/TwoLambdaFunctions.java", " import java.util.function.Function;", " import java.util.function.IntFunction;", " import java.util.function.IntToDoubleFunction;", " public class TwoLambdaFunctions {", " private static int find(IntFunction<Integer> firstSpecial, ", " IntToDoubleFunction secondSpecial, int mid) {", " secondSpecial.applyAsDouble(2);", " return firstSpecial.apply(mid);", " }", " public Integer getMu() {", " return find(mu -> 0, nu -> 1.1, 3);", " }", " public Integer getTu() {", " return find(mu -> 2, nu -> 3.2, 4);", " }", " }") .setFixChooser(FixChoosers.FIRST) .doTest(); } @Test public void refactoringPrimitiveToGeneric() { refactoringHelper .addInputLines( "in/NumbertoT.java", "import java.util.function.Function;", " import java.util.ArrayList; ", " import java.util.List; ", " public class NumbertoT { ", " private static <T extends Number> List<T> numToTFunction(Function<Double, T>", " converter) { ", " List<T> namedNumberIntervals = new ArrayList<>(); ", " T min = converter.apply(2.9); ", " T max = converter.apply(5.6); ", " namedNumberIntervals.add(min); ", " namedNumberIntervals.add(max); ", " return namedNumberIntervals; ", " } ", " public List<Integer> getIntList() { ", " List<Integer> result = numToTFunction(num -> 2); ", " return result; ", " } ", " public List<Double> getDoubleList() { ", " List<Double> result = numToTFunction(num -> 3.2); ", " return result; ", " } ", " }") .addOutputLines( "out/NumbertoT.java", " import java.util.ArrayList; ", " import java.util.List; ", " import java.util.function.DoubleFunction;", " import java.util.function.Function;", " public class NumbertoT { ", " private static <T extends Number> List<T> numToTFunction(DoubleFunction<T> ", " converter) {", " List<T> namedNumberIntervals = new ArrayList<>(); ", " T min = converter.apply(2.9); ", " T max = converter.apply(5.6); ", " namedNumberIntervals.add(min); ", " namedNumberIntervals.add(max); ", " return namedNumberIntervals; ", " } ", " public List<Integer> getIntList() { ", " List<Integer> result = numToTFunction(num -> 2); ", " return result; ", " } ", " public List<Double> getDoubleList() { ", " List<Double> result = numToTFunction(num -> 3.2); ", " return result; ", " } ", " }") .setFixChooser(FixChoosers.FIRST) .doTest(); } @Test public void refactoringGenericToPrimitive() { refactoringHelper .addInputLines( "in/NumbertoT.java", "import java.util.function.Function;", " public class NumbertoT { ", " private <T> int sumAll(Function<T, Integer> sizeConv) {", " return sizeConv.apply((T) Integer.valueOf(3));", " }", " public int getSumAll() {", " return sumAll(o -> 2);", " } ", " }") .addOutputLines( "out/NumbertoT.java", " import java.util.function.Function;", " import java.util.function.ToIntFunction;", " public class NumbertoT { ", " private <T> int sumAll(ToIntFunction<T> sizeConv) {", " return sizeConv.applyAsInt((T) Integer.valueOf(3));", " }", " public int getSumAll() {", " return sumAll(o -> 2);", " } ", " }") .setFixChooser(FixChoosers.FIRST) .doTest(); } @Test public void onEnum() { compilationHelper .addSourceLines( "E.java", "import java.util.function.Function;", "public enum E {", " VALUE(String::length);", " // BUG: Diagnostic contains:", " E(Function<String, Integer> func) {}", "}") .doTest(); } }
8,910
38.255507
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnsynchronizedOverridesSynchronizedTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link UnsynchronizedOverridesSynchronized}Test */ @RunWith(JUnit4.class) public class UnsynchronizedOverridesSynchronizedTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnsynchronizedOverridesSynchronized.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "test/Super.java", // "package test;", "class Super {", " synchronized void f() {}", "}") .addSourceLines( "test/Test.java", "package test;", "class Test extends Super {", " int counter;", " // BUG: Diagnostic contains: f overrides synchronized method in Super", " // synchronized void f()", " void f() {", " counter++;", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "test/Super.java", // "package test;", "class Super {", " synchronized void f() {}", "}") .addSourceLines( "test/Test.java", "package test;", "class Test extends Super {", " int counter;", " synchronized void f() {", " counter++;", " }", "}") .doTest(); } @Test public void ignoreInputStream() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "import java.io.InputStream;", "import java.io.IOException;", "class Test extends InputStream {", " @Override public int read() throws IOException {", " throw new IOException();", " }", " @Override public /*unsynchronized*/ void mark(int readlimit) {}", "}") .doTest(); } @Test public void callsSuperWithOtherStatements() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "class Test {", " class B extends Throwable {", " // BUG: Diagnostic contains:", " public Throwable getCause() {", " System.err.println();", " return super.getCause();", " }", " }", " class C extends Throwable {", " // BUG: Diagnostic contains:", " public Exception getCause() {", " System.err.println();", " return (Exception) super.getCause();", " }", " }", "}") .doTest(); } @Test public void ignoreDelegatesToSuper() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "class Test {", " class B extends Throwable {", " public Throwable getCause() {", " return super.getCause();", " }", " }", " class C extends Throwable {", " public Exception getCause() {", " return (Exception) super.getCause();", " }", " }", "}") .doTest(); } @Test public void ignoreEmptyOverride() { compilationHelper .addSourceLines( "test/Lib.java", "package test;", "class Lib {", " public synchronized void f() {}", "}") .addSourceLines( "test/Test.java", "package test;", "class Test {", " class B extends Lib {", " public void f() {", " }", " }", " class C extends Lib {", " public void f() {", " super.f();", " }", " }", " class D extends Lib {", " public void f() {", " return;", " }", " }", "}") .doTest(); } @Test public void ignoreOverrideThatReturnsThis() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "abstract class Test extends Throwable {", " @Override", " public Throwable fillInStackTrace() {", " return this;", " }", "}") .doTest(); } @Test public void ignoreOverrideThatReturnsConstant() { compilationHelper .addSourceLines( "A.java", // "class A {", " synchronized int f() {", " return -1;", " }", "}") .addSourceLines( "B.java", "class B extends A {", " @Override", " public int f() {", " return 42;", " }", "}") .doTest(); } }
5,850
27.541463
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CheckNotNullMultipleTimesTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link CheckNotNullMultipleTimes}. */ @RunWith(JUnit4.class) public final class CheckNotNullMultipleTimesTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(CheckNotNullMultipleTimes.class, getClass()); @Test public void positive() { helper .addSourceLines( "Test.java", "import static com.google.common.base.Preconditions.checkNotNull;", "class Test {", " Test(Integer a, Integer b) {", " checkNotNull(a);", " // BUG: Diagnostic contains:", " checkNotNull(a);", " }", "}") .doTest(); } @Test public void negative() { helper .addSourceLines( "Test.java", "import static com.google.common.base.Preconditions.checkNotNull;", "class Test {", " Test(Integer a, Integer b) {", " checkNotNull(a);", " checkNotNull(b);", " }", "}") .doTest(); } @Test public void conditional_noError() { helper .addSourceLines( "Test.java", "import static com.google.common.base.Preconditions.checkNotNull;", "class Test {", " Test(Integer a) {", " if (hashCode() > 0) {", " checkNotNull(a);", " } else {", " checkNotNull(a);", " }", " }", "}") .doTest(); } @Test public void assignedTwice_noError() { helper .addSourceLines( "Test.java", "import static com.google.common.base.Preconditions.checkNotNull;", "class Test {", " int a;", " Test(Integer a) {", " this.a = checkNotNull(a);", " checkNotNull(a);", " }", "}") .doTest(); } @Test public void withinTryAndCatch_noError() { helper .addSourceLines( "Test.java", "import static com.google.common.base.Preconditions.checkNotNull;", "class Test {", " Test(Integer a) {", " try {", // There could be intervening lines here which would throw, leading to the first check // not being reached. " checkNotNull(a);", " } catch (Exception e) {", " checkNotNull(a);", " }", " }", "}") .doTest(); } }
3,366
28.535088
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CollectionToArraySafeParameterTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author mariasam@google.com (Maria Sam) on 6/27/17. */ @RunWith(JUnit4.class) public class CollectionToArraySafeParameterTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(CollectionToArraySafeParameter.class, getClass()); @Test public void positiveCases() { compilationHelper.addSourceFile("CollectionToArraySafeParameterPositiveCases.java").doTest(); } @Test public void negativeCases() { compilationHelper.addSourceFile("CollectionToArraySafeParameterNegativeCases.java").doTest(); } // regression test for b/67022899 @Test public void b67022899() { compilationHelper .addSourceLines( "Test.java", "import java.util.Collection;", "class Test {", " <C extends Collection<Integer>> void f(C cx) {", " cx.toArray(new Integer[0]);", " }", "}") .doTest(); } }
1,754
30.339286
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ParametersButNotParameterizedTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link ParametersButNotParameterized}. */ @RunWith(JUnit4.class) public final class ParametersButNotParameterizedTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(ParametersButNotParameterized.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(ParametersButNotParameterized.class, getClass()); @Test public void positive() { refactoringHelper .addInputLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.junit.runners.Parameterized.Parameter;", "@RunWith(JUnit4.class)", "public class Test {", " @Parameter public int foo;", "}") .addOutputLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.junit.runners.Parameterized;", "import org.junit.runners.Parameterized.Parameter;", "@RunWith(Parameterized.class)", "public class Test {", " @Parameter public int foo;", "}") .doTest(); } @Test public void alreadyParameterized_noFinding() { helper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.Parameterized;", "import org.junit.runners.Parameterized.Parameter;", "@RunWith(Parameterized.class)", "public class Test {", " @Parameter public int foo;", "}") .doTest(); } @Test public void noParameters_noFinding() { helper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", "}") .doTest(); } }
2,901
32.744186
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AsyncFunctionReturnsNullTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link AsyncFunctionReturnsNull}. */ @RunWith(JUnit4.class) public class AsyncFunctionReturnsNullTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(AsyncFunctionReturnsNull.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("AsyncFunctionReturnsNullPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("AsyncFunctionReturnsNullNegativeCases.java").doTest(); } }
1,330
32.275
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/PublicApiNamedStreamShouldReturnStreamTest.java
/* * Copyright 2021 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link PublicApiNamedStreamShouldReturnStream}. */ @RunWith(JUnit4.class) public class PublicApiNamedStreamShouldReturnStreamTest { private CompilationTestHelper compilationHelper; @Before public void setup() { compilationHelper = CompilationTestHelper.newInstance(PublicApiNamedStreamShouldReturnStream.class, getClass()); } @Test public void abstractMethodPositiveCase() { compilationHelper .addSourceLines( "in/Test.java", "public abstract class Test {", " // BUG: Diagnostic contains: PublicApiNamedStreamShouldReturnStream", " public abstract int stream();", "}") .doTest(); } @Test public void regularMethodPositiveCase() { compilationHelper .addSourceLines( "in/Test.java", "public class Test {", " // BUG: Diagnostic contains: PublicApiNamedStreamShouldReturnStream", " public String stream() { return \"hello\";}", "}") .doTest(); } @Test public void compliantNegativeCase() { compilationHelper .addSourceLines( "in/Test.java", "import java.util.stream.Stream;", "public abstract class Test {", " public abstract Stream<Integer> stream();", "}") .doTest(); } @Test public void differentNameNegativeCase() { compilationHelper .addSourceLines( "in/Test.java", "public class Test {", " public int differentMethodName() { return 0; }", "}") .doTest(); } @Test public void privateMethodNegativeCase() { compilationHelper .addSourceLines( "in/Test.java", "public class Test {", " private String stream() { return \"hello\"; }", "}") .doTest(); } @Test public void returnTypeEndingWithStreamNegativeCase() { compilationHelper .addSourceLines( "in/Test.java", "public class Test {", " private static class TestStream {}", " public TestStream stream() { return new TestStream(); }", "}") .doTest(); } @Test public void returnTypeNotEndingWithStreamPositiveCase() { compilationHelper .addSourceLines( "in/Test.java", "public class Test {", " private static class TestStreamRandomSuffix {}", " // BUG: Diagnostic contains: PublicApiNamedStreamShouldReturnStream", " public TestStreamRandomSuffix stream() { return new TestStreamRandomSuffix(); }", "}") .doTest(); } }
3,544
28.541667
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RemoveUnusedImportsTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author gak@google.com (Gregory Kick) */ @RunWith(JUnit4.class) public class RemoveUnusedImportsTest { private BugCheckerRefactoringTestHelper testHelper; @Before public void setUp() { this.testHelper = BugCheckerRefactoringTestHelper.newInstance(RemoveUnusedImports.class, getClass()); } @Test public void basicUsageTest() { testHelper .addInputLines( "in/Test.java", "import static java.util.Collections.emptyList;", "import static java.util.Collections.emptySet;", "import static com.google.common.base.Preconditions.checkNotNull;", "", "import java.util.ArrayList;", "import java.util.Collection;", "import java.util.Collections;", "import java.util.HashSet;", "import java.util.List;", "import java.util.Map;", "import java.util.Set;", "import java.util.UUID;", "public class Test {", " private final Object object;", "", " Test(Object object) {", " this.object = checkNotNull(object);", " }", "", " Set<UUID> someMethod(Collection<UUID> collection) {", " if (collection.isEmpty()) {", " return emptySet();", " }", " return new HashSet<>(collection);", " }", "}") .addOutputLines( "out/Test.java", "import static java.util.Collections.emptySet;", "import static com.google.common.base.Preconditions.checkNotNull;", "", "import java.util.Collection;", "import java.util.HashSet;", "import java.util.Set;", "import java.util.UUID;", "public class Test {", " private final Object object;", "", " Test(Object object) {", " this.object = checkNotNull(object);", " }", "", " Set<UUID> someMethod(Collection<UUID> collection) {", " if (collection.isEmpty()) {", " return emptySet();", " }", " return new HashSet<>(collection);", " }", "}") .doTest(); } @Test public void useInSelect() { testHelper .addInputLines( "in/Test.java", "import java.util.Map;", "import java.util.Map.Entry;", "public class Test {", " Map.Entry<String, String> e;", "}") .addOutputLines( "out/Test.java", "import java.util.Map;", "public class Test {", " Map.Entry<String, String> e;", "}") .doTest(); } @Test public void useInJavadocSee() { testHelper .addInputLines( "in/Test.java", // "import java.util.Map;", "/** @see Map */", "public class Test {}") .expectUnchanged() .doTest(); } @Test public void useInJavadocSeeSelect() { testHelper .addInputLines( "in/Test.java", // "import java.util.Map;", "/** @see Map#get */", "public class Test {}") .expectUnchanged() .doTest(); } @Test public void useInJavadocLink() { testHelper .addInputLines( "in/Test.java", // "import java.util.Map;", "/** {@link Map} */", "public class Test {}") .expectUnchanged() .doTest(); } @Test public void useInJavadocLink_selfReferenceDoesNotBreak() { testHelper .addInputLines( "in/Test.java", // "/** {@link #blah} */", "public class Test {", " void blah() {}", "}") .expectUnchanged() .doTest(); } @Test public void useInJavadocLinkSelect() { testHelper .addInputLines( "in/Test.java", "import java.util.Map;", "/** {@link Map#get} */", "public class Test {}") .expectUnchanged() .doTest(); } @Test public void diagnosticPosition() { CompilationTestHelper.newInstance(RemoveUnusedImports.class, getClass()) .addSourceLines( "Test.java", "package test;", "import java.util.ArrayList;", "import java.util.List;", "// BUG: Diagnostic contains:", "import java.util.LinkedList;", "public class Test {", " List<String> xs = new ArrayList<>();", "}") .doTest(); } @Test public void diagnosticListsUnusedImports() { CompilationTestHelper.newInstance(RemoveUnusedImports.class, getClass()) .addSourceLines( "Test.java", "package test;", "import java.util.ArrayList;", "import java.util.List;", "// BUG: Diagnostic contains: java.util.LinkedList, java.util.Map, java.util.Set", "import java.util.LinkedList;", "import java.util.Map;", "import java.util.Set;", "public class Test {", " List<String> xs = new ArrayList<>();", "}") .doTest(); } @Test public void useInJavadocParameter() { testHelper .addInputLines( "in/Test.java", "import java.util.List;", "import java.util.Collection;", "/** {@link List#containsAll(Collection)} */", "public class Test {}") .expectUnchanged() .doTest(); } @Test public void qualifiedJavadoc() { testHelper .addInputLines( "in/Test.java", "import java.util.List;", "import java.util.Map;", "import java.util.Map.Entry;", "/** {@link java.util.List} {@link Map.Entry} */", "public class Test {}") .addOutputLines( "out/Test.java", "import java.util.Map;", "/** {@link java.util.List} {@link Map.Entry} */", "public class Test {}") .doTest(); } @Test public void parameterErasure() { testHelper .addInputLines( "in/A.java", "import java.util.Collection;", "public class A<T extends Collection> {", " public void foo(T t) {}", "}") .expectUnchanged() .addInputLines( "in/B.java", "import java.util.Collection;", "import java.util.List;", "public class B extends A<List> {", " /** {@link #foo(Collection)} {@link #foo(List)} */", " public void foo(List t) {}", "}") .expectUnchanged() .doTest(); } @Test public void atSee() { testHelper .addInputLines( "Lib.java", "import java.nio.file.Path;", "class Lib {", " static void f(Path... ps) {}", "}") .expectUnchanged() .addInputLines( "in/Test.java", "import java.nio.file.Path;", "class Test {", " /** @see Lib#f(Path[]) */", " void f() {}", "}") .expectUnchanged() .doTest(); } @Test public void multipleTopLevelClasses() { CompilationTestHelper.newInstance(RemoveUnusedImports.class, getClass()) .addSourceLines( "MultipleTopLevelClasses.java", "import java.util.List;", "import java.util.Set;", "public class MultipleTopLevelClasses { List x; }", "class Evil { Set x; }") .doTest(); } @Test public void unusedInPackageInfo() { testHelper .addInputLines( "in/com/example/package-info.java", "package com.example;", "import java.util.Map;") .addOutputLines( "out/com/example/package-info.java", "package com.example;", "") // The package statement's trailing newline is retained .doTest(TEXT_MATCH); } @Test public void b69984547() { testHelper .addInputLines( "android/app/PendingIntent.java", "package android.app;", "public class PendingIntent {", "}") .expectUnchanged() .addInputLines( "android/app/AlarmManager.java", "package android.app;", "public class AlarmManager {", " public void set(int type, long triggerAtMillis, PendingIntent operation) {}", "}") .expectUnchanged() .addInputLines( "in/Test.java", "import android.app.PendingIntent;", "/** {@link android.app.AlarmManager#containsAll(int, long, PendingIntent)} */", "public class Test {}") .expectUnchanged() .doTest(); } @Test public void b70690930() { testHelper .addInputLines( "a/One.java", // "package a;", "public class One {}") .expectUnchanged() .addInputLines( "a/Two.java", // "package a;", "public class Two {}") .expectUnchanged() .addInputLines( "p/Lib.java", "package p;", "import a.One;", "import a.Two;", "public class Lib {", " private static class I {", " public void f(One a) {}", " }", " public static class J {", " public void f(Two a) {}", " }", "}") .expectUnchanged() .addInputLines( "p/Test.java", // "package p;", "import a.One;", "import a.Two;", "/** {@link Lib.I#f(One)} {@link Lib.J#f(Two)} */", "public class Test {", "}") .addOutputLines( "out/p/Test.java", // "package p;", "import a.Two;", "/** {@link Lib.I#f(One)} {@link Lib.J#f(Two)} */", "public class Test {", "}") .doTest(); } }
11,270
28.738786
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitchTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import static org.junit.Assume.assumeTrue; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link UnnecessaryDefaultInEnumSwitch}Test */ @RunWith(JUnit4.class) public class UnnecessaryDefaultInEnumSwitchTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()); @Test public void switchCannotComplete() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " default:", " // This is a comment", " throw new AssertionError(c);", " }", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " ", " }", "// This is a comment", "throw new AssertionError(c);", " }", "}") .doTest(TEXT_MATCH); } @Test public void switchCannotCompleteUnrecognized() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " default:", " // This is a comment", " throw new AssertionError(c);", " }", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " case UNRECOGNIZED:", " break;", " }", "// This is a comment", "throw new AssertionError(c);", " }", "}") .doTest(TEXT_MATCH); } @Test public void emptyDefault() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " default:", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " }", " return false;", " }", "}") .doTest(); } @Test public void emptyDefaultUnrecognized() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " default:", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " case UNRECOGNIZED:", " // continue below", " }", " return false;", " }", "}") .doTest(); } @Test public void defaultBreak() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " default:", " break;", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " }", " return false;", " }", "}") .doTest(); } @Test public void defaultBreakUnrecognized() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " default:", " break;", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " case UNRECOGNIZED:", " // continue below", " }", " return false;", " }", "}") .doTest(); } @Test public void completes_noUnassignedVars_priorCaseExits() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " break;", " case THREE:", " return true;", " default:", " throw new AssertionError(c);", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " break;", " case THREE:", " return true;", " }", " return false;", " }", "}") .doTest(); } @Test public void completes_noUnassignedVars_priorCaseExitsUnrecognized() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " break;", " case THREE:", " return true;", " default:", " throw new AssertionError(c);", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " break;", " case THREE:", " return true;", " case UNRECOGNIZED:", " throw new AssertionError(c);", " }", " return false;", " }", "}") .doTest(TEXT_MATCH); } @Test public void completes_noUnassignedVars_priorCaseDoesntExit() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " return true;", " case THREE:", " default:", " // This is a comment", " System.out.println(\"Test\");", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " return true;", " case THREE:", " // This is a comment", " System.out.println(\"Test\");", " }", " return false;", " }", "}") .doTest(); } @Test public void completes_noUnassignedVars_priorCaseDoesntExitUnrecognized() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " return true;", " case THREE:", " default:", " // This is a comment", " System.out.println(\"Test\");", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " return true;", " case THREE:", " case UNRECOGNIZED:", " // This is a comment", " System.out.println(\"Test\");", " }", " return false;", " }", "}") .doTest(); } @Test public void completes_unassignedVars() { compilationHelper .addSourceLines( "Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " int x;", " switch (c) {", " case ONE:", " case TWO:", " x = 1;", " break;", " case THREE:", " x = 2;", " break;", " default:", " x = 3;", " }", " return x == 1;", " }", "}") .doTest(); } @Test public void completes_unassignedVarsUnrecognized() { compilationHelper .addSourceLines( "Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " int x;", " switch (c) {", " case ONE:", " case TWO:", " x = 1;", " break;", " case THREE:", " x = 2;", " break;", " default:", " x = 3;", " }", " return x == 1;", " }", "}") .doTest(); } @Test public void notExhaustive() { compilationHelper .addSourceLines( "Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " return true;", " default:", " throw new AssertionError(c);", " }", " }", "}") .doTest(); } @Test public void notExhaustiveUnrecognized() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "Test.java", "class Test {", " enum Case { ONE, TWO, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " return true;", " default:", " throw new AssertionError(c);", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Case { ONE, TWO, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " return true;", " case UNRECOGNIZED:", " break;", " }", " throw new AssertionError(c);", " }", "}") .doTest(TEXT_MATCH); } @Test public void notExhaustive2() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(boolean f, Case c) {", " if (f) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " default:", " return false;", " }", " } else {", " return false;", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Case { ONE, TWO, THREE }", " boolean m(boolean f, Case c) {", " if (f) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " }", " return false;", " } else {", " return false;", " }", " }", "}") .doTest(); } @Test public void notExhaustive2Unrecognized() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(boolean f, Case c) {", " if (f) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " default:", " return false;", " }", " } else {", " return false;", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(boolean f, Case c) {", " if (f) {", " switch (c) {", " case ONE:", " case TWO:", " case THREE:", " return true;", " case UNRECOGNIZED:", " break;", " }", " return false;", " } else {", " return false;", " }", " }", "}") .doTest(); } @Test public void unrecognizedIgnore() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "Test.java", "class Test {", " enum Case { ONE, TWO, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " return true;", " default:", " throw new AssertionError(c);", " }", " }", "}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void defaultAboveCaseUnrecognized() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " return true;", " default:", " case THREE:", " // This is a comment", " System.out.println(\"Test\");", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " case TWO:", " return true;", " case UNRECOGNIZED:", " case THREE:", " // This is a comment", " System.out.println(\"Test\");", " }", " return false;", " }", "}") .doTest(); } @Test public void messageMovedAssertion() { compilationHelper .addSourceLines( "in/Test.java", "class Test {", " enum Case { ONE }", " boolean m(Case c) {", " switch (c) {", " case ONE:", " return true;", " // BUG: Diagnostic contains: after the switch statement", " default:", " throw new AssertionError(c);", " }", " }", "}") .doTest(); } @Test public void messageRemovedAssertion() { compilationHelper .addSourceLines( "in/Test.java", "class Test {", " enum Case { ONE }", " void m(Case c) {", " int i = 0;", " switch (c) {", " case ONE:", " i = 1;", " break;", " // BUG: Diagnostic contains: case can be omitted", " default:", " throw new AssertionError();", " }", " }", "}") .doTest(); } @Test public void switchCompletesUnrecognized() { BugCheckerRefactoringTestHelper.newInstance(UnnecessaryDefaultInEnumSwitch.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " void m(Case c) {", " switch (c) {", " case ONE:", " break;", " case TWO:", " break;", " case THREE:", " break;", " default:", " // This is a comment", " throw new AssertionError(c);", " }", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " enum Case { ONE, TWO, THREE, UNRECOGNIZED }", " void m(Case c) {", " switch (c) {", " case ONE:", " break;", " case TWO:", " break;", " case THREE:", " break;", " case UNRECOGNIZED:", " // This is a comment", " throw new AssertionError(c);", " }", " }", "}") .doTest(TEXT_MATCH); } @Test public void messages() { compilationHelper .addSourceLines( "Test.java", "class Test {", " enum NormalEnum { A, B }", " enum ProtoEnum { ONE, TWO, UNRECOGNIZED }", " void normal(NormalEnum e) {", " switch (e) {", " case A:", " case B:", " // BUG: Diagnostic contains: default case can be omitted", " default:", " break;", " }", " }", " void proto(ProtoEnum e) {", " switch (e) {", " case ONE:", " case TWO:", " // BUG: Diagnostic contains: UNRECOGNIZED", " default:", " break;", " }", " }", "}") .doTest(); } @Test public void defaultCaseKindRule() { assumeTrue(RuntimeVersion.isAtLeast14()); compilationHelper .addSourceLines( "Test.java", "class Test {", " enum Case { ONE, TWO }", " void m(Case c) {", " switch (c) {", " case ONE -> {}", " case TWO -> {}", " // BUG: Diagnostic contains: UnnecessaryDefaultInEnumSwitch", " default -> {}", " }", " }", "}") .doTest(); } @Test public void unrecognizedCaseKindRule() { assumeTrue(RuntimeVersion.isAtLeast14()); compilationHelper .addSourceLines( "Test.java", "class Test {", " enum Case { ONE, TWO, UNRECOGNIZED }", " void m(Case c) {", " switch (c) {", " case ONE -> {}", " case TWO -> {}", " // BUG: Diagnostic contains: UnnecessaryDefaultInEnumSwitch", " default -> {}", " }", " }", "}") .doTest(); } }
25,432
29.827879
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/GetClassOnEnumTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link GetClassOnEnum}Test */ @RunWith(JUnit4.class) public class GetClassOnEnumTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(GetClassOnEnum.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "class Test {", " enum TheEnum { ONE }", " void f(TheEnum theEnum) {", " // BUG: Diagnostic contains: System.err.println(theEnum.getDeclaringClass());", " System.err.println(theEnum.getClass());", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "class Test {", " enum TheEnum { ONE }", " void f(TheEnum theEnum) {", " System.err.println(theEnum.getDeclaringClass());", " System.err.println(this.getClass());", " }", "}") .doTest(); } }
1,854
29.409836
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MissingSuperCallTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link MissingSuperCall}. */ @RunWith(JUnit4.class) public class MissingSuperCallTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MissingSuperCall.class, getClass()) .addSourceLines( "android/support/annotation/CallSuper.java", "package android.support.annotation;", "import static java.lang.annotation.ElementType.METHOD;", "import java.lang.annotation.Target;", "@Target({METHOD})", "public @interface CallSuper {}"); @Test public void android() { compilationHelper .addSourceLines( "Super.java", "import android.support.annotation.CallSuper;", "public class Super {", " @CallSuper public void doIt() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with @CallSuper,", " // but does not call the super method", " @Override public void doIt() {}", "}") .doTest(); } @Test public void androidx() { compilationHelper .addSourceLines( "androidx/annotation/CallSuper.java", "package androidx.annotation;", "public @interface CallSuper {}") .addSourceLines( "Super.java", "import androidx.annotation.CallSuper;", "public class Super {", " @CallSuper public void doIt() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with @CallSuper,", " // but does not call the super method", " @Override public void doIt() {}", "}") .doTest(); } @Test public void javax() { compilationHelper .addSourceLines( "Super.java", "import javax.annotation.OverridingMethodsMustInvokeSuper;", "public class Super {", " @OverridingMethodsMustInvokeSuper public void doIt() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with", " // @OverridingMethodsMustInvokeSuper, but does not call the super method", " @Override public void doIt() {}", "}") .doTest(); } @Test public void errorProne() { compilationHelper .addSourceLines( "Super.java", "import com.google.errorprone.annotations.OverridingMethodsMustInvokeSuper;", "public class Super {", " @OverridingMethodsMustInvokeSuper public void doIt() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with", " // @OverridingMethodsMustInvokeSuper, but does not call the super method", " @Override public void doIt() {}", "}") .doTest(); } @Test public void findBugs() { compilationHelper .addSourceLines( "edu/umd/cs/findbugs/annotations/OverrideMustInvoke.java", "package edu.umd.cs.findbugs.annotations;", "public @interface OverrideMustInvoke {}") .addSourceLines( "Super.java", "import edu.umd.cs.findbugs.annotations.OverrideMustInvoke;", "public class Super {", " @OverrideMustInvoke public void doIt() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with @OverrideMustInvoke,", " // but does not call the super method", " @Override public void doIt() {}", "}") .doTest(); } @Test public void negativeDoesCallSuper() { compilationHelper .addSourceLines( "Super.java", "import android.support.annotation.CallSuper;", "public class Super {", " @CallSuper public void doIt() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " @Override public void doIt() {", " super.doIt();", " }", "}") .doTest(); } @Test public void negativeDoesCallSuper2() { compilationHelper .addSourceLines( "Super.java", "import android.support.annotation.CallSuper;", "public class Super {", " @CallSuper public Object doIt() {", " return null;", " }", "}") .addSourceLines( "Sub.java", "import java.util.Objects;", "public class Sub extends Super {", " @Override public Object doIt() {", " return Objects.requireNonNull(super.doIt());", " }", "}") .doTest(); } @Test public void negativeDoesCallInterfaceSuper() { compilationHelper .addSourceLines( "Super.java", "import android.support.annotation.CallSuper;", "public interface Super {", " @CallSuper default void doIt() {}", "}") .addSourceLines( "Sub.java", "import java.util.Objects;", "public class Sub implements Super {", " @Override public void doIt() {", " Super.super.doIt();", " }", "}") .doTest(); } @Test public void positiveTwoLevelsApart() { compilationHelper .addSourceLines( "a/b/c/SuperSuper.java", "package a.b.c;", "import javax.annotation.OverridingMethodsMustInvokeSuper;", "public class SuperSuper {", " @OverridingMethodsMustInvokeSuper public void doIt() {}", "}") .addSourceLines( "Super.java", // "import a.b.c.SuperSuper;", "public class Super extends SuperSuper {}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides a.b.c.SuperSuper#doIt, which is annotated with", " // @OverridingMethodsMustInvokeSuper, but does not call the super method", " @Override public void doIt() {}", "}") .doTest(); } @Test public void androidAnnotationDisallowedOnAbstractMethod() { compilationHelper .addSourceLines( "AbstractClass.java", "import android.support.annotation.CallSuper;", "public abstract class AbstractClass {", " // BUG: Diagnostic contains: @CallSuper cannot be applied to an abstract method", " @CallSuper public abstract void bad();", " @CallSuper public void ok() {}", "}") .doTest(); } @Test public void javaxAnnotationDisallowedOnAbstractMethod() { compilationHelper .addSourceLines( "AbstractClass.java", "import javax.annotation.OverridingMethodsMustInvokeSuper;", "public abstract class AbstractClass {", " // BUG: Diagnostic contains:", " // @OverridingMethodsMustInvokeSuper cannot be applied to an abstract method", " @OverridingMethodsMustInvokeSuper public abstract void bad();", " @OverridingMethodsMustInvokeSuper public void ok() {}", "}") .doTest(); } @Test public void findBugsAnnotationDisallowedOnAbstractMethod() { compilationHelper .addSourceLines( "edu/umd/cs/findbugs/annotations/OverrideMustInvoke.java", "package edu.umd.cs.findbugs.annotations;", "public @interface OverrideMustInvoke {}") .addSourceLines( "AbstractClass.java", "import edu.umd.cs.findbugs.annotations.OverrideMustInvoke;", "public abstract class AbstractClass {", " // BUG: Diagnostic contains:", " // @OverrideMustInvoke cannot be applied to an abstract method", " @OverrideMustInvoke public abstract void bad();", " @OverrideMustInvoke public void ok() {}", "}") .doTest(); } @Test public void annotationDisallowedOnInterfaceMethod() { compilationHelper .addSourceLines( "MyInterface.java", "import javax.annotation.OverridingMethodsMustInvokeSuper;", "interface MyInterface {", " // BUG: Diagnostic contains:", " // @OverridingMethodsMustInvokeSuper cannot be applied to an abstract method", " @OverridingMethodsMustInvokeSuper void bad();", " @OverridingMethodsMustInvokeSuper default void ok() {}", "}") .doTest(); } @Test public void positiveOverridingDefaultInterfaceMethod() { compilationHelper .addSourceLines( "MyInterface.java", "import javax.annotation.OverridingMethodsMustInvokeSuper;", "interface MyInterface {", " @OverridingMethodsMustInvokeSuper default void doIt() {}", "}") .addSourceLines( "MyImplementation.java", "public class MyImplementation implements MyInterface {", " // BUG: Diagnostic contains:", " // This method overrides MyInterface#doIt, which is annotated with", " // @OverridingMethodsMustInvokeSuper, but does not call the super method", " @Override public void doIt() {}", "}") .doTest(); } @Test public void superAndSubAnnotated() { compilationHelper .addSourceLines( "Super.java", "import javax.annotation.OverridingMethodsMustInvokeSuper;", "public class Super {", " @OverridingMethodsMustInvokeSuper public void doIt() {}", "}") .addSourceLines( "Sub.java", "import javax.annotation.OverridingMethodsMustInvokeSuper;", "public class Sub extends Super {", " @OverridingMethodsMustInvokeSuper", " @Override", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with", " // @OverridingMethodsMustInvokeSuper, but does not call the super method", " public void doIt() {}", "}") .doTest(); } @Test public void negativeOverridingMethodIsAbstract() { compilationHelper .addSourceLines( "Super.java", "import javax.annotation.OverridingMethodsMustInvokeSuper;", "public class Super {", " @OverridingMethodsMustInvokeSuper public void doIt() {}", "}") .addSourceLines( "Sub.java", "public abstract class Sub extends Super {", " @Override public abstract void doIt();", "}") .doTest(); } @Test public void wrongSuperCall() { compilationHelper .addSourceLines( "Super.java", "import android.support.annotation.CallSuper;", "public class Super {", " @CallSuper public void doIt() {}", " public void wrongToCall() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with @CallSuper,", " // but does not call the super method", " @Override public void doIt() {", " super.wrongToCall();", " }", "}") .doTest(); } @Test public void nestedSuperCall() { compilationHelper .addSourceLines( "Super.java", "import android.support.annotation.CallSuper;", "public class Super {", " @CallSuper public void doIt() {}", " public void wrongToCall() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with @CallSuper,", " // but does not call the super method", " @Override public void doIt() {", " new Super() {", " @Override public void doIt() {", " super.doIt();", " }", " };", " }", "}") .doTest(); } @Test public void lambdas() { compilationHelper .addSourceLines( "Super.java", "import android.support.annotation.CallSuper;", "public class Super {", " @CallSuper public void doIt() {}", " public void wrongToCall() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with @CallSuper,", " // but does not call the super method", " @Override public void doIt() {", " Runnable r = () -> super.doIt();", " }", "}") .doTest(); } @Test public void methodReferences() { compilationHelper .addSourceLines( "Super.java", "import android.support.annotation.CallSuper;", "public class Super {", " @CallSuper public void doIt() {}", " public void wrongToCall() {}", "}") .addSourceLines( "Sub.java", "public class Sub extends Super {", " // BUG: Diagnostic contains:", " // This method overrides Super#doIt, which is annotated with @CallSuper,", " // but does not call the super method", " @Override public void doIt() {", " Runnable r = super::doIt;", " }", "}") .doTest(); } }
15,664
33.811111
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessarilyFullyQualifiedTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link UnnecessarilyFullyQualified}. */ @RunWith(JUnit4.class) public final class UnnecessarilyFullyQualifiedTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(UnnecessarilyFullyQualified.class, getClass()); @Test public void singleUse() { helper .addInputLines( "Test.java", // "interface Test {", " java.util.List foo();", " java.util.List bar();", "}") .addOutputLines( "Test.java", // "import java.util.List;", "interface Test {", " List foo();", " List bar();", "}") .doTest(); } @Test public void wouldBeAmbiguous() { helper .addInputLines( "List.java", // "class List {}") .expectUnchanged() .addInputLines( "Test.java", // "interface Test {", " java.util.List foo();", "}") .expectUnchanged() .doTest(); } @Test public void refersToMultipleTypes() { helper .addInputLines( "List.java", // "package a;", "public class List {}") .expectUnchanged() .addInputLines( "Test.java", "package b;", "interface Test {", " java.util.List foo();", " a.List bar();", "}") .expectUnchanged() .doTest(); } @Test public void refersToMultipleTypes_dependingOnLocation() { helper .addInputLines( "Outer.java", // "package a;", "public class Outer {", " public class List {}", "}") .expectUnchanged() .addInputLines( "Test.java", "package b;", "import a.Outer;", "interface Test {", " java.util.List foo();", " public abstract class Inner extends Outer {", " abstract List bar();", " }", "}") .expectUnchanged() .doTest(); } @Test public void inconsistentImportUsage() { helper .addInputLines( "Test.java", "import java.util.List;", "public class Test {", " public java.util.List<?> foo(List<?> list) {", " return list;", " }", "}") .addOutputLines( "Test.java", "import java.util.List;", "public class Test {", " public List<?> foo(List<?> list) {", " return list;", " }", "}") .doTest(); } @Test public void clashesWithTypeInSuperType() { helper .addInputLines( "A.java", // "package a;", "public interface A {", " public static class List {}", "}") .expectUnchanged() .addInputLines( "Test.java", "package b;", "import a.A;", "class Test implements A {", " java.util.List foo() {", " return null;", " }", "}") .expectUnchanged() .doTest(); } @Test public void builder() { helper .addInputLines( "Foo.java", // "package a;", "public class Foo {", " public static final class Builder {}", "}") .expectUnchanged() .addInputLines( "Test.java", "package b;", "interface Test {", " a.Foo foo();", " a.Foo.Builder fooBuilder();", "}") .addOutputLines( "Test.java", "package b;", "import a.Foo;", "interface Test {", " Foo foo();", " Foo.Builder fooBuilder();", "}") .doTest(); } @Test public void exemptedNames() { helper .addInputLines( "Annotation.java", // "package pkg;", "public class Annotation {}") .expectUnchanged() .addInputLines( "Test.java", // "interface Test {", " pkg.Annotation foo();", "}") .expectUnchanged() .doTest(); } @Test public void innerClass() { helper .addInputLines( "A.java", // "package test;", "public class A {", " class B {}", " void test (A a) {", " a.new B() {};", " }", "}") .expectUnchanged() .doTest(); } @Test public void packageInfo() { CompilationTestHelper.newInstance(UnnecessarilyFullyQualified.class, getClass()) .addSourceLines( "a/A.java", // "package a;", "public @interface A {}") .addSourceLines( "b/package-info.java", // "@a.A", "package b;") .doTest(); } }
5,988
25.267544
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AutoValueBuilderDefaultsInConstructorTest.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.auto.value.processor.AutoValueProcessor; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link AutoValueBuilderDefaultsInConstructor}. */ @RunWith(JUnit4.class) public final class AutoValueBuilderDefaultsInConstructorTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(AutoValueBuilderDefaultsInConstructor.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance( AutoValueBuilderDefaultsInConstructor.class, getClass()) .setArgs(ImmutableList.of("-processor", AutoValueProcessor.class.getName())); @Test public void negative() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " @AutoValue.Builder", " abstract class Builder {", " Builder() {}", " abstract void setFoo(int foo);", " }", "}") .doTest(); } @Test public void positive() { refactoringHelper .addInputLines( "Test.java", "package test;", "import com.google.auto.value.AutoValue;", "@AutoValue", "abstract class Test {", " abstract int foo();", " Builder builder() {", " return new AutoValue_Test.Builder();", " }", " @AutoValue.Builder", " abstract static class Builder {", " Builder() {", " this.setFoo(1);", " }", " abstract Builder setFoo(int foo);", " abstract Test build();", " }", "}") .addOutputLines( "Test.java", "package test;", "import com.google.auto.value.AutoValue;", "@AutoValue", "abstract class Test {", " abstract int foo();", " Builder builder() {", " return new AutoValue_Test.Builder().setFoo(1);", " }", " @AutoValue.Builder", " abstract static class Builder {", " abstract Builder setFoo(int foo);", " abstract Test build();", " }", "}") .doTest(); } @Test public void negative_nonAbstractMethodCalled() { refactoringHelper .addInputLines( "Test.java", "package test;", "import com.google.auto.value.AutoValue;", "@AutoValue", "abstract class Test {", " abstract int foo();", " Builder builder() {", " return new AutoValue_Test.Builder();", " }", " @AutoValue.Builder", " abstract static class Builder {", " Builder() {", " doSomethingOdd();", " }", " void doSomethingOdd() {}", " abstract Builder setFoo(int foo);", " abstract Test build();", " }", "}") .expectUnchanged() .doTest(); } }
4,070
32.368852
97
java