repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FallThroughPositiveCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
public class FallThroughPositiveCases {
class NonTerminatingTryFinally {
public int foo(int i) {
int z = 0;
switch (i) {
case 0:
try {
if (z > 0) {
return i;
} else {
z++;
}
} finally {
z++;
}
// BUG: Diagnostic contains:
case 1:
return -1;
default:
return 0;
}
}
}
abstract class TryWithNonTerminatingCatch {
int foo(int i) {
int z = 0;
switch (i) {
case 0:
try {
return bar();
} catch (RuntimeException e) {
log(e);
throw e;
} catch (Exception e) {
log(e); // don't throw
}
// BUG: Diagnostic contains:
case 1:
return -1;
default:
return 0;
}
}
abstract int bar() throws Exception;
void log(Throwable e) {}
}
public class Tweeter {
public int numTweets = 55000000;
public int everyBodyIsDoingIt(int a, int b) {
switch (a) {
case 1:
System.out.println("1");
// BUG: Diagnostic contains:
case 2:
System.out.println("2");
// BUG: Diagnostic contains:
default:
}
return 0;
}
}
}
| 2,016
| 21.411111
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/LongLiteralLowerCaseSuffixPositiveCase2.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/** Positive cases for {@link LongLiteralLowerCaseSuffix}. */
public class LongLiteralLowerCaseSuffixPositiveCase2 {
// This constant string includes non-ASCII characters to make sure that we're not confusing
// bytes and chars:
@SuppressWarnings("unused")
private static final String TEST_STRING = "Îñţérñåţîöñåļîžåţîờñ";
public void underscoredLowerCase() {
// BUG: Diagnostic contains: value = 0_1__2L
long value = 0_1__2l;
}
}
| 1,115
| 33.875
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/StringBuilderInitWithCharNegativeCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author lowasser@google.com (Louis Wasserman)
*/
public class StringBuilderInitWithCharNegativeCases {
{
new StringBuilder("a");
new StringBuilder(5);
new StringBuilder();
}
}
| 862
| 28.758621
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ImplementAssertionWithChainingPositiveCases.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
public class ImplementAssertionWithChainingPositiveCases {
static final class FooSubject extends Subject {
private final Foo actual;
private FooSubject(FailureMetadata metadata, Foo actual) {
super(metadata, actual);
this.actual = actual;
}
void hasString(String expected) {
// BUG: Diagnostic contains: check("string()").that(actual.string()).isEqualTo(expected)
if (!actual.string().equals(expected)) {
failWithActual("expected to have string", expected);
}
}
void hasStringGuavaObjectsEqual(String expected) {
// BUG: Diagnostic contains: check("string()").that(actual.string()).isEqualTo(expected)
if (!com.google.common.base.Objects.equal(actual.string(), expected)) {
failWithActual("expected to have string", expected);
}
}
void hasStringJavaObjectsEquals(String expected) {
// BUG: Diagnostic contains: check("string()").that(actual.string()).isEqualTo(expected)
if (!java.util.Objects.equals(actual.string(), expected)) {
failWithActual("expected to have string", expected);
}
}
void hasInteger(int expected) {
// BUG: Diagnostic contains: check("integer()").that(actual.integer()).isEqualTo(expected)
if (actual.integer() != expected) {
failWithActual("expected to have integer", expected);
}
}
void hasKind(Kind expected) {
// BUG: Diagnostic contains: check("kind()").that(actual.kind()).isEqualTo(expected)
if (actual.kind() != expected) {
failWithActual("expected to have kind", expected);
}
}
void hasOtherFooInteger(int expected) {
// BUG: Diagnostic contains:
// check("otherFoo().integer()").that(actual.otherFoo().integer()).isEqualTo(expected)
if (actual.otherFoo().integer() != expected) {
failWithActual("expected to have other foo with integer", expected);
}
}
}
private static final class Foo {
final String string;
final int integer;
final Kind kind;
Foo(String string, int integer, Kind kind) {
this.string = string;
this.integer = integer;
this.kind = kind;
}
String string() {
return string;
}
int integer() {
return integer;
}
Kind kind() {
return kind;
}
Foo otherFoo() {
return this;
}
}
private enum Kind {}
}
| 3,198
| 28.62037
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BadShiftAmountNegativeCases.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author Bill Pugh (bill.pugh@gmail.com)
*/
public class BadShiftAmountNegativeCases {
public void foo() {
int x = 0;
long result = 0;
result += (long) x >> 3;
result += x << 3;
result += x >>> 3;
result += (long) (x & 0xff) >> 40;
}
}
| 935
| 26.529412
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/InvalidPatternSyntaxPositiveCases.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.regex.Pattern;
/**
* @author mdempsky@google.com (Matthew Dempsky)
*/
public class InvalidPatternSyntaxPositiveCases {
public static final String INVALID = "*";
{
// BUG: Diagnostic contains: Unclosed character class
Pattern.matches("[^\\]", "");
// BUG: Diagnostic contains: Unclosed character class
Pattern.matches("[a-z", "");
// BUG: Diagnostic contains: Illegal repetition
Pattern.matches("{", "");
// BUG: Diagnostic contains:
Pattern.matches(INVALID, "");
// BUG: Diagnostic contains:
"".matches(INVALID);
// BUG: Diagnostic contains:
"".replaceAll(INVALID, "");
// BUG: Diagnostic contains:
"".replaceFirst(INVALID, "");
// BUG: Diagnostic contains:
"".split(INVALID);
// BUG: Diagnostic contains:
"".split(INVALID, 0);
}
}
| 1,494
| 29.510204
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/RxReturnValueIgnoredNegativeCases.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import io.reactivex.Flowable;
import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.Single;
import java.util.HashMap;
import java.util.Map;
/**
* @author friedj@google.com (Jake Fried)
*/
public class RxReturnValueIgnoredNegativeCases {
interface CanIgnoreMethod {
@CanIgnoreReturnValue
Observable<Object> getObservable();
@CanIgnoreReturnValue
Single<Object> getSingle();
@CanIgnoreReturnValue
Flowable<Object> getFlowable();
@CanIgnoreReturnValue
Maybe<Object> getMaybe();
}
public static class CanIgnoreImpl implements CanIgnoreMethod {
@Override
public Observable<Object> getObservable() {
return null;
}
@Override
public Single<Object> getSingle() {
return null;
}
@Override
public Flowable<Object> getFlowable() {
return null;
}
@Override
public Maybe<Object> getMaybe() {
return null;
}
}
static void callIgnoredInterfaceMethod() {
new CanIgnoreImpl().getObservable();
new CanIgnoreImpl().getSingle();
new CanIgnoreImpl().getFlowable();
new CanIgnoreImpl().getMaybe();
}
static void putInMap() {
Map<Object, Observable<?>> map1 = new HashMap<>();
Map<Object, Single<?>> map2 = new HashMap<>();
Map<Object, Maybe<?>> map3 = new HashMap<>();
HashMap<Object, Flowable<?>> map4 = new HashMap<>();
map1.put(new Object(), null);
map2.put(new Object(), null);
map3.put(new Object(), null);
map4.put(new Object(), null);
}
@CanIgnoreReturnValue
Observable<Object> getObservable() {
return null;
}
@CanIgnoreReturnValue
Single<Object> getSingle() {
return null;
}
@CanIgnoreReturnValue
Flowable<Object> getFlowable() {
return null;
}
@CanIgnoreReturnValue
Maybe<Object> getMaybe() {
return null;
}
void checkIgnore() {
getObservable();
getSingle();
getFlowable();
getMaybe();
}
}
| 2,674
| 22.672566
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TestNotRunNegativeCase2.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import org.junit.internal.runners.JUnit38ClassRunner;
import org.junit.runner.RunWith;
/**
* Not a JUnit 4 test (run with a JUnit3 test runner).
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit38ClassRunner.class)
public class JUnit4TestNotRunNegativeCase2 {
public void testThisIsATest() {}
}
| 982
| 30.709677
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FutureReturnValueIgnoredPositiveCases.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import com.google.common.base.Function;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
public class FutureReturnValueIgnoredPositiveCases {
IntValue intValue = new IntValue(0);
private static Future<Integer> increment(int bar) {
return null;
}
public <T extends Future> T returnFutureType(T input) {
return input;
}
public void testFutureGenerics() {
// BUG: Diagnostic contains: Future must be checked
returnFutureType(Futures.immediateCancelledFuture());
}
public void foo() {
int i = 1;
// BUG: Diagnostic contains: Future must be checked
increment(i);
System.out.println(i);
}
public void bar() {
// BUG: Diagnostic contains: Future must be checked
this.intValue.increment();
}
public void testIntValue() {
IntValue value = new IntValue(10);
// BUG: Diagnostic contains: Future must be checked
value.increment();
}
public void testFunction() {
new Function<Object, ListenableFuture<?>>() {
@Override
public ListenableFuture<?> apply(Object input) {
return immediateFuture(null);
}
// BUG: Diagnostic contains: Future must be checked
}.apply(null);
}
private class IntValue {
final int i;
public IntValue(int i) {
this.i = i;
}
public ListenableFuture<IntValue> increment() {
return immediateFuture(new IntValue(i + 1));
}
public void increment2() {
// BUG: Diagnostic contains: Future must be checked
this.increment();
}
public void increment3() {
// BUG: Diagnostic contains: Future must be checked
increment();
}
}
static <I, N extends Q, Q> ListenableFuture<Q> transform(
ListenableFuture<I> input, Function<? super I, ? extends N> function, Executor executor) {
return null;
}
static ListenableFuture<Integer> futureReturningMethod() {
return null;
}
static ListenableFuture<Integer> futureReturningMethod(Object unused) {
return null;
}
static void consumesFuture(Future<Object> future) {}
static void testIgnoredFuture() throws Exception {
ListenableFuture<String> input = null;
// BUG: Diagnostic contains: nested type
Future<?> output = transform(input, foo -> futureReturningMethod(), runnable -> runnable.run());
Future<?> otherOutput =
// BUG: Diagnostic contains: nested type
transform(
input,
new Function<String, ListenableFuture<Integer>>() {
@Override
public ListenableFuture<Integer> apply(String string) {
return futureReturningMethod();
}
},
runnable -> runnable.run());
// BUG: Diagnostic contains: nested type
transform(
input,
new Function<String, ListenableFuture<Integer>>() {
@Override
public ListenableFuture<Integer> apply(String string) {
return futureReturningMethod();
}
},
runnable -> runnable.run())
.get();
consumesFuture(
// BUG: Diagnostic contains: nested type
transform(
input,
new Function<String, ListenableFuture<Integer>>() {
@Override
public ListenableFuture<Integer> apply(String string) {
System.out.println("First generics");
return futureReturningMethod();
}
},
runnable -> runnable.run()));
consumesFuture(
transform(
input,
new Function<String, Object>() {
@Override
public Object apply(String string) {
// BUG: Diagnostic contains: returned future may be ignored
return futureReturningMethod();
}
},
runnable -> runnable.run()));
consumesFuture(
transform(
input,
new Function<String, Object>() {
@Override
public Object apply(String string) {
Future<?> result = futureReturningMethod();
// BUG: Diagnostic contains: returned future may be ignored
return result;
}
},
runnable -> runnable.run()));
consumesFuture(
// BUG: Diagnostic contains: nested type
transform(input, foo -> futureReturningMethod(), runnable -> runnable.run()));
consumesFuture(
// BUG: Diagnostic contains: nested type
transform(
input,
foo -> {
return futureReturningMethod();
},
runnable -> runnable.run()));
consumesFuture(
// BUG: Diagnostic contains: nested type
transform(
input,
FutureReturnValueIgnoredPositiveCases::futureReturningMethod,
runnable -> runnable.run()));
ListenableFuture<Object> done =
transform(
// BUG: Diagnostic contains: nested type
transform(
input,
new Function<String, ListenableFuture<Integer>>() {
@Override
public ListenableFuture<Integer> apply(String string) {
return futureReturningMethod();
}
},
runnable -> runnable.run()),
new Function<Object, Object>() {
@Override
public Object apply(Object string) {
return new Object();
}
},
runnable -> runnable.run());
}
}
| 6,531
| 28.690909
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/LockOnNonEnclosingClassLiteralNegativeCases.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
public class LockOnNonEnclosingClassLiteralNegativeCases {
static {
synchronized (LockOnNonEnclosingClassLiteralNegativeCases.class) {
}
}
private void methodContainsSynchronizedBlock() {
synchronized (LockOnNonEnclosingClassLiteralNegativeCases.class) {
}
synchronized (this) {
}
}
class SubClass {
public void methodContainsSynchronizedBlock() {
synchronized (SubClass.class) {
}
}
}
}
| 1,110
| 26.097561
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TestNotRunNegativeCase1.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* Not a JUnit 4 test (no @RunWith annotation on the class).
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
public class JUnit4TestNotRunNegativeCase1 {
public void testThisIsATest() {}
}
| 865
| 31.074074
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NonRuntimeAnnotationNegativeCases.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @author scottjohnson@google.com (Scott Johnsson)
*/
@NonRuntimeAnnotationNegativeCases.Runtime
public class NonRuntimeAnnotationNegativeCases {
public Runtime testAnnotation() {
return this.getClass().getAnnotation(NonRuntimeAnnotationNegativeCases.Runtime.class);
}
/** Annotation that is retained at runtime */
@Retention(RetentionPolicy.RUNTIME)
public @interface Runtime {}
}
| 1,151
| 31
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ShouldHaveEvenArgsMultimapPositiveCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.common.truth.Correspondence;
/**
* Positive test cases for {@link ShouldHaveEvenArgs} check.
*
* @author monnoroch@google.com (Max Strakhov)
*/
public class ShouldHaveEvenArgsMultimapPositiveCases {
private static final Multimap<String, String> multimap = ImmutableMultimap.of();
public void testWithOddArgs() {
// BUG: Diagnostic contains: even number of arguments
assertThat(multimap).containsExactly("hello", "there", "rest");
// BUG: Diagnostic contains: even number of arguments
assertThat(multimap).containsExactly("hello", "there", "hello", "there", "rest");
// BUG: Diagnostic contains: even number of arguments
assertThat(multimap).containsExactly(null, null, null, null, new Object[] {});
}
public void testWithArrayArgs() {
String key = "hello";
Object[] value = new Object[] {};
Object[][] args = new Object[][] {};
// BUG: Diagnostic contains: even number of arguments
assertThat(multimap).containsExactly(key, value, (Object) args);
}
public void testWithOddArgsWithCorrespondence() {
assertThat(multimap)
.comparingValuesUsing(Correspondence.from((a, b) -> true, "dummy"))
// BUG: Diagnostic contains: even number of arguments
.containsExactly("hello", "there", "rest");
assertThat(multimap)
.comparingValuesUsing(Correspondence.from((a, b) -> true, "dummy"))
// BUG: Diagnostic contains: even number of arguments
.containsExactly("hello", "there", "hello", "there", "rest");
}
}
| 2,354
| 34.681818
| 85
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BadImportNegativeCases.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.collect.ImmutableList;
/**
* Tests for {@link BadImport}.
*
* @author awturner@google.com (Andy Turner)
*/
public class BadImportNegativeCases {
public void qualified() {
ImmutableList.Builder<String> qualified;
com.google.common.collect.ImmutableList.Builder<String> fullyQualified;
ImmutableList.Builder raw;
new ImmutableList.Builder<String>();
}
static class Nested {
static class Builder {}
void useNestedBuilder() {
new Builder();
}
}
}
| 1,179
| 27.095238
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TestNotRunBaseClass.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Base class for test cases to extend.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit4.class)
public class JUnit4TestNotRunBaseClass {
@Before
public void testSetUp() {}
@After
public void testTearDown() {}
@Test
public void testOverrideThis() {}
}
| 1,093
| 25.682927
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NoAllocationCheckerNegativeCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.errorprone.annotations.NoAllocation;
import java.util.Arrays;
/**
* @author agoode@google.com (Adam Goode)
*/
public class NoAllocationCheckerNegativeCases {
// Calling safe methods is fine.
@NoAllocation
public boolean comparison(int n) {
return n > 1;
}
@NoAllocation
public void callNoAllocationMethod() {
comparison(5);
}
@NoAllocation
@SuppressWarnings({"foo, bar"})
public void annotatedWithArray() {}
@NoAllocation
public boolean arrayComparison(int[] a) {
return a.length > 0 && a[0] > 1;
}
// Non string operations are fine.
@NoAllocation
public int sumInts(int a, int b) {
return a + b;
}
@NoAllocation
public int addOne(int a) {
a += 1;
return a;
}
// Foreach is allowed on arrays.
@NoAllocation
public int forEachArray(int[] a) {
int last = -1;
for (int i : a) {
last = i;
}
return last;
}
// Varargs is ok if no autoboxing occurs.
@NoAllocation
public int varArgsMethod2(int a, int... b) {
return a + b[0];
}
@NoAllocation
public void callVarArgsNoAllocation(int[] b) {
varArgsMethod2(1, b);
}
@NoAllocation
public Object varArgsMethodObject2(Object a, Object... b) {
return b[0];
}
@NoAllocation
public void callVarArgsObject2(Object a, Object[] b) {
varArgsMethodObject2(a, b);
}
// Unboxing is fine.
@NoAllocation
public void unboxByCalling(Integer i) {
comparison(i);
}
@NoAllocation
public int binaryUnbox(Integer a, int b) {
return a + b;
}
// We can call a non-annotated method if we suppress warnings.
@NoAllocation
@SuppressWarnings("NoAllocation")
public void trustMe() {
String s = new String();
}
@NoAllocation
public void trusting() {
trustMe();
}
// Allocations are allowed in a throw statement.
@NoAllocation
public void throwNew() {
throw new RuntimeException();
}
@NoAllocation
public void throwNewArray() {
throw new RuntimeException(Arrays.toString(new int[10]));
}
@NoAllocation
public void throwMethod() {
throw new RuntimeException(Integer.toString(5));
}
@NoAllocation
public void throwStringConcatenation() {
throw new RuntimeException("a" + 5);
}
@NoAllocation
public void throwStringConcatenation2() {
throw new RuntimeException("a" + Integer.toString(5));
}
@NoAllocation
public void throwStringConcatenation3() {
throw new RuntimeException("a" + getInt());
}
@NoAllocation
public String throwStringConvCompoundAssign(int i) {
String s = "";
throw new RuntimeException(s += i);
}
class IntegerException extends RuntimeException {
public IntegerException(Integer i) {
super(i.toString());
}
}
@NoAllocation
public String throwBoxingCompoundAssign(Integer in, int i) {
throw new IntegerException(in += i);
}
@NoAllocation
public String throwBoxingAssign(Integer in, int i) {
throw new IntegerException(in = i);
}
@NoAllocation
public String throwBoxingInitialization(final int i) {
throw new RuntimeException() {
Integer in = i;
};
}
@NoAllocation
public String throwBoxingCast(int i) {
throw new IntegerException((Integer) i);
}
@NoAllocation
public String throwBoxingInvocation(int i) {
throw new IntegerException(i);
}
class VarArgsException extends RuntimeException {
public VarArgsException(int... ints) {
super(Arrays.toString(ints));
}
}
@NoAllocation
public String throwBoxingVarArgs(int i) {
throw new VarArgsException(i, i, i, 4);
}
@NoAllocation
public String throwBoxingUnary(Integer i) {
throw new IntegerException(i++);
}
@NoAllocation
public void callGenericMethod() {
String foo = "foo";
String bar = genericMethod(foo);
}
@NoAllocation
private static <T> T genericMethod(T value) {
return value;
}
// All of the positive cases with @NoAllocation removed are below.
public int[] newArray(int size) {
return new int[size];
}
public int[] arrayInitializer(int a, int b) {
int[] array = {a, b};
return array;
}
public int[] returnArrayInitializer(int a, int b) {
return new int[] {a, b};
}
public String newString(String s) {
return new String(s);
}
public String allocateString() {
return new String();
}
public String getString() {
return allocateString();
}
public int getInt() {
return 1;
}
public String stringConvReturn(int i) {
return "" + i;
}
public String stringConvAssign(int i) {
String s = "" + i;
return s;
}
public String stringConvAssign2(int i) {
String s = "";
s = s + i;
return s;
}
public String stringConvAssign3(int i) {
String s = "";
s = i + s;
return s;
}
public String stringConvReturnMethod() {
String s = "" + getInt();
return s;
}
public String stringConvCompoundAssign(int i) {
String s = "";
s += i;
return s;
}
public String stringConvCompoundReturnMethod() {
String s = "";
s += getInt();
return s;
}
public String doubleString(String s) {
return s + s;
}
public String doubleStringCompound(String s) {
s += s;
return s;
}
public int iteration(Iterable<Object> a) {
int result = 0;
for (Object o : a) {
result++;
}
return result;
}
public Integer assignBox(int i) {
Integer in;
in = i;
return in;
}
public Integer initializeBox(int i) {
Integer in = i;
return in;
}
public Integer initializeBoxLiteral() {
Integer in = 0;
return in;
}
public int castBox(int i) {
int in = (Integer) i;
return in;
}
public Integer returnBox(int i) {
return i;
}
public int unBox(Integer i) {
return i;
}
public void callBox(int i) {
unBox(i);
}
public int unBox2(int i1, Integer i2) {
return i2;
}
public void callBox2(int i1, int i2) {
unBox2(i1, i2);
}
public int unBox3(Integer i1, int i2) {
return i1;
}
public void callBox3(int i1, int i2) {
unBox3(i1, i2);
}
public int varArgsMethod(int a, int... b) {
return a + b[0];
}
public void callVarArgs0() {
varArgsMethod(0);
}
public void callVarArgs() {
varArgsMethod(1, 2);
}
public void callVarArgs2() {
varArgsMethod(1, 2, 3);
}
public Object varArgsMethodObject(Object a, Object... b) {
return b[0];
}
public void callVarArgsObject(Object a, Object[] b) {
varArgsMethodObject(a, b[0]);
}
public void callVarArgsObjectWithPrimitiveArray(Object a, int[] b) {
varArgsMethodObject(a, b);
}
public int forBox(int[] a) {
int count = 0;
for (Integer i = 0; i < a.length; i++) {
count++;
}
return count;
}
public void arrayBox(Integer[] a, int i) {
a[0] = i;
}
public int preIncrementBox(Integer i) {
++i;
return i;
}
public int postIncrementBox(Integer i) {
i++;
return i;
}
public int preDecrementBox(Integer i) {
--i;
return i;
}
public int postDecrementBox(Integer i) {
i--;
return i;
}
public int forEachBox(int[] a) {
int last = -1;
for (Integer i : a) {
last = i;
}
return last;
}
public void arrayPreIncrementBox(Integer[] a) {
++a[0];
}
public void arrayPostIncrementBox(Integer[] a) {
a[0]++;
}
public void arrayPreDecrementBox(Integer[] a) {
--a[0];
}
public void arrayPostDecrementBox(Integer[] a) {
a[0]--;
}
public int compoundBox(Integer a, int b) {
a += b;
return a;
}
public void arrayCompoundBox(Integer[] a, int b) {
a[0] += b;
}
public void andAssignmentBox(Integer i1, Integer i2) {
i1 &= i2;
}
public void divideAssignmentBox(Integer i1, Integer i2) {
i1 /= i2;
}
public void leftShiftAssignmentBox(Integer i1, Integer i2) {
i1 <<= i2;
}
public void minusAssignmentBox(Integer i1, Integer i2) {
i1 -= i2;
}
public void multiplyAssignmentBox(Integer i1, Integer i2) {
i1 *= i2;
}
public void orAssignmentBox(Integer i1, Integer i2) {
i1 |= i2;
}
public void plusAssignmentBox(Integer i1, Integer i2) {
i1 += i2;
}
public void remainderAssignmentBox(Integer i1, Integer i2) {
i1 %= i2;
}
public void rightShiftAssignmentBox(Integer i1, Integer i2) {
i1 >>= i2;
}
public void unsignedRightShiftAssignmentBox(Integer i1, Integer i2) {
i1 >>>= i2;
}
public void xorAssignmentBox(Integer i1, Integer i2) {
i1 ^= i2;
}
public Object doClone() throws CloneNotSupportedException {
return clone();
}
@NoAllocation
public String throwForeach(final Iterable<Object> a) {
throw new RuntimeException() {
private void f() {
for (Object o : a) {
a.toString();
}
}
};
}
public interface NoAllocationInterface {
@NoAllocation
void method();
}
public static class NoAllocationImplementingClass implements NoAllocationInterface {
@Override
@NoAllocation
public void method() {}
}
public static class NoAllocationImplementingClassWithSuppression
implements NoAllocationInterface {
@Override
@SuppressWarnings("NoAllocation")
public void method() {}
}
public abstract static class NoAllocationAbstractClass {
@NoAllocation
abstract void method();
}
public static class NoAllocationConcreteClass extends NoAllocationAbstractClass {
@Override
@NoAllocation
void method() {}
}
public static class NoAllocationConcreteClassWithSuppression extends NoAllocationAbstractClass {
@Override
@SuppressWarnings("NoAllocation")
void method() {}
}
public static class NoAllocationParentClass implements NoAllocationInterface {
@Override
@NoAllocation
public void method() {}
}
public static class NoAllocationSubclass extends NoAllocationParentClass {
@Override
@NoAllocation
public void method() {}
}
public static class NoAllocationSubclassWithSuppression extends NoAllocationParentClass {
@Override
@SuppressWarnings("NoAllocation")
public void method() {}
}
}
| 10,864
| 18.826642
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BadImportPositiveCases_expected.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.collect.ImmutableList;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link BadImport}.
*
* @author awturner@google.com (Andy Turner)
*/
class BadImportPositiveCases {
public void variableDeclarations() {
ImmutableList.Builder<String> qualified;
ImmutableList.Builder raw;
}
public void variableDeclarationsNestedGenerics() {
ImmutableList.Builder<ImmutableList.Builder<String>> builder1;
ImmutableList.Builder<ImmutableList.Builder> builder1Raw;
ImmutableList.Builder<ImmutableList.Builder<String>> builder2;
ImmutableList.Builder<ImmutableList.Builder> builder2Raw;
}
ImmutableList.@Nullable Builder<ImmutableList.@Nullable Builder<@Nullable String>>
parameterizedWithTypeUseAnnotationMethod() {
return null;
}
public void variableDeclarationsNestedGenericsAndTypeUseAnnotations() {
ImmutableList.@Nullable Builder<@Nullable String> parameterizedWithTypeUseAnnotation1;
ImmutableList.@Nullable Builder<ImmutableList.@Nullable Builder<@Nullable String>>
parameterizedWithTypeUseAnnotation2;
}
public void newClass() {
new ImmutableList.Builder<String>();
new ImmutableList.Builder<ImmutableList.Builder<String>>();
}
ImmutableList.Builder<String> returnGenericExplicit() {
return new ImmutableList.Builder<String>();
}
ImmutableList.Builder<String> returnGenericDiamond() {
return new ImmutableList.Builder<>();
}
ImmutableList.Builder returnRaw() {
return new ImmutableList.Builder();
}
void classLiteral() {
System.out.println(ImmutableList.Builder.class);
}
}
| 2,305
| 30.589041
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/CollectionToArraySafeParameterNegativeCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
/**
* @author mariasam@google.com (Maria Sam) on 6/27/17.
*/
public class CollectionToArraySafeParameterNegativeCases {
private void basicCase() {
Collection<String> collection = new ArrayList<String>();
Collection<Integer> collInts = new ArrayList<Integer>();
Object[] intArrayActualNoParam = collInts.toArray();
Integer[] intArrayActual = collInts.toArray(new Integer[collection.size()]);
Collection<Object> collectionObjects = new ArrayList<>();
Integer[] intArrayObjects = collectionObjects.toArray(new Integer[collectionObjects.size()]);
Integer[] arrayOfInts = new Integer[10];
Integer[] otherArray = collInts.toArray(arrayOfInts);
Collection<Collection<Integer>> collectionOfCollection = new ArrayList<Collection<Integer>>();
Collection<Integer>[] collectionOfCollectionArray =
collectionOfCollection.toArray(new ArrayList[10]);
SomeObject someObject = new SomeObject();
Integer[] someObjectArray = someObject.toArray(new Integer[1]);
// test to make sure that when the collection has no explicit type there is no error thrown
// when "toArray" is called.
Collection someObjects = new ArrayList();
Object[] intArray = someObjects.toArray(new Integer[1]);
}
class FooBar<T> extends HashSet<T> {}
void testFooBar(FooBar<Integer> fooBar) {
Integer[] things = fooBar.toArray(new Integer[] {});
}
class Foo<T> extends HashSet<String> {}
void test(Foo<Integer> foo) {
String[] things = foo.toArray(new String[] {});
}
class SomeObject {
Integer[] toArray(Integer[] someArray) {
return new Integer[10];
}
}
}
| 2,382
| 32.56338
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayToStringPositiveCases.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.*;
/**
* @author adgar@google.com (Mike Edgar)
*/
public class ArrayToStringPositiveCases {
public void intArray() {
int[] a = {1, 2, 3};
// BUG: Diagnostic contains: Arrays.toString(a)
if (a.toString().isEmpty()) {
System.out.println("int array string is empty!");
} else {
System.out.println("int array string is nonempty!");
}
}
public void objectArray() {
Object[] a = new Object[3];
// BUG: Diagnostic contains: Arrays.toString(a)
if (a.toString().isEmpty()) {
System.out.println("object array string is empty!");
} else {
System.out.println("object array string is nonempty!");
}
}
public void firstMethodCall() {
String s = "hello";
// BUG: Diagnostic contains: Arrays.toString(s.toCharArray())
if (s.toCharArray().toString().isEmpty()) {
System.out.println("char array string is empty!");
} else {
System.out.println("char array string is nonempty!");
}
}
public void secondMethodCall() {
char[] a = new char[3];
// BUG: Diagnostic contains: Arrays.toString(a)
if (a.toString().isEmpty()) {
System.out.println("array string is empty!");
} else {
System.out.println("array string is nonempty!");
}
}
public void throwable() {
Exception e = new RuntimeException();
// BUG: Diagnostic contains: Throwables.getStackTraceAsString(e)
System.out.println(e.getStackTrace().toString());
}
public void arrayOfArrays() {
int[][] a = {};
// BUG: Diagnostic contains: Arrays.deepToString(a)
System.out.println(a);
}
}
| 2,281
| 26.829268
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/PrivateSecurityContractProtoAccessNegativeCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.html.types.SafeHtml;
import com.google.common.html.types.SafeHtmlProto;
import com.google.common.html.types.SafeHtmls;
public class PrivateSecurityContractProtoAccessNegativeCases {
static SafeHtmlProto safeHtmlProto;
static {
safeHtmlProto = SafeHtmls.toProto(SafeHtml.EMPTY);
}
static SafeHtml safeHtml;
static {
safeHtml = SafeHtmls.fromProto(safeHtmlProto);
}
}
| 1,077
| 28.944444
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ThreadJoinLoopPositiveCases_expected.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.util.concurrent.Uninterruptibles;
/**
* @author mariasam@google.com (Maria Sam) on 7/10/17.
*/
class ThreadJoinLoopPositiveCases {
public void basicCase(Thread thread) {
Uninterruptibles.joinUninterruptibly(thread);
}
public void emptyInterruptedFullException(Thread thread) {
Uninterruptibles.joinUninterruptibly(thread);
}
public void emptyException(Thread thread) {
Uninterruptibles.joinUninterruptibly(thread);
}
public void emptyCatchStatements(Thread thread) {
Uninterruptibles.joinUninterruptibly(thread);
}
public void whileLoop(Thread thread) {
Uninterruptibles.joinUninterruptibly(thread);
}
public void whileLoopCheck(Thread thread) {
Uninterruptibles.joinUninterruptibly(thread);
}
public void whileLoopVariable(Thread thread, boolean threadAlive) {
Uninterruptibles.joinUninterruptibly(thread);
}
public void basicLoopOtherStatements(Thread thread) {
while (7 == 7) {
System.out.println("test");
Uninterruptibles.joinUninterruptibly(thread);
}
}
public void breakStatement(Thread thread) {
Uninterruptibles.joinUninterruptibly(thread);
}
private void whileLoopBreak(Thread thread) {
Uninterruptibles.joinUninterruptibly(thread);
}
private void whileLoopThreadAlive(Thread thread) {
Uninterruptibles.joinUninterruptibly(thread);
}
public void multipleStatements(Thread thread, boolean isAlive) {
Uninterruptibles.joinUninterruptibly(thread);
}
private void arrayJoin(Thread[] threads) {
for (int i = 0; i < threads.length; i++) {
Uninterruptibles.joinUninterruptibly(threads[i]);
}
}
class MyThread extends Thread {
public void run() {
Uninterruptibles.joinUninterruptibly(this);
}
public void whileInThread() {
Uninterruptibles.joinUninterruptibly(this);
}
}
}
| 2,541
| 26.333333
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnitParameterMethodNotFoundNegativeCaseSuperClass.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(JUnitParamsRunner.class)
public class JUnitParameterMethodNotFoundNegativeCaseSuperClass
extends JUnitParameterMethodNotFoundNegativeCaseBaseClass {
@Test
@Parameters(method = "named1")
public void testNamed(int a) {}
}
| 1,027
| 32.16129
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OptionalNotPresentPositiveCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.Optional;
/** Includes true-positive and false-negative cases. */
public class OptionalNotPresentPositiveCases {
// False-negative
public String getWhenUnknown(Optional<String> optional) {
return optional.get();
}
// False-negative
public String getWhenUnknown_testNull(Optional<String> optional) {
if (optional.get() != null) {
return optional.get();
}
return "";
}
// False-negative
public String getWhenAbsent_testAndNestUnrelated(Optional<String> optional) {
if (true) {
String str = optional.get();
if (!optional.isPresent()) {
return "";
}
return str;
}
return "";
}
public String getWhenAbsent(Optional<String> testStr) {
if (!testStr.isPresent()) {
// BUG: Diagnostic contains: Optional
return testStr.get();
}
return "";
}
public String getWhenAbsent_multipleStatements(Optional<String> optional) {
if (!optional.isPresent()) {
String test = "test";
// BUG: Diagnostic contains: Optional
return test + optional.get();
}
return "";
}
// False-negative
public String getWhenAbsent_nestedCheck(Optional<String> optional) {
if (!optional.isPresent() || true) {
return !optional.isPresent() ? optional.get() : "";
}
return "";
}
public String getWhenAbsent_compoundIf_false(Optional<String> optional) {
if (!optional.isPresent() && true) {
// BUG: Diagnostic contains: Optional
return optional.get();
}
return "";
}
// False-negative
public String getWhenAbsent_compoundIf_true(Optional<String> optional) {
if (!optional.isPresent() || true) {
return optional.get();
}
return "";
}
public String getWhenAbsent_elseClause(Optional<String> optional) {
if (optional.isPresent()) {
return optional.get();
} else {
// BUG: Diagnostic contains: Optional
return optional.get();
}
}
// False-negative
public String getWhenAbsent_localReassigned(Optional<String> optional) {
if (!optional.isPresent()) {
optional = Optional.empty();
}
return optional.get();
}
// False-negative
public String getWhenAbsent_methodScoped(Optional<String> optional) {
if (optional.isPresent()) {
return "";
}
return optional.get();
}
}
| 3,005
| 25.368421
| 79
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverridesPositiveCase4.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.Map;
/**
* Test that the suggested fix is correct in the presence of whitespace, comments.
*
* @author cushon@google.com (Liam Miller-Cushon)
*/
public class OverridesPositiveCase4 {
@interface Note { }
abstract class Base {
abstract void varargsMethod(@Note final Map<Object, Object>... xs);
abstract void arrayMethod(@Note final Map<Object, Object>[] xs);
}
abstract class Child1 extends Base {
@Override
// BUG: Diagnostic contains: (@Note final Map<Object, Object> /* asd */ [] /* dsa */ xs);
abstract void arrayMethod(@Note final Map<Object, Object> /* asd */ ... /* dsa */ xs);
}
abstract class Child2 extends Base {
@Override
//TODO(cushon): improve testing infrastructure so we can enforce that no fix is suggested.
// BUG: Diagnostic contains: Varargs
abstract void varargsMethod(@Note final Map<Object, Object> /*dsa*/ [ /* [ */ ] /* dsa */ xs);
}
}
| 1,588
| 34.311111
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MustBeClosedCheckerPositiveCases_expected.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.errorprone.annotations.MustBeClosed;
import java.util.function.Supplier;
import java.util.stream.Stream;
@SuppressWarnings({"UnusedNestedClass", "UnusedVariable"})
class MustBeClosedCheckerPositiveCases {
class DoesNotImplementAutoCloseable {
@MustBeClosed
// BUG: Diagnostic contains: MustBeClosed should only annotate constructors of AutoCloseables.
DoesNotImplementAutoCloseable() {}
@MustBeClosed
// BUG: Diagnostic contains: MustBeClosed should only annotate methods that return an
// AutoCloseable.
void doesNotReturnAutoCloseable() {}
}
class Closeable implements AutoCloseable {
@Override
public void close() {}
public int method() {
return 1;
}
}
class Foo {
@MustBeClosed
Closeable mustBeClosedAnnotatedMethod() {
return new Closeable();
}
void sameClass() {
// BUG: Diagnostic contains:
try (var closeable = mustBeClosedAnnotatedMethod()) {}
}
}
class MustBeClosedAnnotatedConstructor extends Closeable {
@MustBeClosed
MustBeClosedAnnotatedConstructor() {}
void sameClass() {
// BUG: Diagnostic contains:
try (var mustBeClosedAnnotatedConstructor = new MustBeClosedAnnotatedConstructor()) {}
}
}
void positiveCase1() {
// BUG: Diagnostic contains:
try (var closeable = new Foo().mustBeClosedAnnotatedMethod()) {}
}
void positiveCase2() {
// BUG: Diagnostic contains:
try (Closeable closeable = new Foo().mustBeClosedAnnotatedMethod()) {}
}
void positiveCase3() {
try {
// BUG: Diagnostic contains:
try (var closeable = new Foo().mustBeClosedAnnotatedMethod()) {}
} finally {
}
}
void positiveCase4() {
try (Closeable c = new Foo().mustBeClosedAnnotatedMethod()) {
// BUG: Diagnostic contains:
try (var closeable = new Foo().mustBeClosedAnnotatedMethod()) {}
}
}
void positiveCase5() {
// BUG: Diagnostic contains:
try (var mustBeClosedAnnotatedConstructor = new MustBeClosedAnnotatedConstructor()) {}
}
@MustBeClosed
Closeable positiveCase6() {
// BUG: Diagnostic contains:
return new MustBeClosedAnnotatedConstructor();
}
@MustBeClosed
Closeable positiveCase7() {
// BUG: Diagnostic contains:
return new Foo().mustBeClosedAnnotatedMethod();
}
int existingDeclarationUsesVar() {
// Bug: Diagnostic contains:
try (var result = new Foo().mustBeClosedAnnotatedMethod()) {
return 0;
}
}
boolean twoCloseablesInOneExpression() {
// BUG: Diagnostic contains:
try (var closeable = new Foo().mustBeClosedAnnotatedMethod()) {
try (var closeable2 = new Foo().mustBeClosedAnnotatedMethod()) {
return closeable == closeable2;
}
}
}
void voidLambda() {
// Lambda has a fixless finding because no reasonable fix can be suggested.
// BUG: Diagnostic contains:
Runnable runnable = () -> new Foo().mustBeClosedAnnotatedMethod();
}
void expressionLambda() {
Supplier<Closeable> supplier =
() ->
// BUG: Diagnostic contains:
new Foo().mustBeClosedAnnotatedMethod();
}
void statementLambda() {
Supplier<Closeable> supplier =
() -> {
// BUG: Diagnostic contains:
return new Foo().mustBeClosedAnnotatedMethod();
};
}
void methodReference() {
Supplier<Closeable> supplier =
// TODO(b/218377318): BUG: Diagnostic contains:
new Foo()::mustBeClosedAnnotatedMethod;
}
void anonymousClass() {
new Foo() {
@MustBeClosed
@Override
public Closeable mustBeClosedAnnotatedMethod() {
// BUG: Diagnostic contains:
return new MustBeClosedAnnotatedConstructor();
}
};
}
void subexpression() {
// BUG: Diagnostic contains:
try (var closeable = new Foo().mustBeClosedAnnotatedMethod()) {
closeable.method();
}
}
void ternary(boolean condition) {
// BUG: Diagnostic contains:
int result;
try (var closeable = new Foo().mustBeClosedAnnotatedMethod()) {
result = condition ? closeable.method() : 0;
}
}
int variableDeclaration() {
// BUG: Diagnostic contains:
int result;
try (var closeable = new Foo().mustBeClosedAnnotatedMethod()) {
result = closeable.method();
}
return result;
}
void tryWithResources_nonFinal() {
Foo foo = new Foo();
// BUG: Diagnostic contains:
try (Closeable closeable = foo.mustBeClosedAnnotatedMethod()) {
try {
closeable = null;
} finally {
closeable.close();
}
}
}
void tryWithResources_noClose() {
Foo foo = new Foo();
// BUG: Diagnostic contains:
try (Closeable closeable = foo.mustBeClosedAnnotatedMethod()) {
try {
} finally {
}
}
}
class CloseableFoo implements AutoCloseable {
@MustBeClosed
CloseableFoo() {}
// Doesn't autoclose Foo on Stream close.
Stream<String> stream() {
return null;
}
@Override
public void close() {}
}
void twrStream() {
// BUG: Diagnostic contains:
try (CloseableFoo closeableFoo = new CloseableFoo();
Stream<String> stream = closeableFoo.stream()) {}
}
void constructorsTransitivelyRequiredAnnotation() {
abstract class Parent implements AutoCloseable {
@MustBeClosed
Parent() {}
// BUG: Diagnostic contains: Invoked constructor is marked @MustBeClosed
@MustBeClosed
Parent(int i) {
this();
}
}
// BUG: Diagnostic contains: Implicitly invoked constructor is marked @MustBeClosed
abstract class ChildDefaultConstructor extends Parent {}
abstract class ChildExplicitConstructor extends Parent {
// BUG: Diagnostic contains: Invoked constructor is marked @MustBeClosed
@MustBeClosed
ChildExplicitConstructor() {}
// BUG: Diagnostic contains: Invoked constructor is marked @MustBeClosed
@MustBeClosed
ChildExplicitConstructor(int a) {
super();
}
}
}
}
| 6,732
| 24.796935
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ThrowIfUncheckedKnownCheckedTestPositiveCases.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.base.Throwables.propagateIfPossible;
import static com.google.common.base.Throwables.throwIfUnchecked;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
public class ThrowIfUncheckedKnownCheckedTestPositiveCases {
void simple(IOException e) {
// BUG: Diagnostic contains: no-op
throwIfUnchecked(e);
// BUG: Diagnostic contains: no-op
propagateIfPossible(e);
}
void union() {
try {
foo();
} catch (IOException | ExecutionException e) {
// BUG: Diagnostic contains: no-op
throwIfUnchecked(e);
// BUG: Diagnostic contains: no-op
propagateIfPossible(e);
}
}
<E extends IOException> void checkedGeneric(E e) {
// BUG: Diagnostic contains: no-op
throwIfUnchecked(e);
}
void foo() throws IOException, ExecutionException {}
}
| 1,572
| 28.12963
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/DepAnnPositiveCases.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @deprecated
*/
// BUG: Diagnostic contains: @Deprecated
public class DepAnnPositiveCases {
/**
* @deprecated
*/
// BUG: Diagnostic contains: @Deprecated
public DepAnnPositiveCases() {}
/**
* @deprecated
*/
// BUG: Diagnostic contains: @Deprecated
int myField;
/**
* @deprecated
*/
// BUG: Diagnostic contains: @Deprecated
enum Enum {
VALUE,
}
/**
* @deprecated
*/
// BUG: Diagnostic contains: @Deprecated
interface Interface {}
/**
* @deprecated
*/
// BUG: Diagnostic contains: @Deprecated
public void deprecatedMethood() {}
}
| 1,268
| 21.263158
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/PreconditionsExpensiveStringNegativeCase1.java
|
/*
* Copyright 2011 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.base.Preconditions;
/**
* Preconditions calls which shouldn't be picked up for expensive string operations
*
* @author sjnickerson@google.com (Simon Nickerson)
*/
public class PreconditionsExpensiveStringNegativeCase1 {
public void error() {
int foo = 42;
Preconditions.checkState(true, "The foo %s foo is not a good foo", foo);
// This call should not be converted because of the %d, which does some locale specific
// behaviour. If it were an %s, it would be fair game.
Preconditions.checkState(true, String.format("The foo %d foo is not a good foo", foo));
}
}
| 1,282
| 34.638889
| 91
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4SetUpNotRunPositiveCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Basic class with an untagged setUp method */
@RunWith(JUnit4.class)
public class JUnit4SetUpNotRunPositiveCases {
// BUG: Diagnostic contains: @Before
public void setUp() {}
}
@RunWith(JUnit4.class)
class J4PositiveCase2 {
// BUG: Diagnostic contains: @Before
protected void setUp() {}
}
/**
* Replace @After with @Before
*/
@RunWith(JUnit4.class)
class J4AfterToBefore {
// BUG: Diagnostic contains: @Before
@After
protected void setUp() {}
}
/**
* Replace @AfterClass with @BeforeClass
*/
@RunWith(JUnit4.class)
class J4AfterClassToBeforeClass {
// BUG: Diagnostic contains: @BeforeClass
@AfterClass
protected void setUp() {}
}
class BaseTestClass {
void setUp() {}
}
/**
* This is the ambiguous case that we want the developer to make the determination as to
* whether to rename setUp()
*/
@RunWith(JUnit4.class)
class J4Inherit extends BaseTestClass {
// BUG: Diagnostic contains: @Before
protected void setUp() {}
}
/**
* setUp() method overrides parent method with @Override, but that method isn't @Before in the
* superclass
*/
@RunWith(JUnit4.class)
class J4OverriddenSetUp extends BaseTestClass {
// BUG: Diagnostic contains: @Before
@Override protected void setUp() {}
}
@RunWith(JUnit4.class)
class J4OverriddenSetUpPublic extends BaseTestClass {
// BUG: Diagnostic contains: @Before
@Override public void setUp() {}
}
| 2,168
| 23.931034
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MissingFailPositiveCases2.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
// unused import to make sure we don't introduce an import conflict.
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test cases for missing fail */
@RunWith(JUnit4.class)
public class MissingFailPositiveCases2 {
@Test
public void expectedException() {
try {
// BUG: Diagnostic contains: fail()
dummyMethod();
} catch (Exception expected) {
}
}
public void expectedException_helperMethod() {
try {
// BUG: Diagnostic contains: fail()
dummyMethod();
} catch (Exception expected) {
}
}
private static void dummyMethod() {}
}
| 1,294
| 25.979167
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ThreadJoinLoopPositiveCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author mariasam@google.com (Maria Sam) on 7/10/17.
*/
class ThreadJoinLoopPositiveCases {
public void basicCase(Thread thread) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
} catch (InterruptedException e) {
// ignore
}
}
public void emptyInterruptedFullException(Thread thread) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
} catch (InterruptedException e) {
// ignore
}
}
public void emptyException(Thread thread) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
} catch (Exception e) {
// ignore
}
}
public void emptyCatchStatements(Thread thread) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
} catch (Exception e) {
;
;
}
}
public void whileLoop(Thread thread) {
while (true) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
} catch (InterruptedException e) {
// ignore
}
}
}
public void whileLoopCheck(Thread thread) {
while (thread != null) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
} catch (InterruptedException e) {
// ignore
}
}
}
public void whileLoopVariable(Thread thread, boolean threadAlive) {
while (threadAlive) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
threadAlive = false;
} catch (InterruptedException e) {
// ignore
}
}
}
public void basicLoopOtherStatements(Thread thread) {
while (7 == 7) {
System.out.println("test");
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
} catch (InterruptedException e) {
// ignore
}
}
}
public void breakStatement(Thread thread) {
while (7 == 7) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
break;
} catch (InterruptedException e) {
// ignore
}
}
}
private void whileLoopBreak(Thread thread) {
while (true) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
break;
} catch (InterruptedException e) {
/* try again */
}
}
}
private void whileLoopThreadAlive(Thread thread) {
while (thread.isAlive()) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
} catch (InterruptedException e) {
// Ignore
}
}
}
public void multipleStatements(Thread thread, boolean isAlive) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(thread)
thread.join();
isAlive = false;
} catch (InterruptedException e) {
// ignore
}
}
private void arrayJoin(Thread[] threads) {
for (int i = 0; i < threads.length; i++) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(threads[i])
threads[i].join();
} catch (InterruptedException e) {
// ignore
}
}
}
class MyThread extends Thread {
public void run() {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(this)
join();
} catch (InterruptedException e) {
// ignore
}
}
public void whileInThread() {
while (isAlive()) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(this)
join();
} catch (InterruptedException e) {
// Ignore.
}
}
}
}
}
| 4,707
| 24.448649
| 85
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsRefactoringComments_expected.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author hanuszczak@google.com (Łukasz Hanuszczak)
*/
class UngroupedOverloadsRefactoringComments {
private void bar() {}
// Something about `bar`.
/** Does something. */
public void bar(int x) {}
// Something about this `bar`.
public void bar(int x, int y) {}
// More stuff about `bar`.
public void bar(int x, int y, int z) {
// Some internal comments too.
}
public void bar(String s) {}
public static final String FOO = "foo"; // This is super-important comment for `foo`.
// Something about `baz`.
public static final String BAZ = "baz"; // Stuff about `baz` continues.
public void quux() {}
}
| 1,306
| 26.808511
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnitParameterMethodNotFoundNegativeCase.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import junitparams.naming.TestCaseName;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Negative cases for {@link com.google.errorprone.bugpatterns.JUnitParameterMethodNotFound} */
@RunWith(JUnitParamsRunner.class)
public class JUnitParameterMethodNotFoundNegativeCase {
private static final String METHOD = "named1";
private static Object[] dataProvider() {
return new Object[] {1};
}
private static Object[] dataProvider1() {
return new Object[] {2};
}
@Test
@Parameters(method = "dataProvider, dataProvider1")
public void paramStaticProvider(int a) {}
@Test
@Parameters(source = Inner.class, method = "dataProviderInner")
public void testSource(int a) {}
@Test
@Parameters({"AAA,1", "BBB,2"})
public void paramsInAnnotation(String p1, Integer p2) {}
@Test
@Parameters({"AAA|1", "BBB|2"})
public void paramsInAnnotationPipeSeparated(String p1, Integer p2) {}
@Test
@Parameters
public void paramsInDefaultMethod(String p1, Integer p2) {}
private Object parametersForParamsInDefaultMethod() {
return new Object[] {new Object[] {"AAA", 1}, new Object[] {"BBB", 2}};
}
@Test
@Parameters(method = METHOD)
public void paramsInNamedMethod(String p1, Integer p2) {}
private Object named1() {
return new Object[] {"AAA", 1};
}
@Test
@Parameters(method = "named2,named3")
public void paramsInMultipleMethods(String p1, Integer p2) {}
private Object named2() {
return new Object[] {"AAA", 1};
}
private Object named3() {
return new Object[] {"BBB", 2};
}
@Test
@Parameters
public void paramsInCollection(String p1) {}
private List<String> parametersForParamsInCollection() {
return Arrays.asList("a");
}
@Test
@Parameters
public void paramsInIterator(String p1) {}
private Iterator<String> parametersForParamsInIterator() {
return Arrays.asList("a").iterator();
}
@Test
@Parameters
public void paramsInIterableOfIterables(String p1, String p2) {}
private List<List<String>> parametersForParamsInIterableOfIterables() {
return Arrays.asList(Arrays.asList("s01e01", "s01e02"), Arrays.asList("s02e01", "s02e02"));
}
@Test
@Parameters(
"please\\, escape commas if you use it here and don't want your parameters to be splitted")
public void commasInParametersUsage(String phrase) {}
@Test
@Parameters({"1,1", "2,2", "3,6"})
@TestCaseName("factorial({0}) = {1}")
public void customNamesForTestCase(int argument, int result) {}
@Test
@Parameters({"value1, value2", "value3, value4"})
@TestCaseName("[{index}] {method}: {params}")
public void predefinedMacroForTestCaseNames(String param1, String param2) {}
public Object mixedParameters() {
boolean booleanValue = true;
int[] primitiveArray = {1, 2, 3};
String stringValue = "Test";
String[] stringArray = {"one", "two", null};
return new Object[] {new Object[] {booleanValue, primitiveArray, stringValue, stringArray}};
}
@Test
@Parameters(method = "mixedParameters")
@TestCaseName("{0}, {1}, {2}, {3}")
public void usageOfMultipleTypesOfParameters(
boolean booleanValue, int[] primitiveArray, String stringValue, String[] stringArray) {}
static class Inner {
public Object dataProviderInner() {
return new Object[] {1};
}
}
}
| 4,125
| 27.455172
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4SetUpNotRunNegativeCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.internal.runners.JUnit38ClassRunner;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Not a JUnit 4 test (no @RunWith annotation on the class). */
public class JUnit4SetUpNotRunNegativeCases {
public void setUp() {}
}
@RunWith(JUnit38ClassRunner.class)
class J4SetUpWrongRunnerType {
public void setUp() {}
}
@RunWith(JUnit4.class)
class J4SetUpCorrectlyDone {
@Before
public void setUp() {}
}
/** May be a JUnit 3 test -- has @RunWith annotation on the class but also extends TestCase. */
@RunWith(JUnit4.class)
class J4SetUpJUnit3Class extends TestCase {
public void setUp() {}
}
/** setUp() method is private and wouldn't be run by JUnit3 */
@RunWith(JUnit4.class)
class J4PrivateSetUp {
private void setUp() {}
}
/**
* setUp() method is package-local. You couldn't have a JUnit3 test class with a package-private
* setUp() method (narrowing scope from protected to package)
*/
@RunWith(JUnit4.class)
class J4PackageLocalSetUp {
void setUp() {}
}
@RunWith(JUnit4.class)
class J4SetUpNonVoidReturnType {
int setUp() {
return 42;
}
}
/** setUp() has parameters */
@RunWith(JUnit4.class)
class J4SetUpWithParameters {
public void setUp(int ignored) {}
public void setUp(boolean ignored) {}
public void setUp(String ignored) {}
}
/** setUp() method is static and wouldn't be run by JUnit3 */
@RunWith(JUnit4.class)
class J4StaticSetUp {
public static void setUp() {}
}
abstract class SetUpAnnotatedBaseClass {
@Before
public void setUp() {}
}
/** setUp() method overrides parent method with @Before. It will be run by JUnit4BlockRunner */
@RunWith(JUnit4.class)
class J4SetUpExtendsAnnotatedMethod extends SetUpAnnotatedBaseClass {
public void setUp() {}
}
| 2,466
| 24.968421
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/AsyncFunctionReturnsNullNegativeCases.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import com.google.common.base.Function;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.function.Supplier;
import javax.annotation.Nullable;
/** Negative cases for {@link AsyncFunctionReturnsNull}. */
public class AsyncFunctionReturnsNullNegativeCases {
static {
new AsyncFunction<String, Object>() {
@Override
public ListenableFuture<Object> apply(String input) throws Exception {
return immediateFuture(null);
}
};
new Function<String, Object>() {
@Override
public Object apply(String input) {
return null;
}
};
new AsyncFunction<String, Object>() {
@Override
public ListenableFuture<Object> apply(String input) throws Exception {
return apply(input, input);
}
public ListenableFuture<Object> apply(String input1, String input2) {
return null;
}
};
new MyNonAsyncFunction<String, Object>() {
@Override
public ListenableFuture<Object> apply(String input) throws Exception {
return null;
}
};
new AsyncFunction<String, Object>() {
@Override
public ListenableFuture<Object> apply(String input) throws Exception {
Supplier<String> s =
() -> {
return null;
};
return immediateFuture(s.get());
}
};
}
interface MyNonAsyncFunction<I, O> {
ListenableFuture<O> apply(@Nullable I input) throws Exception;
}
}
| 2,266
| 28.828947
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NonAtomicVolatileUpdateNegativeCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/** Positive test cases for {@code NonAtomicVolatileUpdate} checker. */
public class NonAtomicVolatileUpdateNegativeCases {
private volatile int myVolatileInt = 0;
private int myInt = 0;
private volatile String myVolatileString = "";
private String myString = "";
public void incrementNonVolatile() {
myInt++;
++myInt;
myInt += 1;
myInt = myInt + 1;
myInt = 1 + myInt;
myInt = myVolatileInt + 1;
myVolatileInt = myInt + 1;
myString += "update";
myString = myString + "update";
}
public void decrementNonVolatile() {
myInt--;
--myInt;
myInt -= 1;
myInt = myInt - 1;
}
public synchronized void synchronizedIncrement() {
myVolatileInt++;
++myVolatileInt;
myVolatileInt += 1;
myVolatileInt = myVolatileInt + 1;
myVolatileInt = 1 + myVolatileInt;
myVolatileString += "update";
myVolatileString = myVolatileString + "update";
}
public void synchronizedBlock() {
synchronized (this) {
myVolatileInt++;
++myVolatileInt;
myVolatileInt += 1;
myVolatileInt = myVolatileInt + 1;
myVolatileInt = 1 + myVolatileInt;
myVolatileString += "update";
myVolatileString = myVolatileString + "update";
}
}
}
| 1,911
| 25.555556
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/PreconditionsExpensiveStringPositiveCase1.java
|
/*
* Copyright 2011 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.base.Preconditions;
/**
* Test for methodIs call involving String.format() and %s
*
* @author sjnickerson@google.com (Simon Nickerson)
*/
public class PreconditionsExpensiveStringPositiveCase1 {
public void error() {
int foo = 42;
int bar = 78;
Preconditions.checkState(true, String.format("The foo %s (%s) is not a good foo", foo, bar));
}
}
| 1,051
| 30.878788
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/HidingFieldPositiveCases1.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author sulku@google.com (Marsela Sulku)
* @author mariasam@google.com (Maria Sam)
*/
public class HidingFieldPositiveCases1 {
/** base class */
public static class ClassA {
protected String varOne;
public int varTwo;
String varThree;
}
/** ClassB has a field with the same name as one in its parent. */
public static class ClassB extends ClassA {
// BUG: Diagnostic contains: superclass: ClassA
private String varOne = "Test";
}
/** ClassC has a field with the same name as one in its grandparent. */
public static class ClassC extends ClassB {
// BUG: Diagnostic contains: superclass: ClassA
public int varTwo;
}
/**
* ClassD has multiple fields with the same name as those in its grandparent, as well as other
* unrelated members.
*/
public static class ClassD extends ClassB {
// BUG: Diagnostic contains: superclass: ClassA
protected int varThree;
// BUG: Diagnostic contains: superclass: ClassA
int varTwo;
String randOne;
String randTwo;
}
/** ClassE has same variable name as grandparent */
public static class ClassE extends ClassC {
// BUG: Diagnostic contains: superclass: ClassC
public String varTwo;
}
public static class ClassF extends ClassA {
@SuppressWarnings("HidingField") // no warning because it's suppressed
public String varThree;
}
public static class ClassG extends ClassF {
// BUG: Diagnostic contains: superclass: ClassF
String varThree;
}
}
| 2,169
| 29.138889
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/GetClassOnClassNegativeCases.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author chy@google.com (Christine Yang)
* @author kmuhlrad@google.com (Katy Muhlrad)
*/
public class GetClassOnClassNegativeCases {
public void getClassOnClass(Object obj) {
System.out.println(obj.getClass().getName());
}
public void getClassOnClass2() {
String s = "hi";
DummyObject.getClass(s);
}
public static class DummyObject {
public static boolean getClass(Object a) {
return true;
}
}
}
| 1,107
| 26.7
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsRefactoringComments.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author hanuszczak@google.com (Łukasz Hanuszczak)
*/
class UngroupedOverloadsRefactoringComments {
private void bar() {}
public static final String FOO = "foo"; // This is super-important comment for `foo`.
// Something about `bar`.
/** Does something. */
public void bar(int x) {}
// Something about this `bar`.
public void bar(int x, int y) {}
// Something about `baz`.
public static final String BAZ = "baz"; // Stuff about `baz` continues.
// More stuff about `bar`.
public void bar(int x, int y, int z) {
// Some internal comments too.
}
public void quux() {}
public void bar(String s) {}
}
| 1,306
| 26.808511
| 87
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/LongLiteralLowerCaseSuffixPositiveCase1.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* Positive cases for {@link LongLiteralLowerCaseSuffix}.
*/
public class LongLiteralLowerCaseSuffixPositiveCase1 {
// This constant string includes non-ASCII characters to make sure that we're not confusing
// bytes and chars:
@SuppressWarnings("unused")
private static final String TEST_STRING = "Îñţérñåţîöñåļîžåţîờñ";
public void positiveLowerCase() {
// BUG: Diagnostic contains: value = 123432L
long value = 123432l;
}
public void zeroLowerCase() {
// BUG: Diagnostic contains: value = 0L
long value = 0l;
}
public void negativeLowerCase() {
// BUG: Diagnostic contains: value = -123432L
long value = -123432l;
}
public void negativeExtraSpacesLowerCase() {
// BUG: Diagnostic contains: value = - 123432L
long value = - 123432l;
}
public void positiveHexLowerCase() {
// BUG: Diagnostic contains: value = 0x8abcDEF0L
long value = 0x8abcDEF0l;
// BUG: Diagnostic contains: value = 0X80L
value = 0X80l;
}
public void zeroHexLowerCase() {
// BUG: Diagnostic contains: value = 0x0L
long value = 0x0l;
// BUG: Diagnostic contains: value = 0X0L
value = 0X0l;
}
public void negativeHexLowerCase() {
// BUG: Diagnostic contains: value = -0x8abcDEF0L
long value = -0x8abcDEF0l;
// BUG: Diagnostic contains: value = -0X80L
value = -0X80l;
}
public void negativeHexExtraSpacesLowerCase() {
// BUG: Diagnostic contains: value = - 0x8abcDEF0L
long value = - 0x8abcDEF0l;
}
public void positiveOctalLowerCase() {
// BUG: Diagnostic contains: value = 06543L
long value = 06543l;
}
public void zeroOctalLowerCase() {
// BUG: Diagnostic contains: value = 00L
long value = 00l;
}
public void negativeOctalLowerCase() {
// BUG: Diagnostic contains: value = -06543L
long value = -06543l;
}
public void negativeOctalExtraSpacesLowerCase() {
// BUG: Diagnostic contains: value = - 06543L
long value = - 06543l;
}
}
| 2,688
| 27.010417
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/URLEqualsHashCodePositiveCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableSet;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Positive test cases for URLEqualsHashCode check.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
public class URLEqualsHashCodePositiveCases {
public void setOfURL() {
// BUG: Diagnostic contains: java.net.URL
Set<URL> urlSet = new HashSet<URL>();
}
public void setOfCompleteURL() {
// BUG: Diagnostic contains: java.net.URL
Set<java.net.URL> urlSet = new HashSet<java.net.URL>();
}
public void hashmapOfURL() {
// BUG: Diagnostic contains: java.net.URL
HashMap<URL, String> urlMap = new HashMap<URL, String>();
}
public void hashmapOfCompleteURL() {
// BUG: Diagnostic contains: java.net.URL
HashMap<java.net.URL, String> urlMap = new HashMap<java.net.URL, String>();
}
public void hashsetOfURL() {
// BUG: Diagnostic contains: java.net.URL
HashSet<URL> urlSet = new HashSet<URL>();
}
public void hashsetOfCompleteURL() {
// BUG: Diagnostic contains: java.net.URL
HashSet<java.net.URL> urlSet = new HashSet<java.net.URL>();
}
private static class ExtendedSet extends HashSet<java.net.URL> {
// no impl.
}
public void hashSetExtendedClass() {
// BUG: Diagnostic contains: java.net.URL
HashSet extendedSet = new ExtendedSet();
// BUG: Diagnostic contains: java.net.URL
Set urlSet = new ExtendedSet();
}
private static class ExtendedMap extends HashMap<java.net.URL, String> {
// no impl.
}
public void hashMapExtendedClass() {
// BUG: Diagnostic contains: java.net.URL
HashMap extendedMap = new ExtendedMap();
// BUG: Diagnostic contains: java.net.URL
Map urlMap = new ExtendedMap();
}
public void hashBiMapOfURL() {
// BUG: Diagnostic contains: java.net.URL
BiMap<URL, String> urlBiMap = HashBiMap.create();
// BUG: Diagnostic contains: java.net.URL
BiMap<String, URL> toUrlBiMap = HashBiMap.create();
}
public void hashBiMapOfCompleteURL() {
// BUG: Diagnostic contains: java.net.URL
HashBiMap<java.net.URL, String> urlBiMap = HashBiMap.create();
// BUG: Diagnostic contains: java.net.URL
HashBiMap<String, java.net.URL> toUrlBiMap = HashBiMap.create();
}
public void immutableSetOfURL() {
// BUG: Diagnostic contains: java.net.URL
ImmutableSet<URL> urlSet = ImmutableSet.of();
// BUG: Diagnostic contains: java.net.URL
ImmutableSet<URL> urlSet2 = ImmutableSet.<URL>builder().build();
}
}
| 3,321
| 28.39823
| 79
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfEqualsGuavaPositiveCase.java
|
/*
* Copyright 2011 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.base.Objects;
/**
* @author alexeagle@google.com (Alex Eagle)
*/
public class SelfEqualsGuavaPositiveCase {
private String field = "";
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SelfEqualsGuavaPositiveCase other = (SelfEqualsGuavaPositiveCase) o;
boolean retVal;
// BUG: Diagnostic contains: Objects.equal(field, other.field)
retVal = Objects.equal(field, field);
// BUG: Diagnostic contains: Objects.equal(other.field, this.field)
retVal &= Objects.equal(field, this.field);
// BUG: Diagnostic contains: Objects.equal(this.field, other.field)
retVal &= Objects.equal(this.field, field);
// BUG: Diagnostic contains: Objects.equal(this.field, other.field)
retVal &= Objects.equal(this.field, this.field);
return retVal;
}
@Override
public int hashCode() {
return Objects.hashCode(field);
}
public static void test() {
ForTesting tester = new ForTesting();
// BUG: Diagnostic contains: Objects.equal(tester.testing.testing, tester.testing)
Objects.equal(tester.testing.testing, tester.testing.testing);
}
private static class ForTesting {
public ForTesting testing;
public String string;
}
}
| 2,000
| 29.784615
| 86
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TearDownNotRunNegativeCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.internal.runners.JUnit38ClassRunner;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Not a JUnit 4 class (no @RunWith annotation on the class). */
public class JUnit4TearDownNotRunNegativeCases {
public void tearDown() {}
}
@RunWith(JUnit38ClassRunner.class)
class J4TearDownDifferentRunner {
public void tearDown() {}
}
@RunWith(JUnit4.class)
class J4TearDownHasAfter {
@After
public void tearDown() {}
}
@RunWith(JUnit4.class)
class J4TearDownExtendsTestCase extends TestCase {
public void tearDown() {}
}
@RunWith(JUnit4.class)
class J4TearDownPrivateTearDown {
private void tearDown() {}
}
@RunWith(JUnit4.class)
class J4TearDownPackageLocal {
void tearDown() {}
}
@RunWith(JUnit4.class)
class J4TearDownNonVoidReturnType {
int tearDown() {
return 42;
}
}
@RunWith(JUnit4.class)
class J4TearDownTearDownHasParameters {
public void tearDown(int ignored) {}
public void tearDown(boolean ignored) {}
public void tearDown(String ignored) {}
}
@RunWith(JUnit4.class)
class J4TearDownStaticTearDown {
public static void tearDown() {}
}
abstract class TearDownAnnotatedBaseClass {
@After
public void tearDown() {}
}
@RunWith(JUnit4.class)
class J4TearDownInheritsFromAnnotatedMethod extends TearDownAnnotatedBaseClass {
public void tearDown() {}
}
@RunWith(JUnit4.class)
class J4TearDownInheritsFromAnnotatedMethod2 extends TearDownAnnotatedBaseClass {
@After
public void tearDown() {}
}
| 2,197
| 22.891304
| 81
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ThrowsUncheckedExceptionNegativeCases.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author yulissa@google.com (Yulissa Arroyo-Paredes)
*/
public class ThrowsUncheckedExceptionNegativeCases {
public void doSomething() {
throw new IllegalArgumentException("thrown");
}
public void doMore() throws IOException {
throw new FileNotFoundException("thrown");
}
}
| 1,026
| 30.121212
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/WaitNotInLoopNegativeCases.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author eaftan@google.com (Eddie Aftandilian)
* <p>TODO(eaftan): Add test cases for enhanced for loop, loop outside synchronized block.
*/
public class WaitNotInLoopNegativeCases {
boolean flag = true;
public void test1() {
synchronized (this) {
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
}
public void test2() {
synchronized (this) {
while (!flag) {
try {
wait(1000);
} catch (InterruptedException e) {
}
}
}
}
public void test3() {
synchronized (this) {
while (!flag) {
try {
wait(1000, 1000);
} catch (InterruptedException e) {
}
}
}
}
// This code is incorrect, but this check should not flag it.
public void testLoopNotInSynchronized() {
while (!flag) {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
}
public void testDoLoop() {
synchronized (this) {
do {
try {
wait();
} catch (InterruptedException e) {
}
} while (!flag);
}
}
public void testForLoop() {
synchronized (this) {
for (; !flag; ) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
}
public void testEnhancedForLoop() {
int[] arr = new int[100];
synchronized (this) {
for (int i : arr) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
}
private void wait(Object obj) {}
public void testNotObjectWait() {
wait(new Object());
}
}
| 2,378
| 20.241071
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ShouldHaveEvenArgsMultimapNegativeCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
/**
* Negative test cases for {@link ShouldHaveEvenArgs} check.
*
* @author monnoroch@google.com (Max Strakhov)
*/
public class ShouldHaveEvenArgsMultimapNegativeCases {
private static final Multimap<String, String> multimap = ImmutableMultimap.of();
public void testWithMinimalArgs() {
assertThat(multimap).containsExactly("hello", "there");
}
public void testWithEvenArgs() {
assertThat(multimap).containsExactly("hello", "there", "hello", "there");
}
public void testWithVarargs(Object... args) {
assertThat(multimap).containsExactly("hello", args);
assertThat(multimap).containsExactly("hello", "world", args);
}
public void testWithArray() {
String[] arg = {"hello", "there"};
assertThat(multimap).containsExactly("yolo", arg);
String key = "hello";
Object[] value = new Object[] {};
Object[][] args = new Object[][] {};
assertThat(multimap).containsExactly(key, value);
assertThat(multimap).containsExactly(key, value, (Object[]) args);
assertThat(multimap).containsExactly(key, value, key, value, key, value);
}
}
| 1,913
| 31.440678
| 82
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ChainedAssertionLosesContextPositiveCases.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.truth.Truth.assertAbout;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth.assert_;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
public class ChainedAssertionLosesContextPositiveCases {
static final class FooSubject extends Subject {
private final Foo actual;
static Factory<FooSubject, Foo> foos() {
return FooSubject::new;
}
static FooSubject assertThat(Foo foo) {
return assertAbout(foos()).that(foo);
}
private FooSubject(FailureMetadata metadata, Foo actual) {
super(metadata, actual);
this.actual = actual;
}
void hasString(String expected) {
// BUG: Diagnostic contains: check("string()").that(actual.string()).isEqualTo(expected)
Truth.assertThat(actual.string()).isEqualTo(expected);
}
void hasOtherFooInteger(int expected) {
// BUG: Diagnostic contains:
// check("otherFoo().integer()").that(actual.otherFoo().integer()).isEqualTo(expected)
Truth.assertThat(actual.otherFoo().integer()).isEqualTo(expected);
}
FooSubject otherFooAbout() {
// BUG: Diagnostic contains: check("otherFoo()").about(foos()).that(actual.otherFoo())
return assertAbout(foos()).that(actual.otherFoo());
}
FooSubject otherFooThat() {
// BUG: Diagnostic contains: check("otherFoo()").about(foos()).that(actual.otherFoo())
return assertThat(actual.otherFoo());
}
void withMessage(String expected) {
// BUG: Diagnostic contains:
// check("string()").withMessage("blah").that(actual.string()).isEqualTo(expected)
assertWithMessage("blah").that(actual.string()).isEqualTo(expected);
}
void withMessageWithArgs(String expected) {
// BUG: Diagnostic contains:
// check("string()").withMessage("%s", "blah").that(actual.string()).isEqualTo(expected)
assertWithMessage("%s", "blah").that(actual.string()).isEqualTo(expected);
}
void plainAssert(String expected) {
// BUG: Diagnostic contains:
// check("string()").that(actual.string()).isEqualTo(expected)
assert_().that(actual.string()).isEqualTo(expected);
}
}
private static final class Foo {
final String string;
final int integer;
Foo(String string, int integer) {
this.string = string;
this.integer = integer;
}
String string() {
return string;
}
int integer() {
return integer;
}
Foo otherFoo() {
return this;
}
}
}
| 3,344
| 29.688073
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TearDownNotRunPositiveCaseCustomAfter.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Slightly funky test case with a custom After annotation) */
@RunWith(JUnit4.class)
public class JUnit4TearDownNotRunPositiveCaseCustomAfter {
// This will compile-fail and suggest the import of org.junit.After
// BUG: Diagnostic contains: @After
@After
public void tearDown() {}
}
@interface After {}
| 1,043
| 31.625
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ModifyingCollectionWithItselfNegativeCases.java
|
/*
* Copyright 2011 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.ArrayList;
import java.util.List;
/**
* @author scottjohnson@google.com (Scott Johnson)
*/
public class ModifyingCollectionWithItselfNegativeCases {
List<Integer> a = new ArrayList<Integer>();
public boolean addAll(List<Integer> b) {
return a.addAll(b);
}
public boolean removeAll(List<Integer> b) {
return a.removeAll(b);
}
public boolean retainAll(List<Integer> b) {
return a.retainAll(b);
}
public boolean containsAll(List<Integer> b) {
return a.containsAll(b);
}
}
| 1,190
| 25.466667
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ComparisonContractViolatedNegativeCases.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
public class ComparisonContractViolatedNegativeCases {
abstract static class IntOrInfinity implements Comparable<IntOrInfinity> {}
static class IntOrInfinityInt extends IntOrInfinity {
private final int value;
IntOrInfinityInt(int value) {
this.value = value;
}
@Override
public int compareTo(IntOrInfinity o) {
return (o instanceof IntOrInfinityInt)
? Integer.compare(value, ((IntOrInfinityInt) o).value)
: 1;
}
}
static class NegativeInfinity extends IntOrInfinity {
@Override
public int compareTo(IntOrInfinity o) {
return (o instanceof NegativeInfinity) ? 0 : -1;
}
}
}
| 1,324
| 29.113636
| 77
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BanSerializableReadNegativeCases.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.testdata;
import com.google.errorprone.bugpatterns.BanSerializableReadTest;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.Serializable;
/**
* {@link BanSerializableReadTest}
*
* @author tshadwell@google.com (Thomas Shadwell)
*/
public class BanSerializableReadNegativeCases implements Serializable, Externalizable {
public final String hi = "hi";
public Integer testField;
// mostly a smoke test
public static void noCrimesHere() {
System.out.println(new BanSerializableReadNegativeCases().hi);
}
/**
* The checker has a special allowlist that allows classes to define methods called readObject --
* Java accepts these as an override to the default serialization behaviour. While we want to
* allow such methods to be defined, we don't want to allow these methods to be called.
*
* <p>this version has the checks suppressed
*
* @throws IOException
* @throws ClassNotFoundException
*/
@SuppressWarnings("BanSerializableRead")
public static final void directCall() throws IOException, ClassNotFoundException {
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
ObjectOutputStream serializer = new ObjectOutputStream(out);
ObjectInputStream deserializer = new ObjectInputStream(in);
BanSerializableReadPositiveCases self = new BanSerializableReadPositiveCases();
self.readObject(deserializer);
}
/**
* Says 'hi' by piping the string value unsafely through Object I/O stream. This one has the check
* suppressed, though
*
* @throws IOException
* @throws ClassNotFoundException
*/
@SuppressWarnings("BanSerializableRead")
public static void sayHi() throws IOException, ClassNotFoundException {
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
ObjectOutputStream serializer = new ObjectOutputStream(out);
ObjectInputStream deserializer = new ObjectInputStream(in);
serializer.writeObject(new BanSerializableReadPositiveCases());
serializer.close();
BanSerializableReadPositiveCases crime =
(BanSerializableReadPositiveCases) deserializer.readObject();
System.out.println(crime.hi);
}
// These test the more esoteric annotations
// code has gone through a security review
@SuppressWarnings("BanSerializableRead")
public static void directCall2() throws IOException, ClassNotFoundException {
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
ObjectOutputStream serializer = new ObjectOutputStream(out);
ObjectInputStream deserializer = new ObjectInputStream(in);
BanSerializableReadPositiveCases self = new BanSerializableReadPositiveCases();
self.readObject(deserializer);
}
// code is well-tested legacy
@SuppressWarnings("BanSerializableRead")
public static final void directCall3() throws IOException, ClassNotFoundException {
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
ObjectOutputStream serializer = new ObjectOutputStream(out);
ObjectInputStream deserializer = new ObjectInputStream(in);
BanSerializableReadPositiveCases self = new BanSerializableReadPositiveCases();
self.readObject(deserializer);
}
// calls to readObject should themselves be excluded in a readObject method
void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
BanSerializableReadNegativeCases c = new BanSerializableReadNegativeCases();
c.readObject(ois);
ois.defaultReadObject();
}
private static class ObjectInputStreamIsExempt extends ObjectInputStream {
ObjectInputStreamIsExempt() throws IOException, ClassNotFoundException {
super();
}
@Override
public Object readObjectOverride() throws IOException, ClassNotFoundException {
// Calling readObjectOverride is banned by the checker; therefore, overrides can
// call other banned methods without added risk.
return super.readObject();
}
}
@Override
public void readExternal(ObjectInput in) {
try {
testField = (Integer) in.readObject();
} catch (IOException | ClassNotFoundException e) {
}
}
@Override
public void writeExternal(ObjectOutput out) {
try {
out.writeObject(testField);
} catch (IOException e) {
}
}
}
| 5,280
| 33.51634
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UnnecessaryBoxedVariableCases_expected.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nullable;
/** @author awturner@google.com (Andy Turner) */
class UnnecessaryBoxedVariableCases {
void positive_local() {
int i = 0;
}
int positive_local_return() {
int i = 0;
return i;
}
Integer positive_local_addition() {
int i = 0;
return i + 1;
}
void positive_local_compoundAddition(Integer addend) {
int i = 0;
i += addend;
int j = 0;
j += i;
}
void positive_methodInvocation() {
int i = 0;
methodPrimitiveArg(i);
}
void negative_methodInvocation() {
Integer i = 0;
methodBoxedArg(i);
}
void positive_assignedValueOf() {
int i = Integer.valueOf(0);
}
int positive_assignedValueOf_return() {
int i = Integer.valueOf(0);
return i;
}
int positive_noInitializer() {
int i;
i = 0;
return i;
}
void negative_enhancedForLoopOverCollection(List<Integer> list) {
for (Integer i : list) {}
}
void negative_enhancedForLoopOverWrappedArray(Integer[] array) {
for (Integer i : array) {}
}
void positive_enhancedForLoopOverPrimitiveArray(int[] array) {
for (int i : array) {}
}
final void negative_invokeMethod(Integer i) throws InterruptedException {
i.wait(0);
}
final Object[] negative_objectArray(Long l) {
return new Object[] {"", l};
}
void negative_null() {
Integer i = null;
}
void negative_null_noInitializer() {
Integer i;
i = null;
i = 0;
}
void negative_null_reassignNull() {
Integer i = 0;
i = null;
}
void negative_enhancedForLoopOverPrimitiveArray_assignInLoop(int[] array) {
for (Integer i : array) {
i = null;
}
}
void negative_boxedVoid() {
Void v;
}
int negative_assignmentInReturn() {
Integer myVariable;
return myVariable = methodBoxedArg(42);
}
int positive_assignmentInReturn() {
int myVariable;
return myVariable = Integer.valueOf(42);
}
int positive_assignmentInReturn2() {
int myVariable;
return myVariable = Integer.valueOf(42);
}
int positive_hashCode() {
int myVariable = 0;
return Integer.hashCode(myVariable);
}
short positive_castMethod() {
int myVariable = 0;
return (short) myVariable;
}
int positive_castMethod_sameType() {
int myVariable = 0;
return myVariable;
}
void positive_castMethod_statementExpression() {
int myVariable = 0;
}
void negative_methodReference() {
Integer myVariable = 0;
Stream<Integer> stream = Stream.of(1).filter(myVariable::equals);
}
static void positive_parameter_staticMethod(boolean b) {
boolean a = b;
}
static void negative_parameter_staticMethod(Boolean b) {
System.out.println("a " + b);
}
static boolean positive_parameter_returnType(boolean b) {
return b;
}
void negative_parameter_instanceMethod_nonFinal(Boolean b) {
boolean a = b;
}
final void negative_parameter_instanceMethod_final(boolean b) {
boolean a = b;
}
static void negative_parameter_unused(Integer i) {}
static void positive_removeNullable_parameter(int i) {
int j = i;
}
static void positive_removeNullable_localVariable() {
int i = 0;
int j = 0;
int k = i + j;
}
static int positive_nullChecked_expression(int i) {
return i;
}
static int positive_nullChecked_expression_message(int i) {
return i;
}
static int positive_nullChecked_statement(int i) {
return i;
}
static int positive_nullChecked_statement_message(int i) {
return i;
}
private void methodPrimitiveArg(int i) {}
private Integer methodBoxedArg(Integer i) {
return i;
}
}
| 4,426
| 19.882075
| 77
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FallThroughNegativeCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.io.FileInputStream;
import java.io.IOException;
public class FallThroughNegativeCases {
public class AllowAnyComment {
public int numTweets = 55000000;
public int everyBodyIsDoingIt(int a, int b) {
switch (a) {
case 1:
System.out.println("1");
// fall through
case 2:
System.out.println("2");
break;
default:
}
return 0;
}
}
static class EmptyDefault {
static void foo(String s) {
switch (s) {
case "a":
case "b":
throw new RuntimeException();
default:
// do nothing
}
}
static void bar(String s) {
switch (s) {
default:
}
}
}
class TerminatedSynchronizedBlock {
private final Object o = new Object();
int foo(int i) {
switch (i) {
case 0:
synchronized (o) {
return i;
}
case 1:
return -1;
default:
return 0;
}
}
}
class TryWithNonTerminatingFinally {
int foo(int i) {
int z = 0;
switch (i) {
case 0:
try {
return i;
} finally {
z++;
}
case 1:
return -1;
default:
return 0;
}
}
}
abstract class TryWithTerminatingCatchBlocks {
int foo(int i) {
int z = 0;
switch (i) {
case 0:
try {
return bar();
} catch (RuntimeException e) {
log(e);
throw e;
} catch (Exception e) {
log(e);
throw new RuntimeException(e);
}
case 1:
return -1;
default:
return 0;
}
}
int tryWithResources(String path, int i) {
switch (i) {
case 0:
try (FileInputStream f = new FileInputStream(path)) {
return f.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
case 1:
try (FileInputStream f = new FileInputStream(path)) {
return f.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
default:
throw new RuntimeException("blah");
}
}
abstract int bar() throws Exception;
void log(Throwable e) {}
}
class TryWithTerminatingFinally {
int foo(int i) {
int z = 0;
switch (i) {
case 0:
try {
z++;
} finally {
return i;
}
case 1:
return -1;
default:
return 0;
}
}
}
}
| 3,351
| 19.564417
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnitAssertSameCheckPositiveCase.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* Positive test cases for {@link JUnitAssertSameCheck} check.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
public class JUnitAssertSameCheckPositiveCase {
public void test(Object obj) {
// BUG: Diagnostic contains: An object is tested for reference equality to itself using JUnit
org.junit.Assert.assertSame(obj, obj);
// BUG: Diagnostic contains: An object is tested for reference equality to itself using JUnit
org.junit.Assert.assertSame("message", obj, obj);
// BUG: Diagnostic contains: An object is tested for reference equality to itself using JUnit
junit.framework.Assert.assertSame(obj, obj);
// BUG: Diagnostic contains: An object is tested for reference equality to itself using JUnit
junit.framework.Assert.assertSame("message", obj, obj);
}
}
| 1,473
| 35.85
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TreeToStringPositiveCases.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree;
public class TreeToStringPositiveCases {
public static class InnerClass extends BugChecker {
private static void foo() {
Tree tree = (Tree) new Object();
// BUG: Diagnostic contains: [TreeToString] Tree#toString shouldn't be used
tree.toString();
}
private static final Matcher<ClassTree> MATCHER1 =
(tree, state) -> {
ExpressionTree packageName = state.getPath().getCompilationUnit().getPackageName();
// BUG: Diagnostic contains: [TreeToString] Tree#toString shouldn't be used
packageName.toString();
// BUG: Diagnostic contains: [TreeToString] Tree#toString shouldn't be used
state.getPath().getCompilationUnit().getPackageName().toString();
return false;
};
private static final Matcher<ClassTree> MATCHER2 =
new Matcher<ClassTree>() {
@Override
public boolean matches(ClassTree classTree, VisitorState state) {
ExpressionTree packageName = state.getPath().getCompilationUnit().getPackageName();
// BUG: Diagnostic contains:
packageName.toString();
return false;
}
};
}
}
| 2,056
| 35.087719
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfAssignmentPositiveCases2.java
|
/*
* Copyright 2011 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
/**
* Tests for self assignment
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
public class SelfAssignmentPositiveCases2 {
private int a;
private Foo foo;
// BUG: Diagnostic contains: private static final Object obj
private static final Object obj = SelfAssignmentPositiveCases2.obj;
// BUG: Diagnostic contains: private static final Object obj2
private static final Object obj2 = checkNotNull(SelfAssignmentPositiveCases2.obj2);
public void test6() {
Foo foo = new Foo();
foo.a = 2;
// BUG: Diagnostic contains: remove this line
foo.a = foo.a;
// BUG: Diagnostic contains: checkNotNull(foo.a)
foo.a = checkNotNull(foo.a);
// BUG: Diagnostic contains: requireNonNull(foo.a)
foo.a = requireNonNull(foo.a);
}
public void test7() {
Foobar f = new Foobar();
f.foo = new Foo();
f.foo.a = 10;
// BUG: Diagnostic contains: remove this line
f.foo.a = f.foo.a;
// BUG: Diagnostic contains: checkNotNull(f.foo.a)
f.foo.a = checkNotNull(f.foo.a);
// BUG: Diagnostic contains: requireNonNull(f.foo.a)
f.foo.a = requireNonNull(f.foo.a);
}
public void test8() {
foo = new Foo();
// BUG: Diagnostic contains: remove this line
this.foo.a = foo.a;
// BUG: Diagnostic contains: checkNotNull(foo.a)
this.foo.a = checkNotNull(foo.a);
// BUG: Diagnostic contains: requireNonNull(foo.a)
this.foo.a = requireNonNull(foo.a);
}
public void test9(Foo fao, Foo bar) {
// BUG: Diagnostic contains: this.foo = fao
this.foo = foo;
// BUG: Diagnostic contains: this.foo = checkNotNull(fao)
this.foo = checkNotNull(foo);
// BUG: Diagnostic contains: this.foo = requireNonNull(fao)
this.foo = requireNonNull(foo);
}
public void test10(Foo foo) {
// BUG: Diagnostic contains: this.foo = foo
foo = foo;
// BUG: Diagnostic contains: this.foo = checkNotNull(foo)
foo = checkNotNull(foo);
// BUG: Diagnostic contains: this.foo = requireNonNull(foo)
foo = requireNonNull(foo);
}
class Test11 {
final Foo foo;
Foo fao;
Test11(Foo foo) {
if (true) {
// BUG: Diagnostic contains: this.fao = foo
foo = foo;
}
this.foo = foo;
}
public void test11a(Foo foo) {
// BUG: Diagnostic contains: this.fao = foo
foo = foo;
}
}
private static class Foo {
int a;
}
private static class Bar {
int a;
}
private static class Foobar {
Foo foo;
Bar bar;
}
}
| 3,275
| 26.529412
| 85
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EqualsIncompatibleTypeRecursiveTypes.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.time.DayOfWeek;
import java.time.Month;
import java.util.Objects;
/** Checks for objects with recursive type bounds. */
public class EqualsIncompatibleTypeRecursiveTypes {
interface Bar<X, Y> {}
final class ConcreteBar<X, Y> implements Bar<X, Y> {}
static class Foo<T extends Enum<T>> implements Bar<String, T> {
T field;
void check(Foo<?> other) {
// OK since Enum<?> and Enum<T> are not incompatible
this.field.equals(other.field);
}
<X extends ConcreteBar<String, X>> void badCheck(Bar<String, X> other) {
// BUG: Diagnostic contains: T and X are incompatible
this.equals(other);
}
}
interface RandomInterface {}
interface Entity<
E extends Entity<E, K, V, V2>,
K extends EntityKey<K>,
V extends Enum<V>,
V2 extends Enum<V2>> {}
interface EntityKey<K extends EntityKey<K>> extends Comparable<K> {}
static final class EK1 implements EntityKey<EK1> {
@Override
public int compareTo(EK1 o) {
return 0;
}
}
static final class E1 implements Entity<E1, EK1, DayOfWeek, Month>, RandomInterface {}
static final class E2 implements Entity<E2, EK1, Month, DayOfWeek>, RandomInterface {}
void testMultilayer(Class<? extends Entity<?, ?, ?, ?>> eClazz, Class<? extends E2> e2Clazz) {
if (Objects.equals(eClazz, E1.class)) {
System.out.println("yay");
}
if (Objects.equals(eClazz, E2.class)) {
System.out.println("yay");
}
if (Objects.equals(e2Clazz, E2.class)) {
System.out.println("yay");
}
// BUG: Diagnostic contains: E2 and E1 are incompatible.
if (Objects.equals(e2Clazz, E1.class)) {
System.out.println("boo");
}
}
interface First<A extends First<A>> {
default A get() {
return null;
}
}
interface Second<B> extends First<Second<B>> {}
interface Third extends Second<Third> {}
interface Fourth extends Second<Fourth> {}
void testing(Third third, Fourth fourth) {
// BUG: Diagnostic contains: Third and Fourth
boolean equals = third.equals(fourth);
}
interface RecOne extends Comparable<Comparable<RecOne>> {}
interface RecTwo extends Comparable<Comparable<RecTwo>> {}
void testMultiRecursion(RecOne a, RecTwo b) {
// BUG: Diagnostic contains: RecOne and RecTwo
boolean bad = a.equals(b);
}
interface Quux<A extends Quux<A>> {}
interface Quuz<A extends Quux<A>> extends Quux<A> {}
interface Quiz<A extends Quux<A>> extends Quux<A> {}
interface Id1 extends Quuz<Id1> {}
interface Id2 extends Quiz<Id2> {}
abstract static class Id3 implements Quuz<Id3>, Quiz<Id3> {}
void test(Id1 first, Id3 second) {
// BUG: Diagnostic contains: Id1 and Id3
boolean res = Objects.equals(first, second);
}
class I<T> {}
class J<A extends I<B>, B extends I<C>, C extends I<A>> {}
<
A1 extends I<B1>,
B1 extends I<C1>,
C1 extends I<A1>,
A2 extends I<B2>,
B2 extends I<C2>,
C2 extends I<A2>>
void something(J<A1, B1, C1> j1, J<A2, B2, C2> j2) {
// Technically this could work, since there's nothing stopping A1 == A2, etc.
boolean equals = j1.equals(j2);
}
}
| 3,872
| 26.083916
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsRefactoringInterleaved_expected.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author hanuszczak@google.com (Łukasz Hanuszczak)
*/
class UngroupedOverloadsRefactoringInterleaved {
public void foo() {}
public void foo(int x) {}
public void foo(int x, int y) {}
public void foo(int x, int y, int z) {}
public void baz() {}
public void baz(int x) {}
public void baz(int x, int y) {}
public void bar() {}
public void bar(int x) {}
public void bar(int x, int y) {}
public void quux() {}
public void quux(int x) {}
public void quux(int x, int y) {}
}
| 1,176
| 22.54
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EqualsReferenceNegativeCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/** Created by mariasam on 6/23/17. */
public class EqualsReferenceNegativeCases {
@Override
public boolean equals(Object o) {
return (this == o);
}
class OtherEquals {
@Override
public boolean equals(Object o) {
if (o.equals("hi")) {
return true;
} else {
return o == this;
}
}
}
class EqualsThisLast {
@Override
public boolean equals(Object o) {
if (o instanceof EqualsThisLast) {
return true;
}
return o.equals(this);
}
}
class Foo {
@Override
public boolean equals(Object o) {
return o instanceof Foo && this.equals((Foo) o);
}
public boolean equals(Foo o) {
return true;
}
}
class OtherEqualsMethod {
@Override
public boolean equals(Object o) {
return equals((String) o);
}
public boolean equals(String o) {
return true;
}
}
class CodeBase {
public CodeBase(Object o) {}
public boolean equals(Object obj) {
CodeBase other = (CodeBase) obj;
return equals(new CodeBase(other.getValue()));
}
public Object getValue() {
return null;
}
}
}
| 1,827
| 21.292683
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TruthSelfEqualsNegativeCases.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.truth.Truth.assertThat;
/**
* Negative test cases for TruthSelfEquals check.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
public class TruthSelfEqualsNegativeCases {
public void testEq() {
assertThat(Boolean.TRUE.toString()).isEqualTo(Boolean.FALSE.toString());
}
public void testNeq() {
assertThat(Boolean.TRUE.toString()).isNotEqualTo(Boolean.FALSE.toString());
}
}
| 1,092
| 29.361111
| 79
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit3TestNotRunPositiveCases.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import junit.framework.TestCase;
/**
* @author rburny@google.com (Radoslaw Burny)
*/
public class JUnit3TestNotRunPositiveCases extends TestCase {
// BUG: Diagnostic contains: JUnit3TestNotRun
public static void tesNameStatic() {}
// These names are trickier to correct, but we should still indicate the bug
// BUG: Diagnostic contains: JUnit3TestNotRun
public void tetsName() {}
// BUG: Diagnostic contains: JUnit3TestNotRun
public void tesstName() {}
// BUG: Diagnostic contains: JUnit3TestNotRun
public void tesetName() {}
// BUG: Diagnostic contains: JUnit3TestNotRun
public void tesgName() {}
// tentative - can cause false positives
// BUG: Diagnostic contains: JUnit3TestNotRun
public void textName() {}
}
| 1,411
| 30.377778
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/DepAnnNegativeCase2.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @deprecated
*/
@Deprecated
public class DepAnnNegativeCase2 {
abstract class Builder2<P> {
class SummaryRowKey<P> {}
@Deprecated
/**
* @deprecated use {@link Selector.Builder#withSummary()}
*/
public abstract void withSummaryRowKeys(int summaryRowKeys);
/**
* @deprecated use {@link Selector.Builder#withSummary()}
*/
@Deprecated
public abstract void m1();
public abstract void m2();
}
}
| 1,118
| 25.023256
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FinallyPositiveCase1.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* When a finally statement is exited because of a return, throw, break, or continue statement,
* unintuitive behaviour can occur. Consider:
*
* <pre>
* {@code
* finally foo() {
* try {
* return true;
* } finally {
* return false;
* }
* }
* </pre>
*
* Because the finally block always executes, the first return statement has no effect and the
* method will return false.
*
* @author eaftan@google.com (Eddie Aftandilian)
* @author cushon@google.com (Liam Miller-Cushon)
*/
public class FinallyPositiveCase1 {
public static void test1() {
while (true) {
try {
} finally {
// BUG: Diagnostic contains:
break;
}
}
}
public static void test2() {
while (true) {
try {
} finally {
// BUG: Diagnostic contains:
continue;
}
}
}
public static void test3() {
try {
} finally {
// BUG: Diagnostic contains:
return;
}
}
public static void test4() throws Exception {
try {
} finally {
// BUG: Diagnostic contains:
throw new Exception();
}
}
/**
* break statement jumps to outer labeled while, not inner one.
*/
public void test5() {
label:
while (true) {
try {
} finally {
while (true) {
// BUG: Diagnostic contains:
break label;
}
}
}
}
/**
* continue statement jumps to outer labeled for, not inner one.
*/
public void test6() {
label:
for (;;) {
try {
} finally {
for (;;) {
// BUG: Diagnostic contains:
continue label;
}
}
}
}
/**
* continue statement jumps to while, not switch.
*/
public void test7() {
int i = 10;
while (true) {
try {
} finally {
switch (i) {
case 10:
// BUG: Diagnostic contains:
continue;
}
}
}
}
public void test8() {
try {
} finally {
// BUG: Diagnostic contains:
{ { { { { { { { { { return; } } } } } } } } } }
}
}
// Don't assume that completion statements occur inside methods:
static boolean flag = false;
static {
while (flag) {
try {
} finally {
// BUG: Diagnostic contains:
break;
}
}
}
}
| 3,010
| 19.482993
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayToStringCompoundAssignmentNegativeCases.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author adgar@google.com (Mike Edgar)
*/
public class ArrayToStringCompoundAssignmentNegativeCases {
public void concatenateCompoundAssign_object() {
Object a = new Object();
String b = " a string";
b += a;
}
public void concatenateCompoundAssign_int() {
int a = 5;
String b = " a string ";
b += a;
}
}
| 1,006
| 27.771429
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsRefactoringMultiple_expected.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author hanuszczak@google.com (Łukasz Hanuszczak)
*/
class UngroupedOverloadsRefactoringMultiple {
public void foo() {}
public void foo(int x) {}
public void foo(int x, int y) {}
public void foo(int x, int y, int z) {}
private static class foo {}
public void bar() {}
public static final String BAZ = "baz";
public void quux() {}
public void quux(int x) {}
public void quux(int x, int y) {}
public void quux(int x, int y, int z) {}
public static final int X = 0;
public static final int Y = 1;
private int quux;
public void norf() {}
public void thud() {}
}
| 1,275
| 22.2
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ComparableTypeNegativeCases.java
|
/* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.io.Serializable;
import java.util.Comparator;
public class ComparableTypeNegativeCases {
/** Class that implements comparable, with castable type */
public static class ComparableTypeNegative implements Comparable<ComparableTypeNegative> {
@Override
public int compareTo(ComparableTypeNegative o) {
return 0;
}
}
/** abstract class that implements comparable */
public abstract static class OnlyComparable implements Comparable<OnlyComparable> {}
/** class that implements comparable and something else like Serializable */
public static class SerializableComparable
implements Serializable, Comparable<SerializableComparable> {
@Override
public int compareTo(SerializableComparable o) {
return 0;
}
}
/** class that implements comparable and something else with a type */
public static class SomeClass implements Comparable<SomeClass>, Comparator<SomeClass> {
@Override
public int compareTo(SomeClass comparableNode) {
return 0;
}
@Override
public int compare(SomeClass a, SomeClass b) {
return 0;
}
}
// Example interfaces
interface Door {}
public static class HalfOpen implements Door {}
// BUG: Diagnostic contains: [ComparableType]
static final class Open extends HalfOpen implements Comparable<Door> {
@Override
public int compareTo(Door o) {
return 0;
}
}
public static class A {}
// BUG: Diagnostic contains: [ComparableType]
public static class B extends A implements Comparable<A> {
@Override
public int compareTo(A o) {
return 0;
}
}
// ignore enums
enum Location {
TEST_TARGET
}
public abstract static class AClass implements Comparable<AClass> {}
public static class BClass extends AClass {
@Override
public int compareTo(AClass o) {
return 0;
}
}
abstract class Foo<T> implements Comparable<Foo<T>> {}
class T extends Foo<String> {
public int compareTo(Foo<String> o) {
return 0;
}
}
// BUG: Diagnostic contains: [ComparableType]
static final class XGram implements Comparable {
@Override
public int compareTo(Object o) {
return 0;
}
}
}
| 2,878
| 24.477876
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EqualsHashCodeTestNegativeCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class EqualsHashCodeTestNegativeCases {
public static class EqualsAndHashCode {
public boolean equals(Object o) {
return false;
}
public int hashCode() {
return 42;
}
}
public static class HashCodeOnly {
public int hashCode() {
return 42;
}
}
public static class Neither {}
}
| 948
| 24.648649
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BanClassLoaderNegativeCases.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.security.SecureClassLoader;
class BanClassLoaderPositiveCases {
/** OK to extend SecureClassLoader */
class AnotherSecureClassLoader extends SecureClassLoader {}
/** OK to call loadClass if it's not on RMIClassLoader */
public final Class<?> overrideClassLoader() throws ClassNotFoundException {
SecureClassLoader loader = new AnotherSecureClassLoader();
return loader.loadClass("BadClass");
}
/** OK to define loadClass */
private class NotClassLoader {
protected void loadClass() {}
}
}
| 1,194
| 32.194444
| 77
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayToStringNegativeCases.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.*;
/**
* @author adgar@google.com (Mike Edgar)
*/
public class ArrayToStringNegativeCases {
public void objectEquals() {
Object a = new Object();
if (a.toString().isEmpty()) {
System.out.println("string is empty!");
} else {
System.out.println("string is not empty!");
}
}
}
| 990
| 27.314286
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/PreconditionsInvalidPlaceholderPositiveCase1.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Preconditions;
import com.google.common.base.Verify;
public class PreconditionsInvalidPlaceholderPositiveCase1 {
int foo;
public void checkPositive(int x) {
// BUG: Diagnostic contains: %s > 0
checkArgument(x > 0, "%d > 0", x);
}
public void checkFoo() {
// BUG: Diagnostic contains: foo must be equal to 0 but was %s
Preconditions.checkState(foo == 0, "foo must be equal to 0 but was {0}", foo);
}
public void verifyFoo(int x) {
// BUG: Diagnostic contains:
Verify.verify(x > 0, "%d > 0", x);
}
}
| 1,299
| 29.952381
| 82
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayToStringCompoundAssignmentPositiveCases.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.*;
/**
* @author adgar@google.com (Mike Edgar)
*/
public class ArrayToStringCompoundAssignmentPositiveCases {
private static final int[] a = {1, 2, 3};
public void stringVariableAddsArrayAndAssigns() {
String b = "a string";
// BUG: Diagnostic contains: += Arrays.toString(a)
b += a;
}
}
| 990
| 28.147059
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TruthConstantAssertsNegativeCases.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.truth.Truth.assertThat;
/**
* Negative test cases for TruthConstantAsserts check.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
public class TruthConstantAssertsNegativeCases {
public void testNegativeCases() {
assertThat(new TruthConstantAssertsNegativeCases()).isEqualTo(Boolean.TRUE);
assertThat(getObject()).isEqualTo(Boolean.TRUE);
// assertion called on constant with constant expectation is ignored.
assertThat(Boolean.FALSE).isEqualTo(4.2);
}
private static TruthConstantAssertsNegativeCases getObject() {
return new TruthConstantAssertsNegativeCases();
}
}
| 1,302
| 31.575
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NullablePrimitiveNegativeCases.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import javax.annotation.Nullable;
/**
* @author sebastian.h.monte@gmail.com (Sebastian Monte)
*/
public class NullablePrimitiveNegativeCases {
@Nullable Integer a;
public void method(@Nullable Integer a) {}
@Nullable
public Integer method() {
return Integer.valueOf(0);
}
}
| 955
| 27.117647
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MultipleParallelOrSequentialCallsPositiveCases_expected.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
/**
* @author @mariasam (Maria Sam) on 7/6/17.
*/
class MultipleParallelOrSequentialCallsPositiveCases {
public void basicCaseParallel(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel();'?
list.stream().parallel();
}
public void basicCaseParallelNotFirst(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel().map(m -> m);'?
list.stream().parallel().map(m -> m);
}
public void basicCollection(Collection<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel();'?
list.stream().parallel();
}
public void parallelStream(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.parallelStream();'?
list.parallelStream();
}
public void basicCaseParallelThisInMethodArg(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'this.hello(list.stream().parallel());'?
this.hello(list.stream().parallel());
}
public void onlyOneError(List<String> list) {
this.hello(
// BUG: Diagnostic contains: Multiple calls
list.stream().parallel());
}
public void mapMethod(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'hello(list.stream().parallel().map(m ->
// this.hello(null)));'?
hello(list.stream().parallel().map(m -> this.hello(null)));
}
public void betweenMethods(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel().map(m -> m.toString());'?
list.stream().parallel().map(m -> m.toString());
}
public void basicCaseParallelNotLast(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel().map(m ->
// m.toString()).findFirst();'?
list.stream().parallel().map(m -> m.toString()).findFirst();
}
public void basicCaseSequential(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().sequential().map(m -> m.toString());'?
list.stream().sequential().map(m -> m.toString());
}
public void bothSequentialAndParallel(List<String> list) {
// this case is unlikely (wrong, even) but just checking that this works
// BUG: Diagnostic contains: Did you mean 'list.stream().sequential().parallel();'?
list.stream().sequential().parallel();
}
public void bothSequentialAndParallelMultiple(List<String> list) {
// this is even more messed up, this test is here to make sure the checker doesn't throw an
// exception
// BUG: Diagnostic contains: Multiple calls
list.stream().sequential().parallel().parallel();
}
public void parallelMultipleLines(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel()
list.stream().parallel().map(m -> m.toString());
}
public void multipleParallelCalls(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.parallelStream();'?
list.parallelStream();
}
public String hello(Stream st) {
return "";
}
public void streamWithinAStream(List<String> list, List<String> list2) {
// BUG: Diagnostic contains: Did you mean
list.stream().parallel().flatMap(childDir -> list2.stream()).flatMap(a -> list2.stream());
}
public void streamWithinAStreamImmediatelyAfterOtherParallel(
List<String> list, List<String> list2) {
// BUG: Diagnostic contains: Did you mean
list.stream().parallel().map(m -> list2.stream().parallel());
}
public void parallelAndNestedStreams(List<String> list, List<String> list2) {
// BUG: Diagnostic contains: Did you mean
list.parallelStream()
.flatMap(childDir -> list2.stream())
.filter(m -> (new TestClass("test")).testClass())
.map(
a -> {
if (a == null) {
return a;
}
return null;
})
.filter(a -> a != null)
.flatMap(a -> list2.stream());
}
private class TestClass {
public TestClass(String con) {}
private boolean testClass() {
return true;
}
}
}
| 4,813
| 32.901408
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EmptyCatchNegativeCases.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 org.junit.Assert.fail;
import java.io.FileNotFoundException;
import org.junit.Test;
/**
* @author yuan@ece.toronto.edu (Ding Yuan)
*/
public class EmptyCatchNegativeCases {
public void error() throws IllegalArgumentException {
throw new IllegalArgumentException("Fake exception.");
}
public void harmlessError() throws FileNotFoundException {
throw new FileNotFoundException("harmless exception.");
}
public void close() throws IllegalArgumentException {
// close() is an allowed method, so any exceptions
// thrown by this method can be ignored!
throw new IllegalArgumentException("Fake exception.");
}
public void handledException() {
int a = 0;
try {
error();
} catch (Exception e) {
a++; // handled here
}
}
public void exceptionHandledByDataflow() {
int a = 0;
try {
error();
a = 10;
} catch (Throwable t) {
/* Although the exception is ignored here, it is actually
* handled by the if check below.
*/
}
if (a != 10) {
System.out.println("Exception is handled here..");
a++;
}
}
public void exceptionHandledByControlFlow() {
try {
error();
return;
} catch (Throwable t) {
/* Although the exception is ignored here, it is actually
* handled by the return statement in the try block.
*/
}
System.out.println("Exception is handled here..");
}
public void alreadyInCatch() {
try {
error();
} catch (Throwable t) {
try {
error();
} catch (Exception e) {
// Although e is ignored, it is OK b/c we're already
// in a nested catch block.
}
}
}
public void harmlessException() {
try {
harmlessError();
} catch (FileNotFoundException e) {
/* FileNotFoundException is a harmless exception and
* it is OK to ignore it.
*/
}
}
public void exemptedMethod() {
try {
close();
} catch (Exception e) {
// Although the exception is ignored, we can allow this b/c
// it is thrown by an exempted method.
}
}
public void comment() {
int a = 0; // TODO
try {
error();
// TODO
/* FIXME */
} catch (Throwable t) {
// ignored
}
}
public void catchIsLoggedOnly() {
try {
error();
} catch (Throwable t) {
System.out.println("Caught an exception: " + t);
}
}
@Test
public void expectedException() {
try {
System.err.println();
fail();
} catch (Exception expected) {
}
}
}
| 3,260
| 22.460432
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EqualsHashCodeTestPositiveCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class EqualsHashCodeTestPositiveCases {
public static class EqualsOnly {
// BUG: Diagnostic contains: Classes that override equals should also override hashCode
public boolean equals(Object o) {
return false;
}
}
}
| 854
| 31.884615
| 91
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/HidingFieldPositiveCases2.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author sulku@google.com (Marsela Sulku)
* @author mariasam@google.com (Maria Sam)
*/
public class HidingFieldPositiveCases2 {
/**
* ClassA extends a class from a different file and ClassA has a member with the same name as its
* parent
*/
public class ClassA extends HidingFieldPositiveCases1.ClassB {
// BUG: Diagnostic contains: superclass: ClassA
private int varTwo;
}
/**
* ClassB extends a class from a different file and ClassB has a member with the same name as its
* grandparent
*/
public class ClassB extends HidingFieldPositiveCases1.ClassB {
// BUG: Diagnostic contains: superclass: ClassA
public int varOne = 2;
}
}
| 1,347
| 31.095238
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TruthConstantAssertsPositiveCases.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.truth.Truth.assertThat;
/**
* Positive test cases for TruthConstantAsserts check.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
public class TruthConstantAssertsPositiveCases {
public void testAssertThat() {
// BUG: Diagnostic contains: assertThat(new TruthConstantAssertsPositiveCases()).isEqualTo(1);
assertThat(1).isEqualTo(new TruthConstantAssertsPositiveCases());
// BUG: Diagnostic contains: assertThat(someStaticMethod()).isEqualTo("my string");
assertThat("my string").isEqualTo(someStaticMethod());
// BUG: Diagnostic contains: assertThat(memberMethod()).isEqualTo(42);
assertThat(42).isEqualTo(memberMethod());
// BUG: Diagnostic contains: assertThat(someStaticMethod()).isEqualTo(42L);
assertThat(42L).isEqualTo(someStaticMethod());
// BUG: Diagnostic contains: assertThat(new Object()).isEqualTo(4.2);
assertThat(4.2).isEqualTo(new Object());
}
private static TruthConstantAssertsPositiveCases someStaticMethod() {
return new TruthConstantAssertsPositiveCases();
}
private TruthConstantAssertsPositiveCases memberMethod() {
return new TruthConstantAssertsPositiveCases();
}
}
| 1,860
| 34.113208
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NonAtomicVolatileUpdatePositiveCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/** Positive test cases for {@code NonAtomicVolatileUpdate} checker. */
public class NonAtomicVolatileUpdatePositiveCases {
private static class VolatileContainer {
public volatile int volatileInt = 0;
}
private volatile int myVolatileInt = 0;
private VolatileContainer container = new VolatileContainer();
public void increment() {
// BUG: Diagnostic contains:
myVolatileInt++;
// BUG: Diagnostic contains:
++myVolatileInt;
// BUG: Diagnostic contains:
myVolatileInt += 1;
// BUG: Diagnostic contains:
myVolatileInt = myVolatileInt + 1;
// BUG: Diagnostic contains:
myVolatileInt = 1 + myVolatileInt;
// BUG: Diagnostic contains:
if (myVolatileInt++ == 0) {
System.out.println("argh");
}
// BUG: Diagnostic contains:
container.volatileInt++;
// BUG: Diagnostic contains:
++container.volatileInt;
// BUG: Diagnostic contains:
container.volatileInt += 1;
// BUG: Diagnostic contains:
container.volatileInt = container.volatileInt + 1;
// BUG: Diagnostic contains:
container.volatileInt = 1 + container.volatileInt;
}
public void decrement() {
// BUG: Diagnostic contains:
myVolatileInt--;
// BUG: Diagnostic contains:
--myVolatileInt;
// BUG: Diagnostic contains:
myVolatileInt -= 1;
// BUG: Diagnostic contains:
myVolatileInt = myVolatileInt - 1;
// BUG: Diagnostic contains:
container.volatileInt--;
// BUG: Diagnostic contains:
--container.volatileInt;
// BUG: Diagnostic contains:
container.volatileInt -= 1;
// BUG: Diagnostic contains:
container.volatileInt = container.volatileInt - 1;
}
private volatile String myVolatileString = "";
public void stringUpdate() {
// BUG: Diagnostic contains:
myVolatileString += "update";
// BUG: Diagnostic contains:
myVolatileString = myVolatileString + "update";
}
}
| 2,585
| 28.724138
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MissingFailNegativeCases2.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/** Test cases for missing fail in a non-test class */
public class MissingFailNegativeCases2 {
public void expectedException_emptyCatch() {
try {
dummyMethod();
} catch (Exception expected) {
}
}
public void catchAssert() {
try {
dummyMethod();
} catch (Exception e) {
assertDummy();
}
}
private static void dummyMethod() {}
private static void assertDummy() {}
}
| 1,085
| 25.487805
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ByteBufferBackingArrayNegativeCases.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.errorprone.bugpatterns.ByteBufferBackingArrayTest;
import java.nio.ByteBuffer;
import java.util.function.Function;
/** Negative cases for {@link ByteBufferBackingArrayTest}. */
public class ByteBufferBackingArrayNegativeCases {
void noArrayCall_isNotFlagged() {
ByteBuffer buffer = null;
buffer.position();
}
void array_precededByArrayOffset_isNotFlagged() {
ByteBuffer buffer = null;
buffer.arrayOffset();
buffer.array();
}
void array_precededByArrayOffset_onOuterScope_isNotFlagged() {
ByteBuffer buffer = null;
buffer.arrayOffset();
if (true) {
while (true) {
buffer.array();
}
}
}
void array_precededByByteBufferWrap_isNotFlagged() {
ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1});
buffer.array();
}
void array_precededByByteBufferAllocate_isNotFlagged() {
ByteBuffer buffer = ByteBuffer.allocate(1);
buffer.array();
}
// Ideally, this case should be flagged though.
void array_followedByByteBufferArrayOffset_isNotFlagged() {
ByteBuffer buffer = null;
buffer.array();
buffer.arrayOffset();
}
// Ideally, this case should be flagged though.
void array_followedByArrayOffset_inExpression_isNotFlagged() {
ByteBuffer buffer = null;
byte[] outBytes;
int outOffset;
int outPos;
if (buffer.hasArray()) {
outBytes = buffer.array();
outPos = outOffset = buffer.arrayOffset() + buffer.position();
}
}
void array_precededByByteBufferAllocate_inSplitMethodChain_isNotFlagged() {
ByteBuffer buffer = ByteBuffer.allocate(1).put((byte) 'a');
buffer.array();
}
public void array_immediatelyPrecededByByteBufferAllocate_inContinuousMethodChain_isNotFlagged()
throws Exception {
ByteBuffer.allocate(0).array();
}
void array_precededByByteBufferAllocate_inContinuousMethodChain_isNotFlagged() {
ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(1L).array();
}
byte[] array_inMethodChain_precededByByteBufferAllocate_isNotFlagged() {
ByteBuffer buffer = ByteBuffer.allocate(1);
return buffer.put(new byte[] {1}).array();
}
class A {
// Ideally, this case should be flagged though.
void array_inMethodChain_whereByteBufferIsNotAtStartOfChain_isNotFlagged() {
A helper = new A();
helper.getBuffer().put((byte) 1).array();
}
ByteBuffer getBuffer() {
return null;
}
}
class B {
ByteBuffer buffer = ByteBuffer.allocate(1);
void array_precededByByteBufferAllocate_inField_isNotFlagged() {
buffer.array();
}
}
class C {
ByteBuffer buffer = ByteBuffer.allocate(1);
class A {
void array_precededByByteBufferAllocate_inFieldOfParentClass_isNotFlagged() {
buffer.array();
}
}
}
class ArrayInFieldPrecededByByteBufferAllocateInFieldIsNotFlagged {
ByteBuffer buffer = ByteBuffer.allocate(1);
byte[] array = buffer.array();
}
void array_inAnonymousClass_precededByByteBufferAllocate_isNotFlagged() {
final ByteBuffer buffer = ByteBuffer.allocate(0);
new Function<Object, Object>() {
@Override
public Object apply(Object o) {
buffer.array();
return null;
}
};
}
void array_inLambdaExpression_precededByByteBufferAllocate_isNotFlagged() {
final ByteBuffer buffer = ByteBuffer.allocate(0);
Function<Void, Void> f =
(Void unused) -> {
buffer.array();
return null;
};
}
}
| 4,156
| 26.348684
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit3TestNotRunNegativeCase5.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import org.junit.Test;
/**
* Class inherits RunWith from superclass, so should not emit errors.
*
* @author rburny@google.com (Radoslaw Burny)
*/
public class JUnit3TestNotRunNegativeCase5 extends JUnit3TestNotRunNegativeCase3 {
public void testEasyCase() {}
@Test
public void name() {}
public void tesMisspelled() {}
@Test
public void tesBothIssuesAtOnce() {}
}
| 1,046
| 26.552632
| 82
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ComparableAndComparatorNegativeCases.java
|
/* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.Comparator;
/** Created by mariasam on 6/5/17. */
public class ComparableAndComparatorNegativeCases {
/** Class that implements comparable, but also defines a comparator */
public static class ComparableAndComparatorNested
implements Comparable<ComparableAndComparatorNested> {
/** Comparator */
private static final Comparator<ComparableAndComparatorNested> myComparator =
new Comparator<ComparableAndComparatorNested>() {
@Override
public int compare(ComparableAndComparatorNested o1, ComparableAndComparatorNested o2) {
return 0;
}
};
@Override
public int compareTo(ComparableAndComparatorNested o) {
return 0;
}
}
/** class that only implements comparable */
public static class OnlyComparable implements Comparable<OnlyComparable> {
@Override
public int compareTo(OnlyComparable o) {
return 0;
}
}
/** class that only implements comparator */
public static class OnlyComparator implements Comparator<OnlyComparator> {
@Override
public int compare(OnlyComparator o1, OnlyComparator o2) {
return 0;
}
}
/** This test case is here to increase readability */
// BUG: Diagnostic contains: Class should not implement both
public static class BadClass implements Comparable<BadClass>, Comparator<BadClass> {
@Override
public int compareTo(BadClass comparableNode) {
return 0;
}
@Override
public int compare(BadClass a, BadClass b) {
return 0;
}
}
/** Subclass should not cause error */
public static class BadClassSubclass extends BadClass {
public int sampleMethod() {
return 0;
}
}
/** Enums implementing comparator are ok */
enum TestEnum implements Comparator<Integer> {
MONDAY,
TUESDAY,
WEDNESDAY;
@Override
public int compare(Integer one, Integer two) {
return 0;
}
}
}
| 2,607
| 27.043011
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnitParameterMethodNotFoundNegativeCaseNonJUnitParamsRunner.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class JUnitParameterMethodNotFoundNegativeCaseNonJUnitParamsRunner {
@Test
@Parameters(method = "named1")
public void paramStaticProvider() {}
}
| 964
| 31.166667
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ReturnValueIgnoredNegativeCases.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* @author alexeagle@google.com (Alex Eagle)
*/
public class ReturnValueIgnoredNegativeCases {
private String a = "thing";
{
String b = a.trim();
System.out.println(a.trim());
new String(new BigInteger(new byte[] {0x01}).add(BigInteger.ONE).toString());
}
String run() {
return a.trim();
}
public void methodDoesntMatch() {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("test", 1);
}
public void methodDoesntMatch2() {
final String b = a.toString().trim();
}
public void acceptFunctionOfVoid(Function<Integer, Void> arg) {
arg.apply(5);
}
public void passReturnValueCheckedMethodReferenceToFunctionVoid() {
Function<Integer, Void> fn = (i -> null);
acceptFunctionOfVoid(fn::apply);
}
public void arraysReturnValues() {
int[] numbers = {5, 4, 3, 2, 1};
int result = Arrays.binarySearch(numbers, 3);
int hashCode = Arrays.hashCode(numbers);
}
public void arraysNoReturnValues() {
int[] numbers = {5, 4, 3, 2, 1};
Arrays.fill(numbers, 0);
Arrays.sort(numbers);
}
}
| 1,896
| 25.347222
| 81
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ChainingConstructorIgnoresParameterNegativeCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.io.File;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
public class ChainingConstructorIgnoresParameterNegativeCases {
static class ImplicitThisCall {
ImplicitThisCall() {}
ImplicitThisCall(String foo) {}
}
static class ExplicitNoArgThisCall {
ExplicitNoArgThisCall() {}
ExplicitNoArgThisCall(String foo) {
this();
}
}
static class ParameterNotAvailable {
ParameterNotAvailable(String foo, boolean bar) {}
ParameterNotAvailable(String foo) {
this(foo, false);
}
}
static class ParameterDifferentType {
ParameterDifferentType(File foo) {}
ParameterDifferentType(String foo) {
this(new File("/tmp"));
}
}
static class ParameterUsedInExpression {
ParameterUsedInExpression(String foo, boolean bar) {}
ParameterUsedInExpression(String foo) {
this(foo.substring(0), false);
}
}
/** Make sure that we don't confuse a nested class's constructor with the containing class's. */
static class HasNestedClass {
HasNestedClass(String foo) {
this("somethingElse", false);
}
static class NestedClass {
NestedClass(String foo, boolean bar) {}
}
HasNestedClass(String notFoo, boolean bar) {}
}
static class HasNestedClassesWithSameName {
static class Outer1 {
static class Inner {
Inner(String foo, boolean bar) {}
}
}
static class Outer2 {
static class Inner {
Inner(String foo) {
this("somethingElse", false);
}
Inner(String notFoo, boolean bar) {}
}
}
}
class NonStaticClass {
NonStaticClass(String foo, boolean bar) {}
NonStaticClass(String foo) {
this(foo, false);
}
}
static class Varargs1 {
Varargs1(String foo, boolean... bar) {}
Varargs1() {
this("something", false, false);
}
}
static class Varargs2 {
Varargs2(String foo, boolean... bar) {}
Varargs2() {
this("something");
}
}
}
| 2,667
| 21.610169
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/IncrementInForLoopAndHeaderPositiveCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* @author mariasam@google.com (Maria Sam)
*/
public class IncrementInForLoopAndHeaderPositiveCases {
public void basicTest() {
// BUG: Diagnostic contains: increment
for (int i = 0; i < 10; i++) {
i++;
}
}
public void decrement() {
// BUG: Diagnostic contains: increment
for (int i = 0; i < 10; i++) {
i--;
}
}
public void preInc() {
// BUG: Diagnostic contains: increment
for (int i = 0; i < 10; i++) {
--i;
}
}
public void multipleStatements() {
// BUG: Diagnostic contains: increment
for (int i = 0; i < 10; i++) {
--i;
int a = 0;
}
}
public void multipleUpdates() {
// BUG: Diagnostic contains: increment
for (int i = 0, a = 1; i < 10; i++, a++) {
a++;
}
}
public void multipleUpdatesOtherVar() {
// BUG: Diagnostic contains: increment
for (int i = 0, a = 1; i < 10; i++, a++) {
i++;
}
}
public void multipleUpdatesBothVars() {
// BUG: Diagnostic contains: increment
for (int i = 0, a = 1; i < 10; i++, a++) {
a++;
i++;
}
}
public void nestedFor() {
for (int i = 0; i < 10; i++) {
// BUG: Diagnostic contains: increment
for (int a = 0; a < 10; a++) {
a--;
}
}
}
public void nestedForBoth() {
// BUG: Diagnostic contains: increment
for (int i = 0; i < 10; i++) {
i++;
// BUG: Diagnostic contains: increment
for (int a = 0; a < 10; a++) {
a--;
}
}
}
public void expressionStatement() {
// BUG: Diagnostic contains: increment
for (int i = 0; i < 10; i++) i++;
}
}
| 2,306
| 22.30303
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfAssignmentPositiveCases1.java
|
/*
* Copyright 2011 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* Tests for self assignment
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
public class SelfAssignmentPositiveCases1 {
private int a;
public void test1(int b) {
// BUG: Diagnostic contains: this.a = b
this.a = a;
}
public void test2(int b) {
// BUG: Diagnostic contains: remove this line
a = this.a;
}
public void test3() {
int a = 0;
// BUG: Diagnostic contains: this.a = a
a = a;
}
public void test4() {
// BUG: Diagnostic contains: remove this line
this.a = this.a;
}
public void test5() {
// BUG: Diagnostic contains: this.a = a
if ((a = a) != 10) {
System.out.println("foo");
}
}
// Check that WrappedTreeMap handles folded strings; tested by EndPosTest.
// See https://code.google.com/p/error-prone/issues/detail?id=209
public String foldableString() {
return "foo" + "bar";
}
public void testCast() {
int a = 0;
// BUG: Diagnostic contains: this.a = (int) a
a = (int) a;
// BUG: Diagnostic contains: this.a = (short) a
a = (short) a;
}
public void testCast(int x) {
// BUG: Diagnostic contains: this.a = (int) x;
this.a = (int) a;
}
}
| 1,850
| 24.013514
| 76
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TearDownNotRunPositiveCases.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author glorioso@google.com
*/
@RunWith(JUnit4.class)
public class JUnit4TearDownNotRunPositiveCases {
// BUG: Diagnostic contains: @After
public void tearDown() {}
}
@RunWith(JUnit4.class)
class JUnit4TearDownNotRunPositiveCase2 {
// BUG: Diagnostic contains: @After
protected void tearDown() {}
}
@RunWith(JUnit4.class)
class J4BeforeToAfter {
// BUG: Diagnostic contains: @After
@Before protected void tearDown() {}
}
@RunWith(JUnit4.class)
class J4BeforeClassToAfterClass {
// BUG: Diagnostic contains: @AfterClass
@BeforeClass protected void tearDown() {}
}
class TearDownUnannotatedBaseClass {
void tearDown() {}
}
@RunWith(JUnit4.class)
class JUnit4TearDownNotRunPositiveCase3 extends TearDownUnannotatedBaseClass {
// BUG: Diagnostic contains: @After
protected void tearDown() {}
}
@RunWith(JUnit4.class)
class J4TearDownHasOverride extends TearDownUnannotatedBaseClass {
// BUG: Diagnostic contains: @After
@Override protected void tearDown() {}
}
@RunWith(JUnit4.class)
class J4TearDownHasPublicOverride extends TearDownUnannotatedBaseClass {
// BUG: Diagnostic contains: @After
@Override public void tearDown() {}
}
| 1,958
| 25.472973
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfComparisonNegativeCases.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
/**
* Negative test cases for {@link SelfComparison} check.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
public class SelfComparisonNegativeCases implements Comparable<Object> {
private String field;
@Override
public int hashCode() {
return field != null ? field.hashCode() : 0;
}
@Override
public int compareTo(Object o) {
if (!(o instanceof SelfComparisonNegativeCases)) {
return -1;
}
SelfComparisonNegativeCases other = (SelfComparisonNegativeCases) o;
return field.compareTo(other.field);
}
public int test() {
return Boolean.TRUE.toString().compareTo(Boolean.FALSE.toString());
}
public static class CopmarisonTest implements Comparable<CopmarisonTest> {
private String testField;
@Override
public int compareTo(CopmarisonTest obj) {
return testField.compareTo(obj.testField);
}
}
}
| 1,542
| 27.054545
| 76
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TearDownNotRunPositiveCaseCustomAfter2.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test case with a custom After annotation. */
@RunWith(JUnit4.class)
public class JUnit4TearDownNotRunPositiveCaseCustomAfter2 {
// This will compile-fail and suggest the import of org.junit.After
// BUG: Diagnostic contains: @After
@After
public void tidyUp() {}
}
@interface After {}
| 1,027
| 31.125
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ProtocolBufferOrdinalNegativeCases.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.errorprone.bugpatterns.proto.ProtoTest.TestEnum;
/** Negative test cases for {@link ProtocolBufferOrdinal} check. */
public class ProtocolBufferOrdinalNegativeCases {
public static void checkProtoEnum() {
TestEnum.TEST_ENUM_VAL.getNumber();
}
}
| 935
| 32.428571
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/IterableAndIteratorPositiveCases.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.Iterator;
/**
* @author jsjeon@google.com (Jinseong Jeon)
*/
public class IterableAndIteratorPositiveCases {
/** Test Node */
public static class MyNode {
String tag;
MyNode next;
}
/** Test List that implements both Iterator and Iterable */
// BUG: Diagnostic contains: both
public static class MyBadList implements Iterator<MyNode>, Iterable<MyNode> {
private MyNode head;
public MyBadList() {
head = null;
}
@Override
public boolean hasNext() {
return head != null;
}
@Override
public MyNode next() {
if (hasNext()) {
MyNode ret = head;
head = head.next;
return ret;
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove is not supported");
}
public void add(MyNode node) {
if (!hasNext()) {
head.next = node;
}
head = node;
}
@Override
public Iterator<MyNode> iterator() {
return this;
}
}
/** Test List that extends the above bad implementation Diagnostic should bypass this */
public static class MyBadListInherited extends MyBadList {
public MyBadListInherited() {}
}
/** Test List that implements only Iterator */
public static class MyGoodList implements Iterator<MyNode> {
private MyNode head;
public MyGoodList() {
head = null;
}
@Override
public boolean hasNext() {
return head != null;
}
@Override
public MyNode next() {
if (hasNext()) {
MyNode ret = head;
head = head.next;
return ret;
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove is not supported");
}
public void add(MyNode node) {
if (!hasNext()) {
head.next = node;
}
head = node;
}
}
/** Test List that implicitly implements both interfaces */
// BUG: Diagnostic contains: both
public static class MyImplicitlyBadList extends MyGoodList implements Iterable<MyNode> {
public MyImplicitlyBadList() {}
@Override
public Iterator<MyNode> iterator() {
return this;
}
}
}
| 2,901
| 21.850394
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnitParameterMethodNotFoundPositiveCase.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(JUnitParamsRunner.class)
public class JUnitParameterMethodNotFoundPositiveCase {
@Test
@Parameters
// BUG: Diagnostic contains: [JUnitParameterMethodNotFound]
public void paramsInDefaultMethod(String p1, Integer p2) {}
@Test
@Parameters(method = "named2,named3")
// BUG: Diagnostic contains: [JUnitParameterMethodNotFound]
public void paramsInMultipleMethods(String p1, Integer p2) {}
@Test
@Parameters(source = JUnitParameterMethodNotFoundPositiveCase.class, method = "dataProvider")
// BUG: Diagnostic contains: [JUnitParameterMethodNotFound]
public void testSource(int a) {}
static class Inner {
public Object dataProvider() {
return new Object[] {1};
}
}
}
| 1,504
| 30.354167
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TruthAssertExpectedNegativeCases.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
/**
* Negative test cases for TruthAssertExpected check.
*
* @author ghm@google.com (Graeme Morgan)
*/
final class TruthAssertExpectedNegativeCases {
private static final Object expected = new Object();
private static final Object actual = new Object();
private static final Object foo = new Object();
private static final long CONSTANT = 1L;
private enum Enum {
A,
B;
}
private void simple() {
assertThat(foo).isEqualTo(expected);
assertThat(expected.hashCode()).isEqualTo(expected.hashCode());
assertThat(hashCode()).isEqualTo(foo);
}
private void actualAndExpectedTogether(int delay) {
int actualDelayInExpectedUnits = 1;
assertThat(actualDelayInExpectedUnits).isEqualTo(delay);
}
private void expectedExceptions() {
Exception expectedException = new Exception("Oh no.");
assertThat(expectedException).hasMessageThat().isEqualTo("Oh no.");
assertThat(expectedException.getClass()).isEqualTo(hashCode());
}
private void staticFactoryMethod() {
assertThat(expected).isEqualTo(Long.valueOf(10L));
assertThat(expected).isEqualTo(ImmutableList.of(1));
}
private void constantValues() {
assertThat(expected).isEqualTo(Enum.A);
assertThat(expected).isEqualTo(10L);
assertThat(expected).isEqualTo(CONSTANT);
}
}
| 2,078
| 29.573529
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/InvalidPatternSyntaxNegativeCases.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import java.util.regex.Pattern;
/**
* @author mdempsky@google.com (Matthew Dempsky)
*/
public class InvalidPatternSyntaxNegativeCases {
public void foo(String x) {
Pattern.compile("t");
Pattern.compile("t", 0);
Pattern.matches("t", "");
"".matches("t");
"".replaceAll("t", "");
"".replaceFirst("t", "");
"".split("t");
"".split("t", 0);
Pattern.compile(x);
Pattern.compile(x, 0);
Pattern.matches(x, "");
"".matches(x);
"".replaceAll(x, "");
"".replaceFirst(x, "");
"".split(x);
"".split(x, 0);
}
}
| 1,232
| 26.4
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NullablePrimitivePositiveCases.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import javax.annotation.Nullable;
/**
* @author sebastian.h.monte@gmail.com (Sebastian Monte)
*/
public class NullablePrimitivePositiveCases {
// BUG: Diagnostic contains: remove
@Nullable
int a;
public void method(
// BUG: Diagnostic contains: remove
@Nullable
int a) {
}
// BUG: Diagnostic contains: remove
@Nullable
public int method() {
return 0;
}
}
| 1,063
| 24.333333
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EqualsIncompatibleTypePositiveCases.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author avenet@google.com (Arnaud J. Venet)
*/
public class EqualsIncompatibleTypePositiveCases {
class A {}
class B {}
void checkEqualsAB(A a, B b) {
// BUG: Diagnostic contains: incompatible types
a.equals(b);
// BUG: Diagnostic contains: incompatible types
b.equals(a);
}
class C {}
abstract class C1 extends C {
public abstract boolean equals(Object o);
}
abstract class C2 extends C1 {}
abstract class C3 extends C {}
void checkEqualsCC1C2C3(C c, C1 c1, C2 c2, C3 c3) {
// BUG: Diagnostic contains: incompatible types
c3.equals(c1);
// BUG: Diagnostic contains: incompatible types
c3.equals(c2);
// BUG: Diagnostic contains: incompatible types
c1.equals(c3);
// BUG: Diagnostic contains: incompatible types
c2.equals(c3);
}
void checkStaticEqualsCC1C2C3(C c, C1 c1, C2 c2, C3 c3) {
// BUG: Diagnostic contains: incompatible types
java.util.Objects.equals(c3, c1);
// BUG: Diagnostic contains: incompatible types
java.util.Objects.equals(c3, c2);
// BUG: Diagnostic contains: incompatible types
java.util.Objects.equals(c1, c3);
// BUG: Diagnostic contains: incompatible types
java.util.Objects.equals(c2, c3);
}
void checkGuavaStaticEqualsCC1C2C3(C c, C1 c1, C2 c2, C3 c3) {
// BUG: Diagnostic contains: incompatible types
com.google.common.base.Objects.equal(c3, c1);
// BUG: Diagnostic contains: incompatible types
com.google.common.base.Objects.equal(c3, c2);
// BUG: Diagnostic contains: incompatible types
com.google.common.base.Objects.equal(c1, c3);
// BUG: Diagnostic contains: incompatible types
com.google.common.base.Objects.equal(c2, c3);
}
void checkPrimitiveEquals(int a, long b) {
// BUG: Diagnostic contains: incompatible types
java.util.Objects.equals(a, b);
// BUG: Diagnostic contains: incompatible types
java.util.Objects.equals(b, a);
// BUG: Diagnostic contains: incompatible types
com.google.common.base.Objects.equal(a, b);
// BUG: Diagnostic contains: incompatible types
com.google.common.base.Objects.equal(b, a);
}
interface I {
boolean equals(Object o);
}
class D {}
class D1 extends D {}
class D2 extends D implements I {}
void checkEqualsDD1D2(D d, D1 d1, D2 d2) {
// BUG: Diagnostic contains: incompatible types
d1.equals(d2);
// BUG: Diagnostic contains: incompatible types
d2.equals(d1);
}
enum MyEnum {}
enum MyOtherEnum {}
void enumEquals(MyEnum m, MyOtherEnum mm) {
// BUG: Diagnostic contains: incompatible types
m.equals(mm);
// BUG: Diagnostic contains: incompatible types
mm.equals(m);
// BUG: Diagnostic contains: incompatible types
com.google.common.base.Objects.equal(m, mm);
// BUG: Diagnostic contains: incompatible types
com.google.common.base.Objects.equal(mm, m);
}
void collectionsWithGenericMismatches(
List<String> stringList,
List<Integer> intList,
Set<String> stringSet,
Set<Integer> intSet,
ImmutableList<String> stringImmutableList) {
// BUG: Diagnostic contains: incompatible types
stringList.equals(intList);
// BUG: Diagnostic contains: incompatible types
stringSet.equals(intSet);
// BUG: Diagnostic contains: incompatible types
stringList.equals(stringSet);
// BUG: Diagnostic contains: incompatible types
intList.equals(stringImmutableList);
}
void mapKeyChecking(
Map<String, Integer> stringIntegerMap,
Map<Integer, String> integerStringMap,
Map<List<String>, Set<String>> stringListSetMap,
Map<List<String>, Set<Integer>> intListSetMap) {
// BUG: Diagnostic contains: incompatible types
stringIntegerMap.equals(integerStringMap);
// BUG: Diagnostic contains: incompatible types
stringListSetMap.equals(intListSetMap);
}
void nestedColls(Set<List<String>> setListString, Set<List<Integer>> setListInteger) {
// BUG: Diagnostic contains: String and Integer are incompatible
boolean equals = setListString.equals(setListInteger);
}
class MyGenericClazz<T> {}
<T extends I> void testSomeGenerics(
MyGenericClazz<String> strClazz, MyGenericClazz<Integer> intClazz, MyGenericClazz<T> iClazz) {
// BUG: Diagnostic contains: String and Integer are incompatible
strClazz.equals(intClazz);
// BUG: Diagnostic contains: T and String are incompatible
iClazz.equals(strClazz);
}
}
| 5,258
| 29.224138
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ModifySourceCollectionInStreamPositiveCases.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Test cases for {@link com.google.errorprone.bugpatterns.ModifySourceCollectionInStream}.
*
* @author deltazulu@google.com (Donald Duo Zhao)
*/
public class ModifySourceCollectionInStreamPositiveCases {
private final List<Integer> mutableValues = Arrays.asList(1, 2, 3);
private void mutateStreamSourceMethodReference() {
mutableValues.stream()
.map(x -> x + 1)
.filter(x -> x < 5)
// BUG: Diagnostic contains:
.forEach(mutableValues::remove);
this.mutableValues.stream()
.map(x -> x + 1)
.filter(x -> x < 5)
// BUG: Diagnostic contains:
.forEach(mutableValues::remove);
getMutableValues().parallelStream()
.map(x -> x + 1)
.filter(x -> x < 5)
// BUG: Diagnostic contains:
.forEach(getMutableValues()::add);
getMutableValues().stream()
.map(x -> x + 1)
.filter(x -> x < 5)
// BUG: Diagnostic contains:
.forEach(this.getMutableValues()::remove);
ModifySourceCollectionInStreamPositiveCases[] cases = {
new ModifySourceCollectionInStreamPositiveCases(),
new ModifySourceCollectionInStreamPositiveCases()
};
cases[0].mutableValues.stream()
.map(x -> x + 1)
.filter(x -> x < 5)
// BUG: Diagnostic contains:
.forEach(cases[0].mutableValues::add);
}
private List<Integer> mutateStreamSourceLambdaExpression(
ImmutableList<Integer> mutableParamList) {
Stream<Integer> values1 =
mutableParamList.stream()
.map(
x -> {
// BUG: Diagnostic contains:
mutableParamList.add(x);
return x + 1;
});
Stream<Integer> values2 =
mutableParamList.stream()
.filter(
x -> {
// BUG: Diagnostic contains:
mutableParamList.remove(x);
return mutableParamList.size() > 5;
});
return Stream.concat(values1, values2).collect(Collectors.toList());
}
private List<Integer> getMutableValues() {
return mutableValues;
}
}
| 2,972
| 29.96875
| 100
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.