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/PrivateSecurityContractProtoAccessTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class PrivateSecurityContractProtoAccessTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(PrivateSecurityContractProtoAccess.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceFile("PrivateSecurityContractProtoAccessPositiveCases.java")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceFile("PrivateSecurityContractProtoAccessNegativeCases.java")
.doTest();
}
@Test
public void safeHtmlAccessWithinPackage() {
compilationHelper
.addSourceLines(
"Test.java",
"package com.google.common.html.types;",
"import com.google.common.html.types.SafeHtmlProto;",
"class Test {",
" SafeHtmlProto buildProto() {",
" return SafeHtmlProto.newBuilder()",
" .setPrivateDoNotAccessOrElseSafeHtmlWrappedValue(\"foo\")",
" .build();",
" }",
"}")
.doTest();
}
}
| 1,901
| 30.7
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MathAbsoluteNegativeTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author kayco@google.com (Kayla Walker)
*/
@RunWith(JUnit4.class)
public class MathAbsoluteNegativeTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(MathAbsoluteNegative.class, getClass());
@Test
public void random() {
helper
.addSourceLines(
"Test.java",
"import java.util.Random;",
"class Test {",
" private static final Random random = new Random();",
" void f() {",
" // BUG: Diagnostic contains: MathAbsoluteNegative",
" Math.abs(random.nextInt());",
" }",
"}")
.doTest();
}
@Test
public void randomWithBounds() {
helper
.addSourceLines(
"Test.java",
"import java.util.Random;",
"class Test {",
" private static final Random random = new Random();",
" void f() {",
" Math.abs(random.nextInt(10));",
" }",
"}")
.doTest();
}
@Test
public void negativeNumber() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" void f() {",
" Math.abs(-9549451);",
" }",
"}")
.doTest();
}
@Test
public void negativeMethod() {
helper
.addSourceLines(
"Test.java", //
"class Test {",
" void f() {",
" Math.abs(Math.sin(0) * 10.0);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" long random = Math.round(Math.random() * 10000);",
" }",
"}")
.doTest();
}
@Test
public void negativeDouble() {
helper
.addSourceLines(
"Test.java",
"import java.util.Random;",
"class Test {",
" void f() {",
" double random = Math.abs(new Random().nextDouble());",
" }",
"}")
.doTest();
}
@Test
public void hashAsInt() {
helper
.addSourceLines(
"Test.java",
"import static com.google.common.hash.Hashing.goodFastHash;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: MathAbsoluteNegative",
" int foo = Math.abs(goodFastHash(64).hashUnencodedChars(\"\").asInt());",
" }",
"}")
.doTest();
}
@Test
public void hashAsLong() {
helper
.addSourceLines(
"Test.java",
"import static com.google.common.hash.Hashing.goodFastHash;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: MathAbsoluteNegative",
" long foo = Math.abs(goodFastHash(64).hashUnencodedChars(\"\").asLong());",
" }",
"}")
.doTest();
}
@Test
public void hashPadToLong() {
helper
.addSourceLines(
"Test.java",
"import static com.google.common.hash.Hashing.goodFastHash;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: MathAbsoluteNegative",
" long foo = Math.abs(goodFastHash(64).hashUnencodedChars(\"\").padToLong());",
" }",
"}")
.doTest();
}
@Test
public void objectHashCode() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f(String s) {",
" // BUG: Diagnostic contains: MathAbsoluteNegative",
" long foo = Math.abs(s.hashCode());",
" }",
"}")
.doTest();
}
@Test
public void identityHashCode() {
helper
.addSourceLines(
"Test.java",
"class Test {",
" void f(Object o) {",
" // BUG: Diagnostic contains: MathAbsoluteNegative",
" long foo = Math.abs(System.identityHashCode(o));",
" }",
"}")
.doTest();
}
@Test
public void uuid() {
helper
.addSourceLines(
"Test.java",
"import java.util.UUID;",
"class Test {",
" void f(UUID uuid) {",
" // BUG: Diagnostic contains: MathAbsoluteNegative",
" long foo = Math.abs(uuid.getLeastSignificantBits());",
" // BUG: Diagnostic contains: MathAbsoluteNegative",
" long bar = Math.abs(uuid.getMostSignificantBits());",
" }",
"}")
.doTest();
}
}
| 5,591
| 26.014493
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryOptionalGetTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link UnnecessaryOptionalGet}. */
@RunWith(JUnit4.class)
public final class UnnecessaryOptionalGetTest {
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryOptionalGet.class, getClass());
@Test
public void genericOptionalVars_sameVarGet_replacesWithLambdaArg() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.ifPresent(x -> System.out.println(op.get()));",
" op.map(x -> Long.parseLong(op.get()));",
" op.filter(x -> op.get().isEmpty());",
" op.flatMap(x -> Optional.of(op.get()));",
" op.flatMap(x -> Optional.of(op.orElseThrow()));",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.ifPresent(x -> System.out.println(x));",
" op.map(x -> Long.parseLong(x));",
" op.filter(x -> x.isEmpty());",
" op.flatMap(x -> Optional.of(x));",
" op.flatMap(x -> Optional.of(x));",
" }",
"}")
.doTest();
}
@Test
public void guava_sameVarGet_replacesWithLambdaArg() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.common.base.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.transform(x -> Long.parseLong(op.get()));",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.transform(x -> Long.parseLong(x));",
" }",
"}")
.doTest();
}
@Test
public void genericOptionalVars_orElseVariations_replacesWithLambdaArg() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.ifPresent(x -> System.out.println(op.orElse(\"other\")));",
" op.ifPresent(x -> System.out.println(op.orElseGet(() -> \"other\")));",
" op.ifPresent(x -> System.out.println(op.orElseThrow(RuntimeException::new)));",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.ifPresent(x -> System.out.println(x));",
" op.ifPresent(x -> System.out.println(x));",
" op.ifPresent(x -> System.out.println(x));",
" }",
"}")
.doTest();
}
@Test
public void guava_orVariations_replacesWithLambdaArg() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import com.google.common.base.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.transform(x -> Long.parseLong(op.or(\"other\")));",
" op.transform(x -> Long.parseLong(op.or(() -> \"other\")));",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.base.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.transform(x -> Long.parseLong(x));",
" op.transform(x -> Long.parseLong(x));",
" }",
"}")
.doTest();
}
@Test
public void genericOptionalVars_sameVarGet_lamdaBlocks_replacesWithLamdaArg() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.ifPresent(x -> { System.out.println(op.get()); });",
" op.map(x -> { return Long.parseLong(op.get()); });",
" op.filter(x -> { return op.get().isEmpty(); });",
" op.flatMap(x -> { return Optional.of(op.get()); });",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.ifPresent(x -> { System.out.println(x); });",
" op.map(x -> { return Long.parseLong(x); });",
" op.filter(x -> { return x.isEmpty(); });",
" op.flatMap(x -> { return Optional.of(x); });",
" }",
"}")
.doTest();
}
@Test
public void genericOptionalVars_differentOptionalVarGet_doesNothing() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op1 = Optional.of(\"hello\");",
" Optional<String> op2 = Optional.of(\"hello\");",
" op1.ifPresent(x -> System.out.println(op2.get()));",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void genericOptionalVars_differentMethodGet_doesNothing() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" myOpFunc1().ifPresent(x -> System.out.println(myOpFunc2().get()));",
" }",
" private Optional<String> myOpFunc1() {",
" return Optional.of(\"hello\");",
" }",
" private Optional<String> myOpFunc2() {",
" return Optional.of(\"hello\");",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void genericOptionalMethods_sameMethodInvocation_replacesWithLamdaArg() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" myOpFunc().ifPresent(x -> System.out.println(myOpFunc().get()));",
" }",
" private Optional<String> myOpFunc() {",
" return Optional.of(\"hello\");",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void primitiveOptionals() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.OptionalDouble;",
"import java.util.OptionalInt;",
"import java.util.OptionalLong;",
"public class Test {",
" private void home() {",
" OptionalDouble opDouble = OptionalDouble.of(1.0);",
" OptionalInt opInt = OptionalInt.of(1);",
" OptionalLong opLong = OptionalLong.of(1L);",
" opDouble.ifPresent(x -> System.out.println(opDouble.getAsDouble()));",
" opInt.ifPresent(x -> System.out.println(opInt.getAsInt()));",
" opLong.ifPresent(x -> System.out.println(opLong.getAsLong()));",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.OptionalDouble;",
"import java.util.OptionalInt;",
"import java.util.OptionalLong;",
"public class Test {",
" private void home() {",
" OptionalDouble opDouble = OptionalDouble.of(1.0);",
" OptionalInt opInt = OptionalInt.of(1);",
" OptionalLong opLong = OptionalLong.of(1L);",
" opDouble.ifPresent(x -> System.out.println(x));",
" opInt.ifPresent(x -> System.out.println(x));",
" opLong.ifPresent(x -> System.out.println(x));",
" }",
"}")
.doTest();
}
@Test
public void differentReceivers() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" abstract static class T {",
" abstract Optional<String> getValue();",
" }",
" static void test(T actual, T expected) {",
" actual",
" .getValue()",
" .ifPresent(",
" actualValue -> {",
" String expectedValue = expected.getValue().get();",
" actualValue.equals(expectedValue);",
" });",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void orElseThrow() {
refactoringTestHelper
.addInputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.flatMap(x -> Optional.of(op.orElseThrow()));",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Optional;",
"public class Test {",
" private void home() {",
" Optional<String> op = Optional.of(\"hello\");",
" op.flatMap(x -> Optional.of(x));",
" }",
"}")
.doTest();
}
}
| 11,249
| 35.290323
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BadComparableTest.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author irogers@google.com (Ian Rogers)
*/
@RunWith(JUnit4.class)
public class BadComparableTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(BadComparable.class, getClass());
@Test
public void positiveCase() {
compilationHelper.addSourceFile("BadComparablePositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("BadComparableNegativeCases.java").doTest();
}
}
| 1,286
| 29.642857
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerArgumentToStringTest.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.flogger;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link FloggerArgumentToString}Test */
@RunWith(JUnit4.class)
public class FloggerArgumentToStringTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(FloggerArgumentToString.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(FloggerArgumentToString.class, getClass());
@Test
public void refactoring() {
refactoringHelper
.addInputLines(
"in/Test.java",
"import com.google.common.base.Ascii;",
"import com.google.common.flogger.FluentLogger;",
"import java.util.Arrays;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(String world, Object[] xs, long l) {",
" logger.atInfo().log(\"hello '%s'\", world.toString());",
" logger.atInfo().log(\"hello %s %d\", world.toString(), 2);",
" logger.atInfo().log(\"hello %s\", world.toUpperCase());",
" logger.atInfo().log(\"hello %s\", Ascii.toUpperCase(world));",
" logger.atInfo().log(\"hello %s\", Integer.toString(42));",
" logger.atInfo().log(\"hello %d\", Integer.valueOf(42));",
" logger.atInfo().log(\"hello %s\", Integer.toHexString(42));",
" logger.atInfo().log(\"hello %S\", Integer.toHexString(42));",
" logger.atInfo().log(\"hello %s\", Arrays.asList(1, 2));",
" logger.atInfo().log(\"hello %s\", Arrays.asList(xs));",
" logger.atInfo().log(\"hello %s\", Arrays.toString(xs));",
" logger.atInfo().log(\"hello %s\", Long.toHexString(l));",
" logger.atInfo().log(\"%%s\", Ascii.toUpperCase(world));",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.base.Ascii;",
"import com.google.common.flogger.FluentLogger;",
"import java.util.Arrays;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(String world, Object[] xs, long l) {",
" logger.atInfo().log(\"hello '%s'\", world);",
" logger.atInfo().log(\"hello %s %d\", world, 2);",
" logger.atInfo().log(\"hello %S\", world);",
" logger.atInfo().log(\"hello %S\", world);",
" logger.atInfo().log(\"hello %d\", 42);",
" logger.atInfo().log(\"hello %d\", 42);",
" logger.atInfo().log(\"hello %x\", 42);",
" logger.atInfo().log(\"hello %X\", 42);",
" logger.atInfo().log(\"hello %s\", Arrays.asList(1, 2));",
" logger.atInfo().log(\"hello %s\", xs);",
" logger.atInfo().log(\"hello %s\", xs);",
" logger.atInfo().log(\"hello %x\", l);",
" logger.atInfo().log(\"%%s\", Ascii.toUpperCase(world));",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(String world) {",
" logger.atInfo().log(\"hello '%s'\", world);",
" }",
"}")
.doTest();
}
@Test
public void selfToString() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f() {",
" logger.atInfo().log(\"hello '%s'\", toString());",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f() {",
" logger.atInfo().log(\"hello '%s'\", this);",
" }",
"}")
.doTest();
}
}
| 5,299
| 41.063492
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiersTest.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.flogger;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FloggerRequiredModifiers}. */
@RunWith(JUnit4.class)
public class FloggerRequiredModifiersTest {
private BugCheckerRefactoringTestHelper refactoringHelper() {
return BugCheckerRefactoringTestHelper.newInstance(FloggerRequiredModifiers.class, getClass());
}
@Test
public void negative() {
refactoringHelper()
.addInputLines(
"Holder.java",
"import com.google.common.flogger.FluentLogger;",
"class Holder {",
" public FluentLogger logger;",
" public FluentLogger get() {return logger;}",
"}")
.expectUnchanged()
.addInputLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void log(FluentLogger l) {l.atInfo().log(\"bland\");}",
" public void delegate(Holder h) {h.logger.atInfo().log(\"held\");}",
" public void read(Holder h) {h.get().atInfo().log(\"got\");}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void positive_addsStatic() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" final FluentLogger logger = FluentLogger.forEnclosingClass();",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
"}")
.doTest();
}
@Test
public void positive_extractsExpression() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" void doIt() {FluentLogger.forEnclosingClass().atInfo().log();}",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" void doIt() {logger.atInfo().log();}",
"}")
.doTest();
}
@Test
public void negative_doesntCreateSelfAssignment() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger;",
" static {",
" logger = register(FluentLogger.forEnclosingClass());",
" }",
" private static <T> T register(T t) {return t;}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void negative_doesntIndirectWrappers() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static FluentLogger logger = register(FluentLogger.forEnclosingClass());",
" private static <T> T register(T t) {return t;}",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger ="
+ " register(FluentLogger.forEnclosingClass());",
" private static <T> T register(T t) {return t;}",
"}")
.doTest();
}
// People who do this generally do it for good reason, and for interfaces it's required.
@Test
public void negative_allowsSiblingLoggerUse() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" static class A { public A() {B.logger.atInfo().log();}}",
" static class B {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void positive_hidesLoggersFromInterfaces() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"interface Test {",
" static FluentLogger logger = FluentLogger.forEnclosingClass();",
" default void foo() {logger.atInfo().log();}",
"}")
.addOutputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"interface Test {",
" default void foo() {",
" Private.logger.atInfo().log();",
" }",
" public static final class Private {",
" private Private() {}",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_extractsHiddenLoggersForInterfaces() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"interface Test {",
" default void foo() {FluentLogger.forEnclosingClass().atInfo().log();}",
"}")
.addOutputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"interface Test {",
" default void foo() {",
" Private.logger.atInfo().log();",
" }",
" public static final class Private {",
" private Private() {}",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" }",
"}")
.doTest();
}
@Test
public void positive_fixesVisibility() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" public static final FluentLogger logger = FluentLogger.forEnclosingClass();",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
"}")
.doTest();
}
@Test
public void positive_goalsDontConflict() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" public FluentLogger logger = FluentLogger.forEnclosingClass();",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private final FluentLogger logger = FluentLogger.forEnclosingClass();",
"}")
.doTest();
}
@Test
public void positive_replacesInheritedLogger() {
refactoringHelper()
.addInputLines(
"in/Parent.java",
"import com.google.common.flogger.FluentLogger;",
"@SuppressWarnings(\"FloggerRequiredModifiers\")",
"class Parent {",
" protected static final FluentLogger logger = FluentLogger.forEnclosingClass();",
"}")
.expectUnchanged()
.addInputLines(
"in/Child.java",
"class Child extends Parent {",
" Child() {logger.atInfo().log(\"child\");",
" super.logger.atInfo().log(\"super\");",
" Parent.logger.atInfo().log(\"parent\");}",
"}")
.addOutputLines(
"out/Child.java",
"import com.google.common.flogger.FluentLogger;",
"class Child extends Parent {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" Child() {logger.atInfo().log(\"child\");",
" logger.atInfo().log(\"super\");",
" logger.atInfo().log(\"parent\");}",
"}")
.doTest();
}
@Test
public void positive_doesntCreateSelfReference() {
refactoringHelper()
.addInputLines(
"in/Parent.java",
"import com.google.common.flogger.FluentLogger;",
"@SuppressWarnings(\"FloggerRequiredModifiers\")",
"class Parent {",
" protected static final FluentLogger logger = FluentLogger.forEnclosingClass();",
"}")
.expectUnchanged()
.addInputLines(
"in/Child.java",
"import com.google.common.flogger.FluentLogger;",
"class Child extends Parent {",
" private static final FluentLogger logger = Parent.logger;",
" Child() {logger.atInfo().log(\"child\");}",
"}")
.addOutputLines(
"out/Child.java",
"import com.google.common.flogger.FluentLogger;",
"class Child extends Parent {",
" private static final FluentLogger flogger = FluentLogger.forEnclosingClass();",
" private static final FluentLogger logger = flogger;",
" Child() {logger.atInfo().log(\"child\");}",
"}")
.doTest();
}
@Test
public void positive_handlesRewritesInMultipleFiles() {
refactoringHelper()
.addInputLines(
"in/Parent.java",
"import com.google.common.flogger.FluentLogger;",
"interface Parent {",
"}")
.expectUnchanged()
.addInputLines(
"in/Child.java",
"import com.google.common.flogger.FluentLogger;",
"interface Child extends Parent {",
" static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" default void go() {logger.atInfo().log();}",
"}")
.addOutputLines(
"out/Child.java",
"import com.google.common.flogger.FluentLogger;",
"interface Child extends Parent {",
" default void go() {Private.logger.atInfo().log();}",
" public static final class Private {",
" private Private() {}",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" }",
"}")
.addInputLines(
"in/Sibling.java",
"import com.google.common.flogger.FluentLogger;",
"interface Sibling extends Parent {",
" static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" default void go() {logger.atInfo().log();}",
"}")
.addOutputLines(
"out/Sibling.java",
"import com.google.common.flogger.FluentLogger;",
"interface Sibling extends Parent {",
" default void go() {Private.logger.atInfo().log();}",
" public static final class Private {",
" private Private() {}",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" }",
"}")
.doTest();
}
@Test
public void negative_allowsSiblingLoggers() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final class Inner {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" }",
" private void go() {Inner.logger.atInfo().log();}",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void negative_doesntNeedlesslyMoveLoggersToInterfaces() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"interface Test {",
" class Inner {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" private static final class MoreInner {",
" private void go() {logger.atInfo().log();}",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| 13,465
| 35.296496
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerLogWithCauseTest.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.flogger;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FloggerLogWithCause}. */
@RunWith(JUnit4.class)
public final class FloggerLogWithCauseTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FloggerLogWithCause.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void test() {",
" try {}",
" catch (Exception e) {",
" // BUG: Diagnostic contains: logger.atWarning().withCause(e).log",
" logger.atWarning().log(\"failed\");",
" }",
" }",
"}")
.doTest();
}
@Test
public void loggedAtInfo_noWarning() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void test() {",
" try {}",
" catch (Exception e) {",
" logger.atInfo().log(\"failed\");",
" }",
" }",
"}")
.doTest();
}
@Test
public void alreadyLoggedWithCause() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void test() {",
" try {}",
" catch (Exception e) {",
" logger.atWarning().withCause(e).log(\"failed\");",
" }",
" }",
"}")
.doTest();
}
@Test
public void variableUsedInOtherWay() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void test() {",
" try {}",
" catch (Exception e) {",
" logger.atWarning().log(e.getMessage());",
" }",
" }",
"}")
.doTest();
}
@Test
public void suppression() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void test() {",
" try {}",
" catch (@SuppressWarnings(\"FloggerLogWithCause\") Exception e) {",
" logger.atWarning().log(e.getMessage());",
" }",
" }",
"}")
.doTest();
}
}
| 3,920
| 31.139344
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerWithCauseTest.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.flogger;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FloggerWithCause} */
@RunWith(JUnit4.class)
public class FloggerWithCauseTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FloggerWithCause.class, getClass());
@Test
public void positiveCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"import java.io.IOException;",
"class Test {",
" abstract static class MyException extends IOException {",
" abstract public String foo();",
" }",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void method(Exception e, MyException e2) {",
" // BUG: Diagnostic contains:"
+ " logger.atSevere().withStackTrace(MEDIUM).log(\"msg\");",
" logger.atSevere().withCause(new Error()).log(\"msg\");",
" logger.atSevere().withCause(new Error(e2.foo())).log(\"msg\");",
" FluentLogger.Api severeLogger = logger.atSevere();",
" // BUG: Diagnostic contains:"
+ " severeLogger.withStackTrace(MEDIUM).log(\"message\");",
" severeLogger.withCause(new IllegalArgumentException()).log(\"message\");",
" // BUG: Diagnostic contains:",
" // logger.atSevere().withCause(e).log(\"message\");",
" // logger.atSevere().withStackTrace(MEDIUM).withCause(e).log(\"message\");",
" logger.atSevere().withCause(new Throwable(e)).log(\"message\");",
" // BUG: Diagnostic contains:",
" // logger.atSevere().withCause(e).log(\"message\");",
" // logger.atSevere().withStackTrace(MEDIUM).withCause(e).log(\"message\");",
" logger.atSevere().withCause(new SecurityException(e)).log(\"message\");",
" // BUG: Diagnostic contains:",
" // logger.atSevere().withCause(e).log(\"msg\");",
" // logger.atSevere().withStackTrace(MEDIUM).withCause(e).log(\"msg\");",
" logger.atSevere().withCause(new"
+ " NumberFormatException(e.getMessage())).log(\"msg\");",
" // BUG: Diagnostic contains:",
" // logger.atSevere().withCause(e).log(\"message\");",
" // logger.atSevere().withStackTrace(MEDIUM).withCause(e).log(\"message\");",
" logger.atSevere().withCause(new Exception(e.toString())).log(\"message\");",
" // BUG: Diagnostic contains:",
" // logger.atSevere().withCause(e.getCause()).log(\"message\");",
" //"
+ " logger.atSevere().withStackTrace(MEDIUM).withCause(e.getCause()).log(\"message\");",
" logger.atSevere().withCause(new RuntimeException(e.getCause())).log(\"message\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCases() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.flogger.StackSize.FULL;",
"import static com.google.common.flogger.StackSize.MEDIUM;",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void method(Exception e) {",
" logger.atSevere().log(null);",
" logger.atSevere().log(\"hello\");",
" logger.atSevere().log(\"hello %d\", 1);",
" logger.atSevere().withCause(e).log(\"some log message\");",
" logger.atSevere().withStackTrace(FULL).log(\"some log message\");",
" logger.atSevere().withStackTrace(MEDIUM).withCause(e).log(\"some log message\");",
" logger.atSevere().withCause(new NumberFormatException()).log(\"message\");",
" }",
"}")
.doTest();
}
// regression test for http://b/29131466
@Test
public void breakBeforeWithCause() {
BugCheckerRefactoringTestHelper.newInstance(FloggerWithCause.class, getClass())
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void method(Exception e) {",
" logger.atSevere()",
" .withCause(new IllegalArgumentException())",
" .log(\"message\");",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import static com.google.common.flogger.StackSize.MEDIUM;",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void method(Exception e) {",
" logger.atSevere().withStackTrace(MEDIUM).log(\"message\");",
" }",
"}")
.doTest();
}
}
| 6,079
| 45.412214
| 104
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerLogStringTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.flogger;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link FloggerLogString}Test */
@RunWith(JUnit4.class)
public class FloggerLogStringTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FloggerLogString.class, getClass());
private static final String ERROR_MESSAGE =
"Arguments to log(String) must be compile-time constants";
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(String s) {",
" // BUG: Diagnostic contains: " + ERROR_MESSAGE,
" logger.atInfo().log(s);",
" // BUG: Diagnostic contains: " + ERROR_MESSAGE,
" logger.atInfo().log(\"foo \" + s);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" private static final String CONSTANT = \"CONSTANT\";",
" public void f(@CompileTimeConstant String s) {",
" final String localFinal = \"localFinal\";",
" logger.atInfo().log(\"hello\");",
" logger.atInfo().log(s);",
" logger.atInfo().log(CONSTANT);",
" logger.atInfo().log(localFinal);",
" logger.atInfo().log(\"hello \" + s);",
" logger.atInfo().log(\"hello \" + CONSTANT);",
" logger.atInfo().log(\"hello \" + localFinal);",
" logger.atInfo().log(\"hello \"+ s + CONSTANT);",
" logger.atInfo().log(\"hello \"+ s + localFinal);",
" logger.atInfo().log(\"hello \" + localFinal + CONSTANT);",
" logger.atInfo().log(\"hello \"+ s + localFinal + CONSTANT);",
" logger.atInfo().log(s + localFinal);",
" logger.atInfo().log(s + CONSTANT);",
" logger.atInfo().log(CONSTANT + localFinal);",
" logger.atInfo().log(s + localFinal + CONSTANT);",
" logger.atInfo().log((String) null);",
" }",
"}")
.doTest();
}
}
| 3,356
| 38.494118
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerWithoutCauseTest.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.flogger;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link FloggerWithoutCause}Test */
@RunWith(JUnit4.class)
public class FloggerWithoutCauseTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FloggerWithoutCause.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(Exception e, Throwable t) {",
" // BUG: Diagnostic contains: logger.atInfo().withCause(e).log(\"hello %s\", e);",
" logger.atInfo().log(\"hello %s\", e);",
" // BUG: Diagnostic contains: .atInfo().withCause(t).log(\"hello %s\", e, t);",
" logger.atInfo().log(\"hello %s\", e, t);",
" }",
"}")
.doTest();
}
@Test
public void positiveSubtype() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(ReflectiveOperationException e) {",
" // BUG: Diagnostic contains: logger.atInfo().withCause(e).log(\"hello %s\", e);",
" logger.atInfo().log(\"hello %s\", e);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(Exception e, Throwable t) {",
" logger.atInfo().log(null);",
" logger.atInfo().log(\"hello\");",
" logger.atInfo().log(\"hello %s\", 1);",
" logger.atInfo().withCause(e).log(\"hello %s\", e);",
" logger.atInfo().withCause(e).log(\"hello %s\", e, t);",
" }",
"}")
.doTest();
}
}
| 3,053
| 35.357143
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerFormatStringTest.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.flogger;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link FloggerFormatString}Test */
@RunWith(JUnit4.class)
public class FloggerFormatStringTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FloggerFormatString.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(Exception e, Throwable t) {",
" // BUG: Diagnostic contains: 'java.lang.String' cannot be formatted using '%d'",
" logger.atInfo().log(\"hello %d\", \"world\");",
" }",
"}")
.doTest();
}
@Test
public void positiveWithCause() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(Exception e, Throwable t) {",
" // BUG: Diagnostic contains: logger.atInfo().withCause(e).log(\"hello\");",
" logger.atInfo().log(\"hello\", e);",
" // BUG: Diagnostic contains: logger.atInfo().withCause(t).log(\"hello %s\", e);",
" logger.atInfo().log(\"hello %s\", e, t);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(Exception e, Throwable t, String s) {",
" logger.atInfo().withCause(e).log(\"hello %s\", e);",
" }",
"}")
.doTest();
}
@Test
public void lazyArg() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.flogger.LazyArgs.lazy;",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(String s, Integer i) {",
" // BUG: Diagnostic contains: 'java.lang.String'",
" logger.atInfo().log(\"hello %d\", lazy(() -> s));",
" logger.atInfo().log(\"hello %d\", lazy(() -> i));",
" }",
"}")
.doTest();
}
@Test
public void varargs() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f(Object... xs) {",
" // BUG: Diagnostic contains:",
" logger.atInfo().log(\"hello %s %s\", xs);",
" }",
"}")
.doTest();
}
// log(String) takes a literal string, not a format string
@Test
public void negativeLogString() {
compilationHelper
.addSourceLines(
"Test.java",
"package test;",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void f() {",
" logger.atSevere().log(\"hello %s\");",
" }",
"}")
.doTest();
}
}
| 4,560
| 33.816794
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerStringConcatenationTest.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.flogger;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link FloggerStringConcatenation}Test */
@RunWith(JUnit4.class)
public class FloggerStringConcatenationTest {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(FloggerStringConcatenation.class, getClass());
@Test
public void fix() {
testHelper
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" private static final String CONSTANT = \"constant\";",
" public void method(String world, int i, long l, float f, double d, boolean b) {",
" logger.atInfo().log(\"hello \" + world + i + l + f + (d + \"\" + b) + CONSTANT);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" private static final String CONSTANT = \"constant\";",
" public void method(String world, int i, long l, float f, double d, boolean b) {",
" logger.atInfo().log(\"hello %s%d%d%g%g%s%s\", world, i, l, f, d, b, CONSTANT);",
" }",
"}")
.doTest();
}
@Test
public void constant() {
CompilationTestHelper.newInstance(FloggerStringConcatenation.class, getClass())
.addSourceLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" private static final String CONSTANT = \"constant\";",
" public void method() {",
" logger.atInfo().log(CONSTANT + \"hello\");",
" }",
"}")
.doTest();
}
@Test
public void minus() {
testHelper
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void method(String world, int i) {",
" logger.atInfo().log(\"hello \" + world + \" \" + (i - 1));",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void method(String world, int i) {",
" logger.atInfo().log(\"hello %s %d\", world, i - 1);",
" }",
"}")
.doTest();
}
@Test
public void numericOps() {
testHelper
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void method(int x, int y) {",
" logger.atInfo().log(x + y + \" sum; mean \" + (x + y) / 2);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" public void method(int x, int y) {",
" logger.atInfo().log(\"%d sum; mean %d\", x + y, (x + y) / 2);",
" }",
"}")
.doTest();
}
}
| 4,645
| 37.396694
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerSplitLogStatementTest.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.flogger;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FloggerSplitLogStatement}. */
@RunWith(JUnit4.class)
public final class FloggerSplitLogStatementTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FloggerSplitLogStatement.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" // BUG: Diagnostic contains:",
" FluentLogger.Api getLogger() {",
" return logger.atInfo();",
" }",
" void splitLog() {",
" // BUG: Diagnostic contains:",
" FluentLogger.Api api = logger.atInfo();",
" api.log(\"foo\");",
" }",
"}")
.doTest();
}
@Test
public void positiveVar() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" void splitLog() {",
" // BUG: Diagnostic contains:",
" var api = logger.atInfo();",
" api.log(\"foo\");",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" void log() {",
" logger.atInfo().log(\"foo\");",
" }",
"}")
.doTest();
}
}
| 2,706
| 31.614458
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerLogVarargsTest.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.flogger;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FloggerLogVarargs}. */
@RunWith(JUnit4.class)
public final class FloggerLogVarargsTest {
@Test
public void positive() {
BugCheckerRefactoringTestHelper.newInstance(FloggerLogVarargs.class, getClass())
.addInputLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" void log(String s, Object... a) {",
" logger.atInfo().log(s, a);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" void log(String s, Object... a) {",
" logger.atInfo().logVarargs(s, a);",
" }",
"}")
.doTest();
}
@Test
public void positiveAnonymousClass() {
BugCheckerRefactoringTestHelper.newInstance(FloggerLogVarargs.class, getClass())
.addInputLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"import java.util.function.Predicate;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" Predicate<Void> log(String s, Object... a) {",
" return new Predicate<Void>() {",
" @Override public boolean test(Void unused) {",
" logger.atInfo().log(s, a);",
" return true;",
" }",
" };",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"import java.util.function.Predicate;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" Predicate<Void> log(String s, Object... a) {",
" return new Predicate<Void>() {",
" @Override public boolean test(Void unused) {",
" logger.atInfo().logVarargs(s, a);",
" return true;",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void negative() {
CompilationTestHelper.newInstance(FloggerLogVarargs.class, getClass())
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" void log(String s, Object a) {",
" logger.atInfo().log(s, a);",
" }",
" void bar() {",
" logger.atInfo().log(\"foo\", new Object[] {1});",
" }",
"}")
.doTest();
}
}
| 3,900
| 35.801887
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerMessageFormatTest.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.flogger;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FloggerMessageFormat}. */
@RunWith(JUnit4.class)
public class FloggerMessageFormatTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FloggerMessageFormat.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" private static final String FORMAT_STRING = \"hello {0}\";",
" public void method(Exception e) {",
" // BUG: Diagnostic contains:",
" logger.atInfo().log(\"hello {0}\");",
" // BUG: Diagnostic contains:",
" logger.atInfo().log(\"hello {0}\", \"world\");",
" // BUG: Diagnostic contains:",
" logger.atInfo().log(\"\" + \"hello {0}\", \"world\");",
" // BUG: Diagnostic contains:",
" logger.atInfo().log(FORMAT_STRING, \"world\");",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" private static final String FORMAT_STRING = \"hello {0}\";",
" public void method(Exception e) {",
" logger.atInfo().log(\"hello %s\", \"world\");",
" logger.atInfo().log();",
" }",
"}")
.doTest();
}
@Test
public void fix() {
BugCheckerRefactoringTestHelper.newInstance(FloggerMessageFormat.class, getClass())
.addInputLines(
"in/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" private static final String FORMAT_STRING = \"hello {0}\";",
" public void method(Exception e) {",
" logger.atInfo().log(\"hello {0}\", \"world\");",
" logger.atInfo().log(\"\" + \"hello {0}\", \"world\");",
" logger.atInfo().log(FORMAT_STRING, \"world\");",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.common.flogger.FluentLogger;",
"class Test {",
" private static final FluentLogger logger = FluentLogger.forEnclosingClass();",
" private static final String FORMAT_STRING = \"hello {0}\";",
" public void method(Exception e) {",
" logger.atInfo().log(\"hello %s\", \"world\");",
" logger.atInfo().log(\"\" + \"hello %s\", \"world\");",
" logger.atInfo().log(FORMAT_STRING, \"world\");",
" }",
"}")
.doTest();
}
}
| 3,981
| 38.425743
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerRedundantIsEnabledTest.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.flogger;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author mariasam@google.com (Maria Sam)
*/
@RunWith(JUnit4.class)
public class FloggerRedundantIsEnabledTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(FloggerRedundantIsEnabled.class, getClass());
@Test
public void doPositiveCases() {
compilationTestHelper.addSourceFile("FloggerRedundantIsEnabledPositiveCases.java").doTest();
}
@Test
public void doNegativeCases() {
compilationTestHelper.addSourceFile("FloggerRedundantIsEnabledNegativeCases.java").doTest();
}
@Test
public void fixes() {
BugCheckerRefactoringTestHelper.newInstance(FloggerRedundantIsEnabled.class, getClass())
.addInput("FloggerRedundantIsEnabledPositiveCases.java")
.addOutput("FloggerRedundantIsEnabledPositiveCases_expected.java")
.doTest(TestMode.AST_MATCH);
}
}
| 1,801
| 33
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/testdata/FloggerRedundantIsEnabledPositiveCases_expected.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.flogger.testdata;
import com.google.common.flogger.FluentLogger;
/**
* @author mariasam@google.com (Maria Sam)
*/
class FloggerRedundantIsEnabledPositiveCases {
public void basicCase(FluentLogger logger) {
logger.atInfo().log("test");
}
public void nestedIf(FluentLogger logger) {
if (7 == 7) {
logger.atInfo().log("test");
}
}
public void checkBinaryInIf(FluentLogger logger) {
if (7 == 7) {
logger.atInfo().log("test");
}
}
public void checkBinaryOtherWay(FluentLogger logger) {
if (7 == 7) {
logger.atInfo().log("test");
}
}
public void complexBinary(FluentLogger logger) {
if (7 == 7 && (logger != null)) {
logger.atInfo().log("test");
}
}
public void negated(FluentLogger logger) {
logger.atInfo().log("test");
}
public void binaryNegated(FluentLogger logger) {
if (7 == 7) {
logger.atInfo().log("test");
}
}
public void checkConfig(FluentLogger logger) {
logger.atConfig().log("test");
}
public void checkFine(FluentLogger logger) {
logger.atFine().log("test");
}
public void checkFiner(FluentLogger logger) {
logger.atFiner().log("test");
}
public void checkFinest(FluentLogger logger) {
logger.atFinest().log("test");
}
public void checkWarning(FluentLogger logger) {
logger.atWarning().log("test");
}
public void checkSevere(FluentLogger logger) {
logger.atSevere().log("test");
}
}
| 2,114
| 23.034091
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/testdata/FloggerRedundantIsEnabledNegativeCases.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.flogger.testdata;
import com.google.common.flogger.FluentLogger;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author mariasam@google.com (Maria Sam)
*/
public class FloggerRedundantIsEnabledNegativeCases {
public void basicCase(FluentLogger logger) {
logger.atInfo().log("test");
}
public void sameLoggerIf(FluentLogger logger, FluentLogger logger2) {
if (logger.equals(logger2)) {
logger.atInfo().log("test");
}
}
public void relatedIf(FluentLogger logger, FluentLogger logger2) {
if (logger.atInfo().isEnabled()) {
logger2.atInfo().log("test");
}
}
public void doesWork(FluentLogger logger, Map<String, List<String>> map) {
if (logger.atFine().isEnabled()) {
for (Map.Entry<String, List<String>> toLog : map.entrySet()) {
logger.atFine().log("%s%s", toLog.getKey(), Arrays.toString(toLog.getValue().toArray()));
}
}
}
public void differentLevels(FluentLogger logger) {
if (logger.atFine().isEnabled()) {
logger.atInfo().log("This is weird but not necessarily wrong");
}
}
public void checkAtInfo(TestLogger notALogger, FluentLogger logger2) {
if (notALogger.atInfo().isEnabled()) {
logger2.atInfo().log("test");
}
}
public void checkAtInfo(TestLogger notALogger) {
if (notALogger.atInfo() == null) {
notALogger.atInfo();
}
}
public void checkMethods(FluentLogger logger) {
if (logger.atInfo().isEnabled()) {
atInfo();
isEnabled();
}
}
public void multipleLines(FluentLogger logger) {
if (logger.atInfo().isEnabled()) {
int foo = 10;
logger.atInfo().log("test");
}
}
public boolean atInfo() {
return true;
}
public boolean isEnabled() {
return true;
}
private class TestLogger {
public TestLogger atInfo() {
return null;
}
public boolean isEnabled() {
return true;
}
}
}
| 2,598
| 24.23301
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/flogger/testdata/FloggerRedundantIsEnabledPositiveCases.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.flogger.testdata;
import com.google.common.flogger.FluentLogger;
/** Created by mariasam on 7/17/17. */
class FloggerRedundantIsEnabledPositiveCases {
public void basicCase(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atInfo().isEnabled()) {
logger.atInfo().log("test");
}
}
public void nestedIf(FluentLogger logger) {
if (7 == 7) {
// BUG: Diagnostic contains: redundant
if (logger.atInfo().isEnabled()) {
logger.atInfo().log("test");
}
}
}
public void checkBinaryInIf(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (7 == 7 && logger.atInfo().isEnabled()) {
logger.atInfo().log("test");
}
}
public void checkBinaryOtherWay(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atInfo().isEnabled() && 7 == 7) {
logger.atInfo().log("test");
}
}
public void complexBinary(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (7 == 7 && (logger != null && logger.atInfo().isEnabled())) {
logger.atInfo().log("test");
}
}
public void negated(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (!logger.atInfo().isEnabled()) {
logger.atInfo().log("test");
}
}
public void binaryNegated(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (!logger.atInfo().isEnabled() && 7 == 7) {
logger.atInfo().log("test");
}
}
public void checkConfig(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atConfig().isEnabled()) {
logger.atConfig().log("test");
}
}
public void checkFine(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atFine().isEnabled()) {
logger.atFine().log("test");
}
}
public void checkFiner(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atFiner().isEnabled()) {
logger.atFiner().log("test");
}
}
public void checkFinest(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atFinest().isEnabled()) {
logger.atFinest().log("test");
}
}
public void checkWarning(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atWarning().isEnabled()) {
logger.atWarning().log("test");
}
}
public void checkSevere(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atSevere().isEnabled()) {
logger.atSevere().log("test");
}
}
}
| 3,226
| 26.581197
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/overloading/InconsistentOverloadsTest.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.overloading;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Test cases for {@link InconsistentOverloads}.
*
* @author hanuszczak@google.com (Łukasz Hanuszczak)
*/
@RunWith(JUnit4.class)
public final class InconsistentOverloadsTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(InconsistentOverloads.class, getClass());
@Test
public void inconsistentOverloadsNegativeCases() {
compilationHelper.addSourceFile("InconsistentOverloadsNegativeCases.java").doTest();
}
@Test
public void inconsistentOverloadsPositiveCasesAnnotations() {
compilationHelper.addSourceFile("InconsistentOverloadsPositiveCasesAnnotations.java").doTest();
}
@Test
public void inconsistentOverloadsPositiveCasesGeneral() {
compilationHelper.addSourceFile("InconsistentOverloadsPositiveCasesGeneral.java").doTest();
}
@Test
public void inconsistentOverloadsPositiveCasesGenerics() {
compilationHelper.addSourceFile("InconsistentOverloadsPositiveCasesGenerics.java").doTest();
}
@Test
public void inconsistentOverloadsPositiveCasesInterleaved() {
compilationHelper.addSourceFile("InconsistentOverloadsPositiveCasesInterleaved.java").doTest();
}
@Test
public void inconsistentOverloadsPositiveCasesSimple() {
compilationHelper.addSourceFile("InconsistentOverloadsPositiveCasesSimple.java").doTest();
}
@Test
public void inconsistentOverloadsPositiveCasesVarargs() {
compilationHelper.addSourceFile("InconsistentOverloadsPositiveCasesVarargs.java").doTest();
}
@Test
public void inconsistentOverloadsOverrides() {
compilationHelper.addSourceFile("InconsistentOverloadsPositiveCasesOverrides.java").doTest();
}
@Test
public void suppressOnMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public void foo(Object object) {}",
" @SuppressWarnings(\"InconsistentOverloads\")",
" public void foo(int i, Object object) {}",
"}")
.doTest();
}
}
| 2,832
| 31.563218
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/overloading/testdata/InconsistentOverloadsPositiveCasesAnnotations.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.overloading.testdata;
import javax.annotation.Nullable;
public abstract class InconsistentOverloadsPositiveCasesAnnotations {
@interface Bar {}
@interface Baz {}
// BUG: Diagnostic contains: foo(String x, String y, Object z)
abstract void foo(@Nullable Object z, String y, @Nullable String x);
abstract void foo(@Nullable String x);
// BUG: Diagnostic contains: foo(String x, String y)
abstract void foo(String y, @Nullable String x);
// BUG: Diagnostic contains: quux(Object object, String string)
int quux(String string, @Bar @Baz Object object) {
return string.hashCode() + quux(object);
}
int quux(@Bar @Baz Object object) {
return object.hashCode();
}
// BUG: Diagnostic contains: quux(Object object, String string, int x, int y)
abstract int quux(String string, int x, int y, @Bar @Baz Object object);
abstract int norf(@Bar @Baz String string);
// BUG: Diagnostic contains: norf(String string, Object object)
abstract int norf(Object object, @Baz @Bar String string);
}
| 1,682
| 31.365385
| 79
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/overloading/testdata/InconsistentOverloadsPositiveCasesGeneral.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.overloading.testdata;
public final class InconsistentOverloadsPositiveCasesGeneral {
public void foo(Object object) {}
// BUG: Diagnostic contains: foo(Object object, int i)
public void foo(int i, Object object) {}
// BUG: Diagnostic contains: foo(Object object, int i, String string)
public void foo(String string, Object object, int i) {}
// BUG: Diagnostic contains: bar(int i, int j, String x, String y, Object object)
public void bar(Object object, String x, String y, int i, int j) {}
public void bar(int i, int j) {}
// BUG: Diagnostic contains: bar(int i, int j, String x, String y)
public void bar(String x, String y, int i, int j) {}
public void baz(int i, int j) {}
public void baz(Object object) {}
// BUG: Diagnostic contains: baz(int i, int j, String x, Object object)
public void baz(String x, int i, int j, Object object) {}
public void quux(int x, int y, String string) {}
// BUG: Diagnostic contains: quux(int x, int y, Object object)
public void quux(Object object, int y, int x) {}
}
| 1,701
| 33.734694
| 83
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/overloading/testdata/InconsistentOverloadsNegativeCases.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.overloading.testdata;
public final class InconsistentOverloadsNegativeCases {
public void foo(Object object) {}
public void foo(Object object, int x, int y) {}
public void foo(Object object, int x, int y, String string) {}
public void bar(int x, int y, int z) {}
public void bar(int x) {}
public void bar(int x, int y) {}
public void baz(String string) {}
public void baz(int x, int y, String otherString) {}
public void baz(int x, int y, String otherString, Object object) {}
public void quux(int x, int y, int z) {}
public void quux(int x, int y, String string) {}
public void norf(int x, int y) {}
public void norf(Object object, String string) {}
}
| 1,344
| 27.617021
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/overloading/testdata/InconsistentOverloadsPositiveCasesGenerics.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.overloading.testdata;
import java.util.List;
public final class InconsistentOverloadsPositiveCasesGenerics {
// BUG: Diagnostic contains: foo(List<Integer> numbers, List<List<Integer>> nestedNumbers)
public void foo(List<List<Integer>> nestedNumbers, List<Integer> numbers) {}
public void foo(List<Integer> numbers) {}
// BUG: Diagnostic contains: foo(Iterable<Integer> numbers, String description)
public void foo(String description, Iterable<Integer> numbers) {}
public void bar(int x) {}
// BUG: Diagnostic contains: bar(int x, List<? extends java.util.ArrayList<String>> strings)
public void bar(List<? extends java.util.ArrayList<String>> strings, int x) {}
}
| 1,339
| 36.222222
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/overloading/testdata/InconsistentOverloadsPositiveCasesInterleaved.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.overloading.testdata;
public final class InconsistentOverloadsPositiveCasesInterleaved {
// BUG: Diagnostic contains: baz(int x, String string, int y)
public void baz(int y, int x, String string) {}
// BUG: Diagnostic contains: foo(int x, int y, int z, String string)
public void foo(int x, int z, int y, String string) {}
public void foo(int x, int y) {}
public void bar(String string, Object object) {}
// BUG: Diagnostic contains: baz(int x, String string)
public void baz(String string, int x) {}
// BUG: Diagnostic contains: foo(int x, int y, int z)
public void foo(int z, int x, int y) {}
// BUG: Diagnostic contains: bar(String string, Object object, int x, int y)
public void bar(int x, int y, String string, Object object) {}
public void baz(int x) {}
}
| 1,449
| 33.52381
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/overloading/testdata/InconsistentOverloadsPositiveCasesOverrides.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.overloading.testdata;
import java.util.List;
import java.util.Map;
public class InconsistentOverloadsPositiveCasesOverrides {
class SuperClass {
void someMethod(String foo, int bar) {}
// BUG: Diagnostic contains: someMethod(String foo, int bar, List<String> baz)
void someMethod(int bar, String foo, List<String> baz) {}
}
class SubClass extends SuperClass {
@Override // no bug
void someMethod(String foo, int bar) {}
@Override // no bug
void someMethod(int bar, String foo, List<String> baz) {}
// BUG: Diagnostic contains: someMethod(String foo, int bar, List<String> baz, Map<String,
// String> fizz)
void someMethod(int bar, String foo, List<String> baz, Map<String, String> fizz) {}
}
}
| 1,402
| 30.177778
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/overloading/testdata/InconsistentOverloadsPositiveCasesVarargs.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.overloading.testdata;
public abstract class InconsistentOverloadsPositiveCasesVarargs {
public void foo(String... rest) {}
public void foo(int x, String... rest) {}
// BUG: Diagnostic contains: foo(int x, int y, String... rest)
public void foo(int y, int x, String... rest) {}
abstract void bar(float x, float y);
// BUG: Diagnostic contains: bar(float x, float y, float z, Object... rest)
abstract void bar(float z, float y, float x, Object... rest);
// BUG: Diagnostic contains: bar(float x, float y, float z, String string)
abstract void bar(float y, String string, float x, float z);
abstract void bar(Object... rest);
}
| 1,304
| 33.342105
| 77
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/overloading/testdata/InconsistentOverloadsPositiveCasesSimple.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.overloading.testdata;
public final class InconsistentOverloadsPositiveCasesSimple {
public void foo(Object object) {}
// BUG: Diagnostic contains: foo(Object object, int x, int y)
public void foo(int x, int y, Object object) {}
// BUG: Diagnostic contains: foo(Object object, int x, int y, String string)
public void foo(String string, int y, Object object, int x) {}
}
| 1,035
| 34.724138
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/PeriodFromTest.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.time;
import static org.junit.Assert.assertThrows;
import com.google.errorprone.CompilationTestHelper;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.Period;
import java.time.temporal.TemporalAmount;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link PeriodFrom}. */
@RunWith(JUnit4.class)
public class PeriodFromTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(PeriodFrom.class, getClass());
@SuppressWarnings("PeriodFrom")
@Test
public void failures() {
assertThrows(DateTimeException.class, () -> Period.from(Duration.ZERO));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofNanos(1)));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofNanos(-1)));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofMillis(1)));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofMillis(-1)));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofSeconds(1)));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofSeconds(-1)));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofMinutes(1)));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofMinutes(-1)));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofDays(1)));
assertThrows(DateTimeException.class, () -> Period.from(Duration.ofDays(-1)));
TemporalAmount temporalAmount = Duration.ofDays(3);
assertThrows(DateTimeException.class, () -> Period.from(temporalAmount));
}
@Test
public void periodFrom() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.Period;",
"import java.time.temporal.TemporalAmount;",
"public class TestClass {",
" // BUG: Diagnostic contains: PeriodFrom",
" private final Period oneDay = Period.from(Duration.ofDays(1));",
" // BUG: Diagnostic contains: Period.ofDays(2)",
" private final Period twoDays = Period.from(Period.ofDays(2));",
" private final TemporalAmount temporalAmount = Duration.ofDays(3);",
// don't trigger when it is not statically known to be a Duration/Period
" private final Duration threeDays = Duration.from(temporalAmount);",
"}")
.doTest();
}
}
| 3,167
| 41.810811
| 85
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaLocalDateTimeGetNanoTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JavaLocalDateTimeGetNano}. */
@RunWith(JUnit4.class)
public final class JavaLocalDateTimeGetNanoTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JavaLocalDateTimeGetNano.class, getClass());
@Test
public void getSecondWithGetNano() {
compilationHelper
.addSourceLines(
"Test.java",
"package test;",
"import java.time.LocalDateTime;",
"public class Test {",
" public static void foo(LocalDateTime localDateTime) {",
" long seconds = localDateTime.getSecond();",
" int nanos = localDateTime.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getNanoWithNoGetSeconds() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.LocalDateTime;",
"public class Test {",
" public static int foo(LocalDateTime localDateTime) {",
" // BUG: Diagnostic contains:",
" return localDateTime.getNano();",
" }",
"}")
.doTest();
}
}
| 1,979
| 32
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JodaDateTimeConstantsTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JodaDateTimeConstants}. */
@RunWith(JUnit4.class)
public class JodaDateTimeConstantsTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaDateTimeConstants.class, getClass());
@Test
public void assignment() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateTimeConstants;",
"public class TestClass {",
" // BUG: Diagnostic contains: JodaDateTimeConstants",
" private final long oneMinsInMillis = DateTimeConstants.MILLIS_PER_MINUTE;",
// this usage is OK - we only flag the _PER_ constants
" private final int january = DateTimeConstants.JANUARY;",
"}")
.doTest();
}
@Test
public void usedInMultiplication() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateTimeConstants;",
"public class TestClass {",
" // BUG: Diagnostic contains: JodaDateTimeConstants",
" private final long sixMinsInMillis = 6 * DateTimeConstants.MILLIS_PER_MINUTE;",
"}")
.doTest();
}
@Test
public void staticImported() {
helper
.addSourceLines(
"TestClass.java",
"import static org.joda.time.DateTimeConstants.MILLIS_PER_MINUTE;",
"public class TestClass {",
" // BUG: Diagnostic contains: JodaDateTimeConstants",
" private final long sixMinsInMillis = 6 * MILLIS_PER_MINUTE;",
"}")
.doTest();
}
}
| 2,404
| 33.357143
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JodaWithDurationAddedLongTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JodaWithDurationAddedLong}. */
@RunWith(JUnit4.class)
public class JodaWithDurationAddedLongTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaWithDurationAddedLong.class, getClass());
// Instant
@Test
public void instantWithDurationAddedDuration() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"import org.joda.time.Instant;",
"public class TestClass {",
" private static final Instant NOW = Instant.now();",
" private static final Instant A = NOW.withDurationAdded(Duration.millis(42), 1);",
" private static final Instant B =",
" // BUG: Diagnostic contains: NOW.plus(Duration.millis(42));",
" NOW.withDurationAdded(Duration.millis(42).getMillis(), 1);",
"}")
.doTest();
}
@Test
public void instantWithDurationAddedLong() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"import org.joda.time.Instant;",
"public class TestClass {",
" private static final Instant NOW = Instant.now();",
" // BUG: Diagnostic contains: NOW.withDurationAdded(Duration.millis(42), 2);",
" private static final Instant A = NOW.withDurationAdded(42, 2);",
" private static final Instant B =",
" // BUG: Diagnostic contains: NOW.withDurationAdded(Duration.millis(42), 2);",
" NOW.withDurationAdded(Duration.millis(42).getMillis(), 2);",
"",
" // BUG: Diagnostic contains: NOW.plus(Duration.millis(42));",
" private static final Instant PLUS = NOW.withDurationAdded(42, 1);",
" // BUG: Diagnostic contains: NOW;",
" private static final Instant ZERO = NOW.withDurationAdded(42, 0);",
" // BUG: Diagnostic contains: NOW.minus(Duration.millis(42));",
" private static final Instant MINUS = NOW.withDurationAdded(42, -1);",
"}")
.doTest();
}
@Test
public void instantWithDurationAddedLong_insideJodaTime() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final Instant A = Instant.now().withDurationAdded(42, 1);",
"}")
.doTest();
}
// Duration
@Test
public void durationWithDurationAddedDuration() {
helper
.addSourceLines(
"TestClass.java",
"import static org.joda.time.Duration.ZERO;",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration A = ZERO.withDurationAdded(Duration.millis(42), 1);",
" private static final Duration B =",
" // BUG: Diagnostic contains: ZERO.plus(Duration.millis(42));",
" ZERO.withDurationAdded(Duration.millis(42).getMillis(), 1);",
"}")
.doTest();
}
@Test
public void durationWithDurationAddedLong() {
helper
.addSourceLines(
"TestClass.java",
"import static org.joda.time.Duration.ZERO;",
"import org.joda.time.Duration;",
"public class TestClass {",
" // BUG: Diagnostic contains: ZERO.withDurationAdded(Duration.millis(42), 2);",
" private static final Duration A = ZERO.withDurationAdded(42, 2);",
" private static final Duration B =",
" // BUG: Diagnostic contains: ZERO.withDurationAdded(Duration.millis(42), 2);",
" ZERO.withDurationAdded(Duration.millis(42).getMillis(), 2);",
"",
" // BUG: Diagnostic contains: ZERO.plus(Duration.millis(42));",
" private static final Duration PLUS = ZERO.withDurationAdded(42, 1);",
" // BUG: Diagnostic contains: ZERO;",
" private static final Duration ZEROX = ZERO.withDurationAdded(42, 0);",
" // BUG: Diagnostic contains: ZERO.minus(Duration.millis(42));",
" private static final Duration MINUS = ZERO.withDurationAdded(42, -1);",
"}")
.doTest();
}
@Test
public void durationWithDurationAddedLong_insideJodaTime() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"import static org.joda.time.Duration.ZERO;",
"public class TestClass {",
" private static final Duration A = ZERO.withDurationAdded(42, 1);",
"}")
.doTest();
}
// DateTime
@Test
public void dateTimeWithDurationAddedDuration() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"import org.joda.time.DateTime;",
"public class TestClass {",
" private static final DateTime NOW = DateTime.now();",
" private static final DateTime A = NOW.withDurationAdded(Duration.millis(42), 1);",
" private static final DateTime B =",
" // BUG: Diagnostic contains: NOW.plus(Duration.millis(42));",
" NOW.withDurationAdded(Duration.millis(42).getMillis(), 1);",
"}")
.doTest();
}
@Test
public void dateTimeWithDurationAddedLong() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateTime;",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final DateTime NOW = DateTime.now();",
" // BUG: Diagnostic contains: NOW.withDurationAdded(Duration.millis(42), 2);",
" private static final DateTime A = NOW.withDurationAdded(42, 2);",
" private static final DateTime B =",
" // BUG: Diagnostic contains: NOW.withDurationAdded(Duration.millis(42), 2);",
" NOW.withDurationAdded(Duration.millis(42).getMillis(), 2);",
"",
" // BUG: Diagnostic contains: NOW.plus(Duration.millis(42));",
" private static final DateTime PLUS = NOW.withDurationAdded(42, 1);",
" // BUG: Diagnostic contains: NOW;",
" private static final DateTime ZERO = NOW.withDurationAdded(42, 0);",
" // BUG: Diagnostic contains: NOW.minus(Duration.millis(42));",
" private static final DateTime MINUS = NOW.withDurationAdded(42, -1);",
"}")
.doTest();
}
@Test
public void dateTimeWithDurationAddedLong_insideJodaTime() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final DateTime A = DateTime.now().withDurationAdded(42, 1);",
"}")
.doTest();
}
}
| 7,832
| 38.964286
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JodaInstantWithMillisTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JodaInstantWithMillis}. */
@RunWith(JUnit4.class)
public class JodaInstantWithMillisTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaInstantWithMillis.class, getClass());
@Test
public void instantConstructor() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Instant;",
"public class TestClass {",
" private static final Instant INSTANT = new Instant(42);",
"}")
.doTest();
}
@Test
public void instantWithMillisIntPrimitive() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Instant;",
"public class TestClass {",
" // BUG: Diagnostic contains: Instant.ofEpochMilli(42);",
" private static final Instant INSTANT = Instant.now().withMillis(42);",
"}")
.doTest();
}
@Test
public void instantWithMillisLongPrimitive() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Instant;",
"public class TestClass {",
" // BUG: Diagnostic contains: Instant.ofEpochMilli(42L);",
" private static final Instant INSTANT = Instant.now().withMillis(42L);",
"}")
.doTest();
}
@Test
public void instantWithMillisNamedVariable() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Instant;",
"public class TestClass {",
" private static final Instant INSTANT1 = new Instant(42);",
" // BUG: Diagnostic contains: Instant.ofEpochMilli(44);",
" private static final Instant INSTANT2 = INSTANT1.withMillis(44);",
"}")
.doTest();
}
@Test
public void instantConstructorIntPrimitiveInsideJoda() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final Instant INSTANT = Instant.now().withMillis(42);",
"}")
.doTest();
}
@Test
public void instantConstructorLongPrimitiveInsideJoda() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final Instant INSTANT = Instant.now().withMillis(42L);",
"}")
.doTest();
}
@Test
public void instantConstructorLongPrimitiveImportClash() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"public class TestClass {",
" private static final org.joda.time.Instant INSTANT = ",
" // BUG: Diagnostic contains: org.joda.time.Instant.ofEpochMilli(42L);",
" org.joda.time.Instant.now().withMillis(42L);",
"}")
.doTest();
}
}
| 3,807
| 31
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/ZoneIdOfZTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link ZoneIdOfZ}. */
@RunWith(JUnit4.class)
public class ZoneIdOfZTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(ZoneIdOfZ.class, getClass());
@Test
public void zoneIdOfNyc() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.ZoneId;",
"public class TestClass {",
" private static final ZoneId NYC = ZoneId.of(\"America/New_York\");",
"}")
.doTest();
}
@Test
public void zoneIdOfZ() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.ZoneId;",
"public class TestClass {",
" // BUG: Diagnostic contains: private static final ZoneId UTC = ZoneOffset.UTC;",
" private static final ZoneId UTC = ZoneId.of(\"Z\");",
"}")
.doTest();
}
@Test
public void zoneIdOfLowerCaseZ() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.ZoneId;",
"public class TestClass {",
" private static final ZoneId UTC = ZoneId.of(\"z\");",
"}")
.doTest();
}
@Test
public void zoneIdOfConstant() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.ZoneId;",
"public class TestClass {",
" private static final String ZONE = \"Z\";",
" // BUG: Diagnostic contains: private static final ZoneId UTC = ZoneOffset.UTC;",
" private static final ZoneId UTC = ZoneId.of(ZONE);",
"}")
.doTest();
}
@Test
public void zoneIdOfNonConstant() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.ZoneId;",
"public class TestClass {",
" private String zone = \"z\";",
" private ZoneId utc = ZoneId.of(zone);",
"}")
.doTest();
}
}
| 2,791
| 29.021505
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/StronglyTypeTimeTest.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.time;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link StronglyTypeTime}. */
@RunWith(JUnit4.class)
public final class StronglyTypeTimeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(StronglyTypeTime.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(StronglyTypeTime.class, getClass());
@Test
public void findingLocatedOnField() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" // BUG: Diagnostic contains: Duration instances",
" private static final long FOO_MILLIS = 100;",
" public Duration get() {",
" return Duration.ofMillis(FOO_MILLIS);",
" }",
"}")
.doTest();
}
@Test
public void findingOnBoxedField() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" // BUG: Diagnostic contains:",
" private static final Long FOO_MILLIS = 100L;",
" public Duration get() {",
" return Duration.ofMillis(FOO_MILLIS);",
" }",
"}")
.doTest();
}
@Test
public void jodaInstantConstructor() {
refactoringHelper
.addInputLines(
"Test.java",
"import org.joda.time.Instant;",
"class Test {",
" private static final long FOO_MILLIS = 100L;",
" public Instant get() {",
" return new Instant(FOO_MILLIS);",
" }",
"}")
.addOutputLines(
"Test.java",
"import org.joda.time.Instant;",
"class Test {",
" private static final Instant FOO = new Instant(100L);",
" public Instant get() {",
" return FOO;",
" }",
"}")
.doTest();
}
@Test
public void jodaInstantStaticFactory() {
refactoringHelper
.addInputLines(
"Test.java",
"import org.joda.time.Instant;",
"class Test {",
" private static final long FOO_MILLIS = 100L;",
" public Instant get() {",
" return Instant.ofEpochMilli(FOO_MILLIS);",
" }",
"}")
.addOutputLines(
"Test.java",
"import org.joda.time.Instant;",
"class Test {",
" private static final Instant FOO = Instant.ofEpochMilli(100L);",
" public Instant get() {",
" return FOO;",
" }",
"}")
.doTest();
}
@Test
public void protoTimestamp() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.protobuf.Timestamp;",
"import com.google.protobuf.util.Timestamps;",
"class Test {",
" private static final long FOO_MILLIS = 100L;",
" public Timestamp get() {",
" return Timestamps.fromMillis(FOO_MILLIS);",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.protobuf.Timestamp;",
"import com.google.protobuf.util.Timestamps;",
"class Test {",
" private static final Timestamp FOO = Timestamps.fromMillis(100L);",
" public Timestamp get() {",
" return FOO;",
" }",
"}")
.doTest();
}
@Test
public void fieldQualifiedByThis() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" // BUG: Diagnostic contains:",
" private final long fooMillis = 100;",
" public Duration get() {",
" return Duration.ofMillis(this.fooMillis);",
" }",
"}")
.doTest();
}
@Test
public void notInitializedInline_noFinding() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private static final long FOO_MILLIS;",
" static {",
" FOO_MILLIS = 100;",
" }",
" public Duration get() {",
" return Duration.ofMillis(FOO_MILLIS);",
" }",
"}")
.doTest();
}
@Test
public void refactoring() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private final long FOO_MILLIS = 100;",
" public Duration get() {",
" return Duration.ofMillis(FOO_MILLIS);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private final Duration FOO = Duration.ofMillis(100);",
" public Duration get() {",
" return FOO;",
" }",
"}")
.doTest();
}
@Test
public void fieldRenaming() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private final long FOO_MILLIS = 100;",
" private final long BAR_IN_MILLIS = 100;",
" private final long BAZ_MILLI = 100;",
" public Duration foo() {",
" return Duration.ofMillis(FOO_MILLIS);",
" }",
" public Duration bar() {",
" return Duration.ofMillis(BAR_IN_MILLIS);",
" }",
" public Duration baz() {",
" return Duration.ofMillis(BAZ_MILLI);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private final Duration FOO = Duration.ofMillis(100);",
" private final Duration BAR = Duration.ofMillis(100);",
" private final Duration BAZ = Duration.ofMillis(100);",
" public Duration foo() {",
" return FOO;",
" }",
" public Duration bar() {",
" return BAR;",
" }",
" public Duration baz() {",
" return BAZ;",
" }",
"}")
.doTest();
}
@Test
public void variableUsedInOtherWays_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private final long FOO_MILLIS = 100;",
" public Duration get() {",
" return Duration.ofMillis(FOO_MILLIS);",
" }",
" public long frobnicate() {",
" return FOO_MILLIS + 1;",
" }",
"}")
.doTest();
}
@Test
public void fieldNotPrivate_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" final long FOO_MILLIS = 100;",
" public Duration get() {",
" return Duration.ofMillis(FOO_MILLIS);",
" }",
"}")
.doTest();
}
@Test
public void unusedField_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.io.Serializable;",
"class Test implements Serializable {",
" private static final long serialVersionUID = 1L;",
"}")
.expectNoDiagnostics()
.doTest();
}
@Test
public void whenJodaAndJavaInstantUsed_fullyQualifiesName() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.time.Instant;",
"class Test {",
" private static final long FOO_MILLIS = 100L;",
" private static final Instant INSTANT = null;",
" public org.joda.time.Instant get() {",
" return new org.joda.time.Instant(FOO_MILLIS);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.time.Instant;",
"class Test {",
" private static final org.joda.time.Instant FOO = new org.joda.time.Instant(100L);",
" private static final Instant INSTANT = null;",
" public org.joda.time.Instant get() {",
" return FOO;",
" }",
"}")
.doTest();
}
@Test
public void milliseconds() {
refactoringHelper
.addInputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private static final long F1_RETRY_MILLISECONDS = 5000;",
" public Duration frobber() {",
" return Duration.ofMillis(F1_RETRY_MILLISECONDS);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.time.Duration;",
"class Test {",
" private static final Duration F1_RETRY = Duration.ofMillis(5000);",
" public Duration frobber() {",
" return F1_RETRY;",
" }",
"}")
.doTest();
}
}
| 10,403
| 30.149701
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaPeriodGetDaysTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link JavaPeriodGetDays}.
*
* @author kak@google.com (Kurt Alfred Kluever)
*/
@RunWith(JUnit4.class)
public class JavaPeriodGetDaysTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JavaPeriodGetDays.class, getClass());
@Test
public void getBoth() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" public static void foo(Period period) {",
" int days = period.getDays();",
" int months = period.getMonths();",
" }",
"}")
.doTest();
}
@Test
public void getDaysInReturn() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" public static int foo(Period period) {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" return period.getDays();",
" }",
"}")
.doTest();
}
@Test
public void getDaysInReturnWithConsultingMonths() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.common.collect.ImmutableMap;",
"import java.time.Period;",
"public class TestCase {",
" public static ImmutableMap<String, Object> foo(Period period) {",
" return ImmutableMap.of(",
" \"months\", period.getMonths(), \"days\", period.getDays());",
" }",
"}")
.doTest();
}
@Test
public void getDaysWithMonthsInDifferentScope() {
// Ideally we would also catch cases like this, but it requires scanning "too much" of the class
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" public static void foo(Period period) {",
" long months = period.getMonths();",
" if (true) {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" int days = period.getDays();",
" }",
" }",
"}")
.doTest();
}
@Test
public void getDaysAndGetMonthsInDifferentMethods() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" public static void foo(Period period) {",
" long months = period.getMonths();",
" }",
" public static void bar(Period period) {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" int days = period.getDays();",
" }",
"}")
.doTest();
}
@Test
public void getMonths() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" public static void foo(Period period) {",
" long months = period.getMonths();",
" }",
"}")
.doTest();
}
@Test
public void getDaysOnly() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" public static void foo(Period period) {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" int days = period.getDays();",
" }",
"}")
.doTest();
}
@Test
public void getMonthsInVariableDetachedFromDays() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" private static final Period PERIOD = Period.ZERO;",
" private static final long months = PERIOD.getMonths();",
" public static void foo() {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" int days = PERIOD.getDays();",
" }",
"}")
.doTest();
}
@Test
public void getMonthsInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" static {",
" long months = Period.ZERO.getMonths();",
" }",
"}")
.doTest();
}
@Test
public void getDaysInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" static {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" int days = Period.ZERO.getDays();",
" }",
"}")
.doTest();
}
@Test
public void getDaysAndMonthsInParallelInitializers() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" private final long months = Period.ZERO.getMonths();",
" private final int days = Period.ZERO.getDays();",
"}")
.doTest();
}
@Test
public void getDaysInFieldInitializer() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" private final int days = Period.ZERO.getDays();",
"}")
.doTest();
}
@Test
public void getDaysInInnerClass() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" private static final Period PERIOD = Period.ZERO;",
" public static void foo() {",
" long months = PERIOD.getMonths();",
" Object obj = new Object() {",
" @Override public String toString() {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" return String.valueOf(PERIOD.getDays()); ",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void getDaysInInnerClassField() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" Period PERIOD = Period.ZERO;",
" long months = PERIOD.getMonths();",
" Object obj = new Object() {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" long days = PERIOD.getDays();",
" };",
"}")
.doTest();
}
@Test
public void getDaysWithMonthInLambdaContext() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" private static final Period PERIOD = Period.ZERO;",
" public static void foo() {",
" Runnable r = () -> PERIOD.getMonths();",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" int days = PERIOD.getDays();",
" }",
"}")
.doTest();
}
@Test
public void getDaysWithMonthInMethodArgumentLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"import java.util.function.Supplier;",
"public class TestCase {",
" private static final Period PERIOD = Period.ZERO;",
" public void foo() {",
" doSomething(() -> PERIOD.getMonths());",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" int days = PERIOD.getDays();",
" }",
" public void doSomething(Supplier<Integer> supplier) {",
" }",
"}")
.doTest();
}
@Test
public void getDaysInLambdaWithMonthOutside() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Period;",
"public class TestCase {",
" private static final Period PERIOD = Period.ZERO;",
" public static void foo() {",
" // BUG: Diagnostic contains: JavaPeriodGetDays",
" Runnable r = () -> PERIOD.getDays();",
" long months = PERIOD.getMonths();",
" }",
"}")
.doTest();
}
}
| 10,219
| 30.253823
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/LocalDateTemporalAmountTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link LocalDateTemporalAmount}. */
@RunWith(JUnit4.class)
public final class LocalDateTemporalAmountTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(LocalDateTemporalAmount.class, getClass());
@Test
public void localDatePlus_good() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.LocalDate;",
"import java.time.Period;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" private static final LocalDate LD = LocalDate.of(1985, 5, 31);",
" private static final Period PERIOD = Period.ofDays(1);",
" private static final LocalDate LD1 = LD.plus(PERIOD);",
" private static final LocalDate LD2 = LD.plus(1, ChronoUnit.DAYS);",
"}")
.doTest();
}
@Test
public void localDatePlus_bad() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.LocalDate;",
"public class TestClass {",
" private static final LocalDate LD = LocalDate.of(1985, 5, 31);",
" private static final Duration DURATION = Duration.ofDays(1);",
" // BUG: Diagnostic contains: LocalDateTemporalAmount",
" private static final LocalDate LD0 = LD.plus(DURATION);",
"}")
.doTest();
}
@Test
public void localDatePlus_zero() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.LocalDate;",
"public class TestClass {",
" private static final LocalDate LD = LocalDate.of(1985, 5, 31);",
" // BUG: Diagnostic contains: LocalDateTemporalAmount",
// This call technically doesn't throw, but we don't currently special case it
" private static final LocalDate LD0 = LD.plus(Duration.ZERO);",
"}")
.doTest();
}
@Test
public void localDateMinus_good() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.LocalDate;",
"import java.time.Period;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" private static final LocalDate LD = LocalDate.of(1985, 5, 31);",
" private static final Period PERIOD = Period.ofDays(1);",
" private static final LocalDate LD1 = LD.minus(PERIOD);",
" private static final LocalDate LD2 = LD.minus(1, ChronoUnit.DAYS);",
"}")
.doTest();
}
@Test
public void localDateMinus_bad() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.LocalDate;",
"public class TestClass {",
" private static final LocalDate LD = LocalDate.of(1985, 5, 31);",
" private static final Duration DURATION = Duration.ofDays(1);",
" // BUG: Diagnostic contains: LocalDateTemporalAmount",
" private static final LocalDate LD0 = LD.minus(DURATION);",
"}")
.doTest();
}
@Test
public void localDateMinus_zero() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.LocalDate;",
"public class TestClass {",
" private static final LocalDate LD = LocalDate.of(1985, 5, 31);",
" // BUG: Diagnostic contains: LocalDateTemporalAmount",
// This call technically doesn't throw, but we don't currently special case it
" private static final LocalDate LD0 = LD.minus(Duration.ZERO);",
"}")
.doTest();
}
}
| 4,675
| 35.818898
| 90
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/PreferJavaTimeOverloadTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link PreferJavaTimeOverload}. */
@RunWith(JUnit4.class)
public class PreferJavaTimeOverloadTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(PreferJavaTimeOverload.class, getClass());
@Test
public void callingLongTimeUnitMethodWithDurationOverload_microseconds() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.common.cache.CacheBuilder;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" public CacheBuilder foo(CacheBuilder builder) {",
" // BUG: Diagnostic contains: builder.expireAfterAccess(Duration.of(42,"
+ " ChronoUnit.MICROS));",
" return builder.expireAfterAccess(42, TimeUnit.MICROSECONDS);",
" }",
"}")
.doTest();
}
@Test
public void callingLongTimeUnitMethodWithDurationOverload() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.common.cache.CacheBuilder;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" public CacheBuilder foo(CacheBuilder builder) {",
" // BUG: Diagnostic contains: builder.expireAfterAccess(Duration.ofSeconds(42L));",
" return builder.expireAfterAccess(42L, TimeUnit.SECONDS);",
" }",
"}")
.doTest();
}
@Test
public void callingLongTimeUnitMethodWithDurationOverload_durationDecompose() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.common.cache.CacheBuilder;",
"import java.time.Duration;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" public CacheBuilder foo(CacheBuilder builder) {",
" Duration duration = Duration.ofMillis(12345);",
" // BUG: Diagnostic contains: builder.expireAfterAccess(duration);",
" return builder.expireAfterAccess(duration.getSeconds(), TimeUnit.SECONDS);",
" }",
"}")
.doTest();
}
@Test
public void callingLongTimeUnitMethodWithDurationOverload_durationHashCode() {
// this is admittedly a _very_ weird case, but we should _not_ suggest re-writing to:
// builder.expireAfterAccess(duration)
helper
.addSourceLines(
"TestClass.java",
"import com.google.common.cache.CacheBuilder;",
"import java.time.Duration;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" public CacheBuilder foo(CacheBuilder builder) {",
" Duration duration = Duration.ofMillis(12345);",
" // BUG: Diagnostic contains: return"
+ " builder.expireAfterAccess(Duration.ofSeconds(duration.hashCode()));",
" return builder.expireAfterAccess(duration.hashCode(), TimeUnit.SECONDS);",
" }",
"}")
.doTest();
}
@Test
public void callingLongTimeUnitMethodWithDurationOverload_intParam() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.common.cache.CacheBuilder;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" public CacheBuilder foo(CacheBuilder builder) {",
" // BUG: Diagnostic contains: builder.expireAfterAccess(Duration.ofSeconds(42));",
" return builder.expireAfterAccess(42, TimeUnit.SECONDS);",
" }",
"}")
.doTest();
}
@Test
public void callLongTimeUnitInsideImpl() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" private void bar(long d, TimeUnit u) {",
" }",
" private void bar(Duration d) {",
// Would normally flag, but we're avoiding recursive suggestions
" bar(d.toMillis(), TimeUnit.MILLISECONDS);",
" }",
"}")
.doTest();
}
@Test
public void callingLongTimeUnitMethodWithDurationOverload_privateMethod() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" private void bar(long v, TimeUnit tu) {",
" }",
" private void bar(Duration d) {",
" }",
" public void foo() {",
" // BUG: Diagnostic contains: bar(Duration.ofSeconds(42L));",
" bar(42L, TimeUnit.SECONDS);",
" }",
"}")
.doTest();
}
@Test
public void callingLongTimeUnitMethodWithoutDurationOverload() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.concurrent.Future;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" public String foo(Future<String> future) throws Exception {",
" return future.get(42L, TimeUnit.SECONDS);",
" }",
"}")
.doTest();
}
@Test
public void callingJodaDurationMethodWithDurationOverload_privateMethod() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" private void bar(org.joda.time.Duration d) {",
" }",
" private void bar(Duration d) {",
" }",
" public void foo(org.joda.time.Duration jodaDuration) {",
" // BUG: Diagnostic contains: bar(Duration.ofMillis(jodaDuration.getMillis()));",
" bar(jodaDuration);",
" }",
"}")
.doTest();
}
@Test
public void callingJodaInstantMethodWithInstantOverload_privateMethod() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"public class TestClass {",
" private void bar(org.joda.time.Instant i) {",
" }",
" private void bar(Instant i) {",
" }",
" public void foo(org.joda.time.Instant jodaInstant) {",
" // BUG: Diagnostic contains: bar(Instant.ofEpochMilli(jodaInstant.getMillis()));",
" bar(jodaInstant);",
" }",
"}")
.doTest();
}
@Test
public void callingJodaDurationMethodWithDurationOverload_privateMethod_jodaDurationMillis() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" private void bar(org.joda.time.Duration d) {",
" }",
" private void bar(Duration d) {",
" }",
" public void foo() {",
" // BUG: Diagnostic contains: bar(Duration.ofMillis(42));",
" bar(org.joda.time.Duration.millis(42));",
" }",
"}")
.doTest();
}
@Test
public void callingJodaDurationMethodWithDurationOverload_privateMethod_jodaDurationCtor() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" private void bar(org.joda.time.Duration d) {",
" }",
" private void bar(Duration d) {",
" }",
" public void foo() {",
" // BUG: Diagnostic contains: bar(Duration.ofMillis(42));",
" bar(new org.joda.time.Duration(42));",
" }",
"}")
.doTest();
}
@Test
public void callingJodaInstantMethodWithInstantOverload_privateMethod_jodaInstantCtor() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"public class TestClass {",
" private void bar(org.joda.time.Instant i) {",
" }",
" private void bar(Instant i) {",
" }",
" public void foo() {",
" // BUG: Diagnostic contains: bar(Instant.ofEpochMilli(42));",
" bar(new org.joda.time.Instant(42));",
" }",
"}")
.doTest();
}
@Test
public void callingJodaDurationMethodWithDurationOverload_privateMethod_jodaSeconds() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" private void bar(org.joda.time.Duration d) {",
" }",
" private void bar(Duration d) {",
" }",
" public void foo() {",
" // BUG: Diagnostic contains: bar(Duration.ofSeconds(42));",
" bar(org.joda.time.Duration.standardSeconds(42));",
" }",
"}")
.doTest();
}
@Test
public void callingJodaDurationMethodWithoutDurationOverload() {
helper
.addSourceLines(
"TestClass.java",
"public class TestClass {",
" private void bar(org.joda.time.Duration d) {",
" }",
" public void foo(org.joda.time.Duration jodaDuration) {",
" bar(jodaDuration);",
" }",
"}")
.doTest();
}
@Test
public void callingJodaDurationMethodWithSupertypeJavaDurationOverload() {
helper
.addSourceLines(
"TestClass.java",
"public class TestClass extends SuperClass {",
" @Override",
" public void bar(java.time.Duration d) {",
" bar(org.joda.time.Duration.standardSeconds(d.getSeconds()));",
" }",
" public void bar(org.joda.time.Duration jodaDuration) {}",
"}",
"class SuperClass {",
" public void bar(java.time.Duration d) {}",
"}")
.doTest();
}
@Test
public void callingJodaReadableInstantMethodWithInstantOverload_privateMethod() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"public class TestClass {",
" private void bar(org.joda.time.ReadableInstant i) {",
" }",
" private void bar(Instant i) {",
" }",
" public void foo(org.joda.time.Instant jodaInstant) {",
" // BUG: Diagnostic contains: bar(Instant.ofEpochMilli(jodaInstant.getMillis()));",
" bar(jodaInstant);",
" }",
"}")
.doTest();
}
@Test
public void callingJodaReadableDurationMethodWithoutDurationOverload() {
helper
.addSourceLines(
"TestClass.java",
"public class TestClass {",
" private void bar(org.joda.time.ReadableDuration d) {",
" }",
" public void foo(org.joda.time.Duration jodaDuration) {",
" bar(jodaDuration);",
" }",
"}")
.doTest();
}
@Test
public void callingPrimitiveOverloadFromFieldInitializer() {
helper
.addSourceLines(
"TestClass.java",
"public class TestClass {",
" static {",
" // BUG: Diagnostic contains: call bar(Duration) instead",
" bar(42);",
" }",
" private static void bar(java.time.Duration d) {",
" }",
" private static void bar(long d) {",
" }",
"}")
.doTest();
}
@Test
public void callingNumericPrimitiveMethodWithDurationOverload() {
helper
.addSourceLines(
"TestClass.java",
"public class TestClass {",
" private void bar(java.time.Duration d) {",
" }",
" private void bar(long d) {",
" }",
" public void foo() {",
" // BUG: Diagnostic contains: call bar(Duration) instead",
" bar(42);",
" }",
"}")
.doTest();
}
@Test
public void callingNumericPrimitiveMethodWithInstantOverload() {
helper
.addSourceLines(
"TestClass.java",
"public class TestClass {",
" private void bar(java.time.Instant i) {",
" }",
" private void bar(long timestamp) {",
" }",
" public void foo() {",
" // BUG: Diagnostic contains: call bar(Instant) instead",
" bar(42);",
" }",
"}")
.doTest();
}
@Test
public void ignoredApisAreExcluded() {}
@Test
public void b138221392() {}
@Test
public void durationDividedBy() {
// See https://github.com/google/error-prone/issues/1431
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" public static Duration dividedBy(long divisor) {",
" return Duration.ZERO;",
" }",
" public static long dividedBy(Duration divisor) {",
" return 0L;",
" }",
" public void foo() {",
" dividedBy(42L);",
" dividedBy(Duration.ZERO);",
" }",
"}")
.doTest();
}
// TODO(kak): After upgrading to AssertJ 3.15, double-check that removing the AssertJ matcher from
// PreferJavaTimeOverload.IGNORED_APIS causes these tests to start failing.
@Test
public void assertJ() {
// https://github.com/google/error-prone/issues/1377
// https://github.com/google/error-prone/issues/1437
helper
.addSourceLines(
"TestClass.java",
"public class TestClass {",
" public void testAssertThat() {",
" org.assertj.core.api.Assertions.assertThat(1).isEqualTo(1);",
" }",
" public void testAssumeThat() {",
" org.assertj.core.api.Assumptions.assumeThat(1).isEqualTo(1);",
" }",
"}")
.doTest();
}
}
| 15,285
| 32.743929
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaTimeDefaultTimeZoneTest.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.time;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JavaTimeDefaultTimeZone}. */
@RunWith(JUnit4.class)
public class JavaTimeDefaultTimeZoneTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JavaTimeDefaultTimeZone.class, getClass())
.expectErrorMessage("REPLACEME", s -> s.contains("systemDefault()"));
@Test
public void clock() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.Clock;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" Clock clock = Clock.systemDefaultZone();",
" Clock clockWithZone = Clock.system(systemDefault());",
"}")
.doTest();
}
@Test
public void staticImportOfStaticMethod() {
BugCheckerRefactoringTestHelper.newInstance(
JavaTimeDefaultTimeZone.class, JavaTimeDefaultTimeZoneTest.class)
.addInputLines(
"in/TestClass.java",
"import static java.time.LocalDate.now;",
"",
"import java.time.LocalDate;",
"public class TestClass {",
" LocalDate date = now();",
"}")
.addOutputLines(
"out/TestClass.java",
"import static java.time.LocalDate.now;",
"import java.time.LocalDate;",
"import java.time.ZoneId;",
"public class TestClass {",
" LocalDate date = now(ZoneId.systemDefault());",
"}")
.doTest();
}
@Test
public void localDate() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.LocalDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" LocalDate now = LocalDate.now();",
" LocalDate nowWithZone = LocalDate.now(systemDefault());",
"}")
.doTest();
}
@Test
public void localTime() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.LocalTime;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" LocalTime now = LocalTime.now();",
" LocalTime nowWithZone = LocalTime.now(systemDefault());",
"}")
.doTest();
}
@Test
public void localDateTime() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.LocalDateTime;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" LocalDateTime now = LocalDateTime.now();",
" LocalDateTime nowWithZone = LocalDateTime.now(systemDefault());",
"}")
.doTest();
}
@Test
public void monthDay() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.MonthDay;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" MonthDay now = MonthDay.now();",
" MonthDay nowWithZone = MonthDay.now(systemDefault());",
"}")
.doTest();
}
@Test
public void offsetDateTime() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.OffsetDateTime;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" OffsetDateTime now = OffsetDateTime.now();",
" OffsetDateTime nowWithZone = OffsetDateTime.now(systemDefault());",
"}")
.doTest();
}
@Test
public void offsetTime() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.OffsetTime;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" OffsetTime now = OffsetTime.now();",
" OffsetTime nowWithZone = OffsetTime.now(systemDefault());",
"}")
.doTest();
}
@Test
public void year() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.Year;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" Year now = Year.now();",
" Year nowWithZone = Year.now(systemDefault());",
"}")
.doTest();
}
@Test
public void yearMonth() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.YearMonth;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" YearMonth now = YearMonth.now();",
" YearMonth nowWithZone = YearMonth.now(systemDefault());",
"}")
.doTest();
}
@Test
public void zonedDateTime() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.ZonedDateTime;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" ZonedDateTime now = ZonedDateTime.now();",
" ZonedDateTime nowWithZone = ZonedDateTime.now(systemDefault());",
"}")
.doTest();
}
@Test
public void japaneseDate() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.chrono.JapaneseDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" JapaneseDate now = JapaneseDate.now();",
" JapaneseDate nowWithZone = JapaneseDate.now(systemDefault());",
"}")
.doTest();
}
@Test
public void minguoDate() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.chrono.MinguoDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" MinguoDate now = MinguoDate.now();",
" MinguoDate nowWithZone = MinguoDate.now(systemDefault());",
"}")
.doTest();
}
@Test
public void hijrahDate() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.chrono.HijrahDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" HijrahDate now = HijrahDate.now();",
" HijrahDate nowWithZone = HijrahDate.now(systemDefault());",
"}")
.doTest();
}
@Test
public void thaiBuddhistDate() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.chrono.ThaiBuddhistDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" ThaiBuddhistDate now = ThaiBuddhistDate.now();",
" ThaiBuddhistDate nowWithZone = ThaiBuddhistDate.now(systemDefault());",
"}")
.doTest();
}
@Test
public void chronology() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.chrono.Chronology;",
"import java.time.chrono.ChronoLocalDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" ChronoLocalDate now = Chronology.of(\"ISO\").dateNow();",
" ChronoLocalDate nowWithZone = Chronology.of(\"ISO\").dateNow(systemDefault());",
"}")
.doTest();
}
@Test
public void hijrahChronology() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.chrono.HijrahChronology;",
"import java.time.chrono.HijrahDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" HijrahDate now = HijrahChronology.INSTANCE.dateNow();",
" HijrahDate nowWithZone = HijrahChronology.INSTANCE.dateNow(systemDefault());",
"}")
.doTest();
}
@Test
public void isoChronology() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.LocalDate;",
"import java.time.chrono.IsoChronology;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" LocalDate now = IsoChronology.INSTANCE.dateNow();",
" LocalDate nowWithZone = IsoChronology.INSTANCE.dateNow(systemDefault());",
"}")
.doTest();
}
@Test
public void japaneseChronology() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.chrono.JapaneseChronology;",
"import java.time.chrono.JapaneseDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" JapaneseDate now = JapaneseChronology.INSTANCE.dateNow();",
" JapaneseDate nowWithZone = JapaneseChronology.INSTANCE.dateNow(systemDefault());",
"}")
.doTest();
}
@Test
public void minguoChronology() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.chrono.MinguoChronology;",
"import java.time.chrono.MinguoDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" MinguoDate now = MinguoChronology.INSTANCE.dateNow();",
" MinguoDate nowWithZone = MinguoChronology.INSTANCE.dateNow(systemDefault());",
"}")
.doTest();
}
@Test
public void thaiBuddhistChronology() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.ZoneId.systemDefault;",
"import java.time.chrono.ThaiBuddhistChronology;",
"import java.time.chrono.ThaiBuddhistDate;",
"public class TestClass {",
" // BUG: Diagnostic matches: REPLACEME",
" ThaiBuddhistDate now = ThaiBuddhistChronology.INSTANCE.dateNow();",
" ThaiBuddhistDate nowWithZone = "
+ "ThaiBuddhistChronology.INSTANCE.dateNow(systemDefault());",
"}")
.doTest();
}
}
| 12,158
| 32.68144
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JodaPlusMinusLongTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JodaPlusMinusLong}. */
@RunWith(JUnit4.class)
public class JodaPlusMinusLongTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaPlusMinusLong.class, getClass());
// Instant
@Test
public void instantPlusMinusDuration() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"import org.joda.time.Instant;",
"public class TestClass {",
" private static final Instant PLUS = Instant.now().plus(Duration.millis(42));",
" private static final Instant MINUS = Instant.now().minus(Duration.millis(42));",
"}")
.doTest();
}
@Test
public void instantPlusMinusLong() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"import org.joda.time.Instant;",
"public class TestClass {",
" private static final Duration D = Duration.ZERO;",
" // BUG: Diagnostic contains: Instant.now().plus(Duration.millis(42L));",
" private static final Instant PLUS = Instant.now().plus(42L);",
" // BUG: Diagnostic contains: Instant.now().plus(D);",
" private static final Instant PLUS2 = Instant.now().plus(D.getMillis());",
" // BUG: Diagnostic contains: Instant.now().minus(Duration.millis(42L));",
" private static final Instant MINUS = Instant.now().minus(42L);",
" // BUG: Diagnostic contains: Instant.now().minus(D);",
" private static final Instant MINUS2 = Instant.now().minus(D.getMillis());",
"}")
.doTest();
}
@Test
public void instantPlusMinusLong_insideJodaTime() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final Instant PLUS = Instant.now().plus(42L);",
" private static final Instant MINUS = Instant.now().minus(42L);",
"}")
.doTest();
}
// Duration
@Test
public void durationPlusMinusDuration() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"import org.joda.time.Instant;",
"public class TestClass {",
" private static final Duration PLUS = Duration.ZERO.plus(Duration.millis(42));",
" private static final Duration MINUS = Duration.ZERO.minus(Duration.millis(42));",
"}")
.doTest();
}
@Test
public void durationPlusMinusLong() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration D = Duration.ZERO;",
" // BUG: Diagnostic contains: Duration.ZERO.plus(Duration.millis(42L));",
" private static final Duration PLUS = Duration.ZERO.plus(42L);",
" // BUG: Diagnostic contains: Duration.ZERO.plus(D);",
" private static final Duration PLUS2 = Duration.ZERO.plus(D.getMillis());",
" // BUG: Diagnostic contains: Duration.ZERO.minus(Duration.millis(42L));",
" private static final Duration MINUS = Duration.ZERO.minus(42L);",
" // BUG: Diagnostic contains: Duration.ZERO.minus(D);",
" private static final Duration MINUS2 = Duration.ZERO.minus(D.getMillis());",
"}")
.doTest();
}
@Test
public void durationPlusMinusLong_insideJodaTime() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final Duration PLUS = Duration.ZERO.plus(42L);",
" private static final Duration MINUS = Duration.ZERO.minus(42L);",
"}")
.doTest();
}
// DateTime
@Test
public void dateTimePlusMinusDuration() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateTime;",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final DateTime PLUS = DateTime.now().plus(Duration.millis(42));",
" private static final DateTime MINUS = DateTime.now().minus(Duration.millis(42));",
"}")
.doTest();
}
@Test
public void dateTimePlusMinusLong() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateTime;",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration D = Duration.ZERO;",
" // BUG: Diagnostic contains: DateTime.now().plus(Duration.millis(42L));",
" private static final DateTime PLUS = DateTime.now().plus(42L);",
" // BUG: Diagnostic contains: DateTime.now().plus(D);",
" private static final DateTime PLUS2 = DateTime.now().plus(D.getMillis());",
" // BUG: Diagnostic contains: DateTime.now().minus(Duration.millis(42L));",
" private static final DateTime MINUS = DateTime.now().minus(42L);",
" // BUG: Diagnostic contains: DateTime.now().minus(D);",
" private static final DateTime MINUS2 = DateTime.now().minus(D.getMillis());",
"}")
.doTest();
}
@Test
public void dateTimePlusMinusLong_insideJodaTime() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final DateTime PLUS = DateTime.now().plus(42L);",
" private static final DateTime MINUS = DateTime.now().minus(42L);",
"}")
.doTest();
}
// DateMidnight
@Test
public void dateMidnightPlusMinusDuration() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateMidnight;",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final DateMidnight PLUS = ",
" DateMidnight.now().plus(Duration.millis(42));",
" private static final DateMidnight MINUS = ",
" DateMidnight.now().minus(Duration.millis(42));",
"}")
.doTest();
}
@Test
public void dateMidnightPlusMinusLong() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateMidnight;",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration D = Duration.ZERO;",
" // BUG: Diagnostic contains: DateMidnight.now().plus(Duration.millis(42L));",
" private static final DateMidnight PLUS = DateMidnight.now().plus(42L);",
" // BUG: Diagnostic contains: DateMidnight.now().plus(D);",
" private static final DateMidnight PLUS2 = DateMidnight.now().plus(D.getMillis());",
" // BUG: Diagnostic contains: DateMidnight.now().minus(Duration.millis(42L));",
" private static final DateMidnight MINUS = DateMidnight.now().minus(42L);",
" // BUG: Diagnostic contains: DateMidnight.now().minus(D);",
" private static final DateMidnight MINUS2 = DateMidnight.now().minus(D.getMillis());",
"}")
.doTest();
}
@Test
public void dateMidnightPlusMinusLong_insideJodaTime() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final DateMidnight PLUS = DateMidnight.now().plus(42L);",
" private static final DateMidnight MINUS = DateMidnight.now().minus(42L);",
"}")
.doTest();
}
}
| 8,809
| 37.304348
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaLocalTimeGetNanoTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JavaLocalTimeGetNano}. */
@RunWith(JUnit4.class)
public final class JavaLocalTimeGetNanoTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JavaLocalTimeGetNano.class, getClass());
@Test
public void getSecondWithGetNano() {
compilationHelper
.addSourceLines(
"Test.java",
"package test;",
"import java.time.LocalTime;",
"public class Test {",
" public static void foo(LocalTime localTime) {",
" long seconds = localTime.getSecond();",
" int nanos = localTime.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getNanoWithNoGetSeconds() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.time.LocalTime;",
"public class Test {",
" public static int foo(LocalTime localTime) {",
" // BUG: Diagnostic contains:",
" return localTime.getNano();",
" }",
"}")
.doTest();
}
}
| 1,931
| 31.2
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/TimeUnitMismatchTest.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.time;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.errorprone.bugpatterns.time.TimeUnitMismatch.unitSuggestedByName;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
@RunWith(JUnit4.class)
public class TimeUnitMismatchTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(TimeUnitMismatch.class, getClass());
@Test
public void testPositiveCase() {
compilationHelper.addSourceFile("TimeUnitMismatchPositiveCases.java").doTest();
}
@Test
public void testNegativeCase() {
compilationHelper.addSourceFile("TimeUnitMismatchNegativeCases.java").doTest();
}
@Test
public void testUnitSuggestedByName() {
assertSeconds("sleepSec", "deadlineSeconds", "secondsTimeout", "msToS");
assertUnknown(
"second",
"getSecond",
"SECOND",
"secondDeadline",
"twoSeconds",
"THIRTY_SECONDS",
"fromSeconds",
"x",
"millisMicros");
assertMillis(
"millis",
"MILLIS",
"someMillis",
"millisecs",
"timeoutMilli",
"valueInMills",
"mSec",
"deadlineMSec",
"milliSecond",
"milliSeconds",
"FOO_MILLI_SECONDS",
"dateMS",
"dateMs",
"dateMsec",
"msRemaining");
assertMicros("micro", "us");
assertNanos("nano", "secondsPart");
}
private static void assertUnknown(String... names) {
for (String name : names) {
assertWithMessage("unit for %s", name).that(unitSuggestedByName(name)).isNull();
}
}
private static void assertSeconds(String... names) {
for (String name : names) {
assertWithMessage("unit for %s", name).that(unitSuggestedByName(name)).isEqualTo(SECONDS);
}
}
private static void assertMillis(String... names) {
for (String name : names) {
assertWithMessage("unit for %s", name)
.that(unitSuggestedByName(name))
.isEqualTo(MILLISECONDS);
}
}
private static void assertMicros(String... names) {
for (String name : names) {
assertWithMessage("unit for %s", name)
.that(unitSuggestedByName(name))
.isEqualTo(MICROSECONDS);
}
}
private static void assertNanos(String... names) {
for (String name : names) {
assertWithMessage("unit for %s", name).that(unitSuggestedByName(name)).isEqualTo(NANOSECONDS);
}
}
}
| 3,470
| 28.922414
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JodaConstructorsTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JodaConstructors}. */
@RunWith(JUnit4.class)
public class JodaConstructorsTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaConstructors.class, getClass());
@Test
public void durationStaticFactories() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration ONE_MILLI = Duration.millis(1);",
" private static final Duration ONE_SEC = Duration.standardSeconds(1);",
" private static final Duration ONE_MIN = Duration.standardMinutes(1);",
" private static final Duration ONE_HOUR = Duration.standardHours(1);",
" private static final Duration ONE_DAY = Duration.standardDays(1);",
"}")
.doTest();
}
@Test
public void durationConstructorObject() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration ONE_MILLI = new Duration(\"1\");",
"}")
.doTest();
}
@Test
public void durationConstructorIntInt() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration INTERVAL = new Duration(42, 48);",
"}")
.doTest();
}
@Test
public void durationConstructorIntLong() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration INTERVAL = new Duration(42, 48L);",
"}")
.doTest();
}
@Test
public void durationConstructorLongInt() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration INTERVAL = new Duration(42L, 48);",
"}")
.doTest();
}
@Test
public void durationConstructorLongLong() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration INTERVAL = new Duration(42L, 48L);",
"}")
.doTest();
}
@Test
public void durationConstructorIntPrimitive() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" // BUG: Diagnostic contains: Duration ONE_MILLI = Duration.millis(1);",
" private static final Duration ONE_MILLI = new Duration(1);",
"}")
.doTest();
}
@Test
public void durationConstructorInteger() {
// TODO(kak): This really should be an error too :(
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration ONE_MILLI = new Duration(Integer.valueOf(42));",
"}")
.doTest();
}
@Test
public void durationConstructorLongPrimitive() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" // BUG: Diagnostic contains: Duration ONE_MILLI = Duration.millis(1L);",
" private static final Duration ONE_MILLI = new Duration(1L);",
"}")
.doTest();
}
@Test
public void durationConstructorLongPrimitiveInsideJoda() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final Duration ONE_MILLI = new Duration(1L);",
"}")
.doTest();
}
@Test
public void durationConstructorLongPrimitiveNoImport() {
helper
.addSourceLines(
"TestClass.java",
"public class TestClass {",
" private static final org.joda.time.Duration ONE_MILLI = ",
" // BUG: Diagnostic contains: Did you mean 'org.joda.time.Duration.millis(1L);'",
" new org.joda.time.Duration(1L);",
"}")
.doTest();
}
@Test
public void durationConstructorLong() {
// TODO(kak): This really should be an error too :(
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration ONE_MILLI = new Duration(Long.valueOf(1L));",
"}")
.doTest();
}
@Test
public void instantConstructor() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Instant;",
"public class TestClass {",
" // BUG: Diagnostic contains: Instant I1 = Instant.now();",
" private static final Instant I1 = new Instant();",
" // BUG: Diagnostic contains: Instant I2 = Instant.ofEpochMilli(42);",
" private static final Instant I2 = new Instant(42);",
"}")
.doTest();
}
@Test
public void instantConstructor_fqcn() {
helper
.addSourceLines(
"TestClass.java",
"public class TestClass {",
" // BUG: Diagnostic contains: I1 = org.joda.time.Instant.now();",
" private static final org.joda.time.Instant I1 = new org.joda.time.Instant();",
" // BUG: Diagnostic contains: I2 = org.joda.time.Instant.ofEpochMilli(42);",
" private static final org.joda.time.Instant I2 = new org.joda.time.Instant(42);",
"}")
.doTest();
}
@Test
public void dateTimeConstructors() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Chronology;",
"import org.joda.time.chrono.GregorianChronology;",
"import org.joda.time.DateTime;",
"import org.joda.time.DateTimeZone;",
"public class TestClass {",
" private static final DateTimeZone NYC = DateTimeZone.forID(\"America/New_York\");",
" private static final Chronology GREG = GregorianChronology.getInstance();",
" // BUG: Diagnostic contains: DateTime NOW = DateTime.now();",
" private static final DateTime NOW = new DateTime();",
" // BUG: Diagnostic contains: DateTime NOW_NYC = DateTime.now(NYC);",
" private static final DateTime NOW_NYC = new DateTime(NYC);",
" // BUG: Diagnostic contains: DateTime NOW_GREG = DateTime.now(GREG);",
" private static final DateTime NOW_GREG = new DateTime(GREG);",
"}")
.doTest();
}
}
| 7,861
| 32.742489
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaDurationWithSecondsTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JavaDurationWithSeconds}. */
@RunWith(JUnit4.class)
public class JavaDurationWithSecondsTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JavaDurationWithSeconds.class, getClass());
@Test
public void durationWithSeconds() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" // BUG: Diagnostic contains: Duration.ofSeconds(42, Duration.ZERO.getNano());",
" private static final Duration DURATION = Duration.ZERO.withSeconds(42);",
"}")
.doTest();
}
@Test
public void durationWithSecondsNamedVariable() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" private static final Duration DURATION1 = Duration.ZERO;",
" // BUG: Diagnostic contains: Duration.ofSeconds(44, DURATION1.getNano());",
" private static final Duration DURATION2 = DURATION1.withSeconds(44);",
"}")
.doTest();
}
@Test
public void durationWithSecondsPrimitiveImportClash() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final java.time.Duration DURATION = ",
" // BUG: Diagnostic contains: "
+ "java.time.Duration.ofSeconds(42, java.time.Duration.ZERO.getNano());",
" java.time.Duration.ZERO.withSeconds(42);",
"}")
.doTest();
}
}
| 2,496
| 34.169014
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JodaNewPeriodTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JodaNewPeriod}. */
@RunWith(JUnit4.class)
public final class JodaNewPeriodTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaNewPeriod.class, getClass());
@Test
public void positive() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Instant;",
"import org.joda.time.LocalDate;",
"import org.joda.time.Period;",
"public class TestClass {",
" // BUG: Diagnostic contains: new Duration(10, 20).getStandardDays()",
" private static final int DAYS = new Period(10, 20).getDays();",
" int days(LocalDate a, LocalDate b) {",
" // BUG: Diagnostic contains: Days.daysBetween(a, b).getDays()",
" return new Period(a, b).getDays();",
" }",
"}")
.doTest();
}
@Test
public void negative() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Period;",
"import org.joda.time.Instant;",
"public class TestClass {",
" private static final Period period = new Period(10, 20);",
" private static final int DAYS = period.getDays();",
"}")
.doTest();
}
}
| 2,126
| 33.306452
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JodaTimeConverterManagerTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JodaTimeConverterManager}. */
@RunWith(JUnit4.class)
public final class JodaTimeConverterManagerTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaTimeConverterManager.class, getClass());
@Test
public void converterManager() {
helper
.addSourceLines(
"Test.java",
"import org.joda.time.convert.ConverterManager;",
"class Test {",
" // BUG: Diagnostic contains: JodaTimeConverterManager",
" ConverterManager cm = ConverterManager.getInstance();",
"}")
.doTest();
}
@Test
public void withinJoda() {
helper
.addSourceLines(
"Test.java",
"package org.joda.time;",
"import org.joda.time.convert.ConverterManager;",
"class Test {",
" ConverterManager cm = ConverterManager.getInstance();",
"}")
.doTest();
}
}
| 1,772
| 31.236364
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/InstantTemporalUnitTest.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.time;
import static com.google.common.truth.Truth.assertThat;
import com.google.errorprone.CompilationTestHelper;
import java.time.temporal.ChronoUnit;
import java.util.EnumSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link InstantTemporalUnit}. */
@RunWith(JUnit4.class)
public final class InstantTemporalUnitTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(InstantTemporalUnit.class, getClass());
@Test
public void invalidTemporalUnitsMatchesEnumeratedList() throws Exception {
// This list comes from the Instant javadocs, but the checker builds the list based on the
// definition in Instant.isSupported(): unit.isTimeBased() || unit == DAYS;
assertThat(InstantTemporalUnit.INVALID_TEMPORAL_UNITS)
.containsExactlyElementsIn(
EnumSet.complementOf(
EnumSet.of(
ChronoUnit.NANOS,
ChronoUnit.MICROS,
ChronoUnit.MILLIS,
ChronoUnit.SECONDS,
ChronoUnit.MINUTES,
ChronoUnit.HOURS,
ChronoUnit.HALF_DAYS,
ChronoUnit.DAYS)));
}
@Test
public void instantPlus_good() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" private static final Instant I0 = Instant.EPOCH.plus(1, ChronoUnit.DAYS);",
" private static final Instant I1 = Instant.EPOCH.plus(1, ChronoUnit.HALF_DAYS);",
" private static final Instant I2 = Instant.EPOCH.plus(1, ChronoUnit.HOURS);",
" private static final Instant I3 = Instant.EPOCH.plus(1, ChronoUnit.MICROS);",
" private static final Instant I4 = Instant.EPOCH.plus(1, ChronoUnit.MILLIS);",
" private static final Instant I5 = Instant.EPOCH.plus(1, ChronoUnit.MINUTES);",
" private static final Instant I6 = Instant.EPOCH.plus(1, ChronoUnit.NANOS);",
" private static final Instant I7 = Instant.EPOCH.plus(1, ChronoUnit.SECONDS);",
"}")
.doTest();
}
@Test
public void instantPlus_bad() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I0 = Instant.EPOCH.plus(1, ChronoUnit.CENTURIES);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I1 = Instant.EPOCH.plus(1, ChronoUnit.DECADES);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I2 = Instant.EPOCH.plus(1, ChronoUnit.ERAS);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I3 = Instant.EPOCH.plus(1, ChronoUnit.FOREVER);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I4 = Instant.EPOCH.plus(1, ChronoUnit.MILLENNIA);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I5 = Instant.EPOCH.plus(1, ChronoUnit.MONTHS);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I6 = Instant.EPOCH.plus(1, ChronoUnit.WEEKS);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I7 = Instant.EPOCH.plus(1, ChronoUnit.YEARS);",
"}")
.doTest();
}
@Test
public void instantMinus_good() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" private static final Instant I0 = Instant.EPOCH.minus(1, ChronoUnit.DAYS);",
" private static final Instant I1 = Instant.EPOCH.minus(1, ChronoUnit.HALF_DAYS);",
" private static final Instant I2 = Instant.EPOCH.minus(1, ChronoUnit.HOURS);",
" private static final Instant I3 = Instant.EPOCH.minus(1, ChronoUnit.MICROS);",
" private static final Instant I4 = Instant.EPOCH.minus(1, ChronoUnit.MILLIS);",
" private static final Instant I5 = Instant.EPOCH.minus(1, ChronoUnit.MINUTES);",
" private static final Instant I6 = Instant.EPOCH.minus(1, ChronoUnit.NANOS);",
" private static final Instant I7 = Instant.EPOCH.minus(1, ChronoUnit.SECONDS);",
"}")
.doTest();
}
@Test
public void instantMinus_bad() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Instant;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I0 = Instant.EPOCH.minus(1, ChronoUnit.CENTURIES);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I1 = Instant.EPOCH.minus(1, ChronoUnit.DECADES);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I2 = Instant.EPOCH.minus(1, ChronoUnit.ERAS);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I3 = Instant.EPOCH.minus(1, ChronoUnit.FOREVER);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I4 = Instant.EPOCH.minus(1, ChronoUnit.MILLENNIA);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I5 = Instant.EPOCH.minus(1, ChronoUnit.MONTHS);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I6 = Instant.EPOCH.minus(1, ChronoUnit.WEEKS);",
" // BUG: Diagnostic contains: InstantTemporalUnit",
" private static final Instant I7 = Instant.EPOCH.minus(1, ChronoUnit.YEARS);",
"}")
.doTest();
}
}
| 7,095
| 47.272109
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/DurationGetTemporalUnitTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link DurationGetTemporalUnit}. */
@RunWith(JUnit4.class)
public class DurationGetTemporalUnitTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(DurationGetTemporalUnit.class, getClass());
@Test
public void durationGetTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" private static final long seconds = Duration.ZERO.get(ChronoUnit.SECONDS);",
" private static final long nanos = Duration.ZERO.get(ChronoUnit.NANOS);",
" // BUG: Diagnostic contains: Duration.ZERO.toDays();",
" private static final long days = Duration.ZERO.get(ChronoUnit.DAYS);",
"}")
.doTest();
}
@Test
public void durationGetTemporalUnitStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoUnit.MILLIS;",
"import static java.time.temporal.ChronoUnit.NANOS;",
"import static java.time.temporal.ChronoUnit.SECONDS;",
"import java.time.Duration;",
"public class TestClass {",
" private static final long seconds = Duration.ZERO.get(SECONDS);",
" private static final long nanos = Duration.ZERO.get(NANOS);",
" // BUG: Diagnostic contains: Duration.ZERO.toMillis();",
" private static final long days = Duration.ZERO.get(MILLIS);",
"}")
.doTest();
}
@Test
public void durationGetWithRandomTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoUnit.DAYS;",
"import static java.time.temporal.ChronoUnit.SECONDS;",
"import java.time.Duration;",
"import java.time.temporal.TemporalUnit;",
"import java.util.Random;",
"public class TestClass {",
" private final TemporalUnit random = new Random().nextBoolean() ? DAYS : SECONDS;",
// Since we don't know at compile time what 'random' is, we can't flag this
" private final long mightWork = Duration.ZERO.get(random);",
"}")
.doTest();
}
@Test
public void durationGetWithAliasedTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoUnit.DAYS;",
"import java.time.Duration;",
"import java.time.temporal.Temporal;",
"import java.time.temporal.TemporalUnit;",
"public class TestClass {",
" private static final TemporalUnit SECONDS = DAYS;",
// This really should be flagged, but isn't :(
" private static final long seconds = Duration.ZERO.get(SECONDS);",
"}")
.doTest();
}
@Test
public void durationGetWithCustomTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.temporal.Temporal;",
"import java.time.temporal.TemporalUnit;",
"public class TestClass {",
" private static class BadTemporalUnit implements TemporalUnit {",
" @Override",
" public long between(Temporal t1, Temporal t2) {",
" throw new AssertionError();",
" }",
" @Override",
" public <R extends Temporal> R addTo(R temporal, long amount) {",
" throw new AssertionError();",
" }",
" @Override",
" public boolean isTimeBased() {",
" throw new AssertionError();",
" }",
" @Override",
" public boolean isDateBased() {",
" throw new AssertionError();",
" }",
" @Override",
" public boolean isDurationEstimated() {",
" throw new AssertionError();",
" }",
" @Override",
" public Duration getDuration() {",
" throw new AssertionError();",
" }",
" }",
" private static final TemporalUnit MINUTES = new BadTemporalUnit();",
" private static final TemporalUnit SECONDS = new BadTemporalUnit();",
// This really should be flagged, but isn't :(
" private static final long seconds = Duration.ZERO.get(SECONDS);",
" // BUG: Diagnostic contains: Duration.ZERO.toMinutes();",
" private static final long days = Duration.ZERO.get(MINUTES);",
"}")
.doTest();
}
}
| 5,666
| 38.629371
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JodaToSelfTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JodaToSelf}. */
@RunWith(JUnit4.class)
public class JodaToSelfTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaToSelf.class, getClass());
@Test
public void durationWithSeconds() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" // BUG: Diagnostic contains: private static final Duration DUR = Duration.ZERO;",
" private static final Duration DUR = Duration.ZERO.toDuration();",
"}")
.doTest();
}
@Test
public void durationWithSecondsNamedVariable() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration DURATION1 = Duration.ZERO;",
" // BUG: Diagnostic contains: private static final Duration DURATION2 = DURATION1;",
" private static final Duration DURATION2 = DURATION1.toDuration();",
"}")
.doTest();
}
@Test
public void durationWithSecondsInsideJodaTime() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final Duration DURATION = Duration.ZERO.toDuration();",
"}")
.doTest();
}
@Test
public void durationWithSecondsPrimitiveImportClash() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final org.joda.time.Duration DURATION = ",
" // BUG: Diagnostic contains: org.joda.time.Duration.ZERO;",
" org.joda.time.Duration.ZERO.toDuration();",
"}")
.doTest();
}
@Test
public void dateTimeConstructor() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateTime;",
"public class TestClass {",
" DateTime test(DateTime dt) {",
" // BUG: Diagnostic contains: return dt;",
" return new DateTime(dt);",
" }",
"}")
.doTest();
}
@Test
public void dateTimeConstructorInstant() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateTime;",
"import org.joda.time.Instant;",
"public class TestClass {",
" DateTime test(Instant i) {",
" return new DateTime(i);",
" }",
"}")
.doTest();
}
}
| 3,539
| 30.607143
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaDurationWithNanosTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JavaDurationWithNanos}. */
@RunWith(JUnit4.class)
public class JavaDurationWithNanosTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JavaDurationWithNanos.class, getClass());
@Test
public void durationWithNanos() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" // BUG: Diagnostic contains: Duration.ofSeconds(Duration.ZERO.getSeconds(), 42);",
" private static final Duration DURATION = Duration.ZERO.withNanos(42);",
"}")
.doTest();
}
@Test
public void durationWithNanosNamedVariable() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" private static final Duration DURATION1 = Duration.ZERO;",
" // BUG: Diagnostic contains: Duration.ofSeconds(DURATION1.getSeconds(), 44);",
" private static final Duration DURATION2 = DURATION1.withNanos(44);",
"}")
.doTest();
}
@Test
public void durationWithNanosPrimitiveImportClash() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final java.time.Duration DURATION = ",
" // BUG: Diagnostic contains: "
+ "java.time.Duration.ofSeconds(java.time.Duration.ZERO.getSeconds(), 42);",
" java.time.Duration.ZERO.withNanos(42);",
"}")
.doTest();
}
}
| 2,487
| 34.042254
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/PeriodTimeMathTest.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.time;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.Period;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link PeriodTimeMath} */
@RunWith(JUnit4.class)
public class PeriodTimeMathTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(PeriodTimeMath.class, getClass());
@SuppressWarnings("PeriodTimeMath")
@Test
public void failures() {
Period p = Period.ZERO;
assertThrows(DateTimeException.class, () -> p.plus(Duration.ZERO));
assertThrows(DateTimeException.class, () -> p.minus(Duration.ZERO));
assertThrows(DateTimeException.class, () -> p.plus(Duration.ofHours(48)));
assertThrows(DateTimeException.class, () -> p.minus(Duration.ofHours(48)));
assertThrows(DateTimeException.class, () -> p.plus(Duration.ofDays(2)));
}
@Test
public void periodMath() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.Period;",
"import java.time.temporal.TemporalAmount;",
"public class TestClass {",
" // BUG: Diagnostic contains: PeriodTimeMath",
" private final Period zero = Period.ZERO.plus(Duration.ZERO);",
" private final Period oneDay = Period.ZERO.plus(Period.ofDays(1));",
" // BUG: Diagnostic contains: PeriodTimeMath",
" private final Period twoDays = Period.ZERO.minus(Duration.ZERO);",
" private final TemporalAmount temporalAmount = Duration.ofDays(3);",
// don't trigger when it is not statically known to be a Duration/Period
" private final Period threeDays = Period.ZERO.plus(temporalAmount);",
"}")
.doTest();
}
@Test
public void strictPeriodMath() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.Period;",
"import java.time.temporal.TemporalAmount;",
"public class TestClass {",
" // BUG: Diagnostic contains: PeriodTimeMath",
" private final Period zero = Period.ZERO.plus(Duration.ZERO);",
" private final Period oneDay = Period.ZERO.plus(Period.ofDays(1));",
" // BUG: Diagnostic contains: PeriodTimeMath",
" private final Period twoDays = Period.ZERO.minus(Duration.ZERO);",
" private final TemporalAmount temporalAmount = Duration.ofDays(3);",
// In strict mode, trigger when it's not known to be a Period
" // BUG: Diagnostic contains: PeriodTimeMath",
" private final Period threeDays = Period.ZERO.plus(temporalAmount);",
"}")
.setArgs(ImmutableList.of("-XepOpt:PeriodTimeMath:RequireStaticPeriodArgument"))
.doTest();
}
}
| 3,719
| 40.333333
| 88
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/DurationFromTest.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.time;
import static org.junit.Assert.assertThrows;
import com.google.errorprone.CompilationTestHelper;
import java.time.Duration;
import java.time.Period;
import java.time.temporal.TemporalAmount;
import java.time.temporal.UnsupportedTemporalTypeException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link DurationFrom}. */
@RunWith(JUnit4.class)
public class DurationFromTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(DurationFrom.class, getClass());
@SuppressWarnings("DurationFrom")
@Test
public void failures() {
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(Period.ZERO));
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(Period.ofDays(1)));
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(Period.ofDays(-1)));
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(Period.ofWeeks(1)));
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(Period.ofWeeks(-1)));
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(Period.ofMonths(1)));
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(Period.ofMonths(-1)));
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(Period.ofYears(1)));
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(Period.ofYears(-1)));
TemporalAmount temporalAmount = Period.ofDays(3);
assertThrows(UnsupportedTemporalTypeException.class, () -> Duration.from(temporalAmount));
}
@Test
public void durationFrom() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.Period;",
"import java.time.temporal.TemporalAmount;",
"public class TestClass {",
" // BUG: Diagnostic contains: DurationFrom",
" private final Duration oneDay = Duration.from(Period.ofDays(1));",
" // BUG: Diagnostic contains: Duration.ofDays(2)",
" private final Duration twoDays = Duration.from(Duration.ofDays(2));",
" private final TemporalAmount temporalAmount = Duration.ofDays(3);",
// don't trigger when it is not statically known to be a Duration/Period
" private final Duration threeDays = Duration.from(temporalAmount);",
"}")
.doTest();
}
}
| 3,188
| 43.291667
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/DateCheckerTest.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.time;
import static com.google.common.truth.Truth.assertThat;
import static java.time.Month.DECEMBER;
import static java.time.Month.FEBRUARY;
import static java.time.Month.JANUARY;
import static java.time.Month.JUNE;
import static java.time.Month.MAY;
import com.google.errorprone.CompilationTestHelper;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link DateChecker}. */
@RunWith(JUnit4.class)
@SuppressWarnings({"DateChecker", "JdkObsolete", "deprecation"})
public class DateCheckerTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(DateChecker.class, getClass());
@Test
public void badBehavior() {
assertThat(toLocalDate(2020, 6, 10)).isEqualTo(LocalDate.of(2020 + 1900, 6 + 1, 10));
assertThat(toLocalDate(120, 0, 20)).isEqualTo(LocalDate.of(2020, JANUARY, 20));
assertThat(toLocalDate(120, 12, 20)).isEqualTo(LocalDate.of(2021, JANUARY, 20));
assertThat(toLocalDate(120, 13, 20)).isEqualTo(LocalDate.of(2021, FEBRUARY, 20));
assertThat(toLocalDate(120, -1, 20)).isEqualTo(LocalDate.of(2019, DECEMBER, 20));
assertThat(toLocalDate(121, -7, 20)).isEqualTo(LocalDate.of(2020, JUNE, 20));
assertThat(toLocalDate(121, -7, 0)).isEqualTo(LocalDate.of(2020, MAY, 31));
assertThat(toLocalDate(121, -7, -1)).isEqualTo(LocalDate.of(2020, MAY, 30));
LocalDateTime expected = LocalDateTime.of(2020, JUNE, 20, 16, 36, 13);
// normal (well, for some definition of "normal")
assertThat(toLocalDateTime(120, 5, 20, 16, 36, 13)).isEqualTo(expected);
// hours = 40 (wrap around)
assertThat(toLocalDateTime(120, 5, 19, 40, 36, 13)).isEqualTo(expected);
// minutes = 96 (wrap around)
assertThat(toLocalDateTime(120, 5, 20, 15, 96, 13)).isEqualTo(expected);
// seconds = 73 (wrap around)
assertThat(toLocalDateTime(120, 5, 20, 16, 35, 73)).isEqualTo(expected);
}
private static LocalDate toLocalDate(int year, int month, int day) {
return new Date(year, month, day).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
private static LocalDateTime toLocalDateTime(
int year, int month, int day, int hour, int minute, int second) {
return new Date(year, month, day, hour, minute, second)
.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
@Test
public void constructor_good() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.Calendar.JULY;",
"import java.util.Date;",
"public class TestClass {",
" Date good = new Date(120, JULY, 10);",
"}")
.doTest();
}
@Test
public void constructor_nonConstantMonth() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" // BUG: Diagnostic contains: Use Calendar.MAY instead of 4 to represent the month.",
" Date good = new Date(120, 4, 10);",
"}")
.doTest();
}
@Test
public void constructor_constants() {
// TODO(kak): We may want to consider warning on this case as well.
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" private static final int MAY = 4;",
" Date good = new Date(120, MAY, 31);",
"}")
.doTest();
}
@Test
public void constructor_nonConstants() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" Date good = new Date(getYear(), getMonth(), getDay());",
" int getYear() { return 120; }",
" int getMonth() { return 0; }",
" int getDay() { return 1; }",
"}")
.doTest();
}
@Test
public void constructor_allBad() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" // BUG: Diagnostic contains: "
+ "The 1900-based year value (2020) is out of bounds [1..150]. "
+ "The 0-based month value (13) is out of bounds [0..11].",
" Date bad1 = new Date(2020, 13, 31);",
" // BUG: Diagnostic contains: "
+ "The 1900-based year value (2020) is out of bounds [1..150]. "
+ "The 0-based month value (13) is out of bounds [0..11]. "
+ "The hours value (-2) is out of bounds [0..23]. "
+ "The minutes value (61) is out of bounds [0..59].",
" Date bad2 = new Date(2020, 13, 31, -2, 61);",
" // BUG: Diagnostic contains: "
+ "The 1900-based year value (2020) is out of bounds [1..150]. "
+ "The 0-based month value (13) is out of bounds [0..11]. "
+ "The hours value (-2) is out of bounds [0..23]. "
+ "The minutes value (61) is out of bounds [0..59]. "
+ "The seconds value (75) is out of bounds [0..59].",
" Date bad3 = new Date(2020, 13, 31, -2, 61, 75);",
"}")
.doTest();
}
@Test
public void constructor_badYear() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.Calendar.JULY;",
"import java.util.Date;",
"public class TestClass {",
" // BUG: Diagnostic contains: "
+ "The 1900-based year value (2020) is out of bounds [1..150].",
" Date bad = new Date(2020, JULY, 10);",
"}")
.doTest();
}
@Test
public void constructor_badMonth() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" // BUG: Diagnostic contains: The 0-based month value (12) is out of bounds [0..11].",
" Date bad1 = new Date(120, 12, 10);",
" // BUG: Diagnostic contains: The 0-based month value (13) is out of bounds [0..11].",
" Date bad2 = new Date(120, 13, 10);",
" // BUG: Diagnostic contains: The 0-based month value (-1) is out of bounds [0..11].",
" Date bad3 = new Date(120, -1, 10);",
" // BUG: Diagnostic contains: The 0-based month value (-13) is out of bounds"
+ " [0..11].",
" Date bad4 = new Date(120, -13, 10);",
" // BUG: Diagnostic contains: Use Calendar.MAY instead of 4 to represent the month.",
" Date bad5 = new Date(120, 4, 10);",
"}")
.doTest();
}
@Test
public void constructor_badDay() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.Calendar.JULY;",
"import java.util.Date;",
"public class TestClass {",
" // BUG: Diagnostic contains: The day value (32) is out of bounds [1..31].",
" Date bad1 = new Date(120, JULY, 32);",
" // BUG: Diagnostic contains: The day value (0) is out of bounds [1..31].",
" Date bad2 = new Date(120, JULY, 0);",
" // BUG: Diagnostic contains: The day value (-32) is out of bounds [1..31].",
" Date bad3 = new Date(120, JULY, -32);",
"}")
.doTest();
}
@Test
public void setters_good() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.Calendar.*;",
"import java.util.Date;",
"public class TestClass {",
" public void foo(Date date) {",
" date.setYear(1);",
" date.setYear(120);",
" date.setYear(150);",
" date.setMonth(JANUARY);",
" date.setMonth(FEBRUARY);",
" date.setMonth(MARCH);",
" date.setMonth(APRIL);",
" date.setMonth(MAY);",
" date.setMonth(JUNE);",
" date.setMonth(JULY);",
" date.setMonth(AUGUST);",
" date.setMonth(SEPTEMBER);",
" date.setMonth(OCTOBER);",
" date.setMonth(NOVEMBER);",
" date.setMonth(DECEMBER);",
" date.setDate(1);",
" date.setDate(15);",
" date.setDate(31);",
" date.setHours(0);",
" date.setHours(12);",
" date.setHours(23);",
" date.setMinutes(0);",
" date.setMinutes(30);",
" date.setMinutes(59);",
" date.setSeconds(0);",
" date.setSeconds(30);",
" date.setSeconds(59);",
" }",
"}")
.doTest();
}
@Test
public void setters_badYears() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" public void foo(Date date) {",
" // BUG: Diagnostic contains: "
+ "The 1900-based year value (0) is out of bounds [1..150].",
" date.setYear(0);",
" // BUG: Diagnostic contains: "
+ "The 1900-based year value (-1) is out of bounds [1..150].",
" date.setYear(-1);",
" // BUG: Diagnostic contains: "
+ "The 1900-based year value (2020) is out of bounds [1..150].",
" date.setYear(2020);",
" }",
"}")
.doTest();
}
@Test
public void setters_badMonths() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" public void foo(Date date) {",
" // BUG: Diagnostic contains: The 0-based month value (-13) is out of bounds"
+ " [0..11].",
" date.setMonth(-13);",
" // BUG: Diagnostic contains: The 0-based month value (-1) is out of bounds"
+ " [0..11].",
" date.setMonth(-1);",
" // BUG: Diagnostic contains: The 0-based month value (12) is out of bounds"
+ " [0..11].",
" date.setMonth(12);",
" }",
"}")
.doTest();
}
@Test
public void setters_badDays() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" public void foo(Date date) {",
" // BUG: Diagnostic contains: The day value (-32) is out of bounds [1..31].",
" date.setDate(-32);",
" // BUG: Diagnostic contains: The day value (0) is out of bounds [1..31].",
" date.setDate(0);",
" // BUG: Diagnostic contains: The day value (32) is out of bounds [1..31].",
" date.setDate(32);",
" }",
"}")
.doTest();
}
@Test
public void setters_badHours() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" public void foo(Date date) {",
" // BUG: Diagnostic contains: The hours value (-1) is out of bounds [0..23].",
" date.setHours(-1);",
" // BUG: Diagnostic contains: The hours value (24) is out of bounds [0..23].",
" date.setHours(24);",
" }",
"}")
.doTest();
}
@Test
public void setters_badMinutes() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" public void foo(Date date) {",
" // BUG: Diagnostic contains: The minutes value (-1) is out of bounds [0..59].",
" date.setMinutes(-1);",
" // BUG: Diagnostic contains: The minutes value (60) is out of bounds [0..59].",
" date.setMinutes(60);",
" }",
"}")
.doTest();
}
@Test
public void setters_badSeconds() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.Date;",
"public class TestClass {",
" public void foo(Date date) {",
" // BUG: Diagnostic contains: The seconds value (-1) is out of bounds [0..59].",
" date.setSeconds(-1);",
" // BUG: Diagnostic contains: The seconds value (60) is out of bounds [0..59].",
" date.setSeconds(60);",
" }",
"}")
.doTest();
}
}
| 13,657
| 36.01355
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/ProtoTimestampGetSecondsGetNanoTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link ProtoTimestampGetSecondsGetNano}.
*
* @author kak@google.com (Kurt Alfred Kluever)
*/
@RunWith(JUnit4.class)
@Ignore("b/130667208")
public class ProtoTimestampGetSecondsGetNanoTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ProtoTimestampGetSecondsGetNano.class, getClass());
@Test
public void getSecondsWithGetNanos() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" public static void foo(Timestamp timestamp) {",
" long seconds = timestamp.getSeconds();",
" int nanos = timestamp.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInReturnType() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" public static int foo(Timestamp timestamp) {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" return timestamp.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInReturnType2() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" public static ImmutableMap<String, Object> foo(Timestamp timestamp) {",
" return ImmutableMap.of(",
" \"seconds\", timestamp.getSeconds(), \"nanos\", timestamp.getNanos());",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosDifferentScope() {
// Ideally we would also catch cases like this, but it requires scanning "too much" of the class
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" public static void foo(Timestamp timestamp) {",
" long seconds = timestamp.getSeconds();",
" if (true) {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" int nanos = timestamp.getNanos();",
" }",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInDifferentMethods() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" public static void foo(Timestamp timestamp) {",
" long seconds = timestamp.getSeconds();",
" }",
" public static void bar(Timestamp timestamp) {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" int nanos = timestamp.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnly() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" public static void foo(Timestamp timestamp) {",
" long seconds = timestamp.getSeconds();",
" }",
"}")
.doTest();
}
@Test
public void getNanoOnly() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" public static void foo(Timestamp timestamp) {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" int nanos = timestamp.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getNanoInMethodGetSecondsInClassVariable() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
" private static final long seconds = TIMESTAMP.getSeconds();",
" public static void foo() {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" int nanos = TIMESTAMP.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnlyInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" static {",
" long seconds = Timestamp.getDefaultInstance().getSeconds();",
" }",
"}")
.doTest();
}
@Test
public void getNanoOnlyInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" static {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" int nanos = Timestamp.getDefaultInstance().getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnlyInClassBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" private final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
" private final long seconds = TIMESTAMP.getSeconds();",
" private final int nanos = TIMESTAMP.getNanos();",
"}")
.doTest();
}
@Test
public void getNanoOnlyInClassBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" private final int nanos = Timestamp.getDefaultInstance().getNanos();",
"}")
.doTest();
}
@Test
public void getNanoInInnerClassGetSecondsInMethod() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
" public static void foo() {",
" long seconds = TIMESTAMP.getSeconds();",
" Object obj = new Object() {",
" @Override public String toString() {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" return String.valueOf(TIMESTAMP.getNanos()); ",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void getNanoInInnerClassGetSecondsInClassVariable() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
" long seconds = TIMESTAMP.getSeconds();",
" Object obj = new Object() {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" long nanos = TIMESTAMP.getNanos();",
" };",
"}")
.doTest();
}
@Test
public void getNanoInMethodGetSecondsInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
" public static void foo() {",
" Runnable r = () -> TIMESTAMP.getSeconds();",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" int nanos = TIMESTAMP.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"import java.util.function.Supplier;",
"public class TestCase {",
" private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
" public void foo() {",
" doSomething(() -> TIMESTAMP.getSeconds());",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" int nanos = TIMESTAMP.getNanos();",
" }",
" public void doSomething(Supplier<Long> supplier) {",
" }",
"}")
.doTest();
}
@Test
public void getNanoInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Timestamp;",
"public class TestCase {",
" private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
" public static void foo() {",
" // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
" Runnable r = () -> TIMESTAMP.getNanos();",
" long seconds = TIMESTAMP.getSeconds();",
" }",
"}")
.doTest();
}
@Test
public void getMessageGetSecondsGetNanos() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.errorprone.bugpatterns.time.Test.DurationTimestamp;",
"public class TestCase {",
" public static void foo(DurationTimestamp durationTimestamp) {",
" long seconds = durationTimestamp.getTestTimestamp().getSeconds();",
" int nanos = durationTimestamp.getTestTimestamp().getNanos();",
" }",
"}")
.doTest();
}
}
| 11,856
| 33.170029
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/InvalidJavaTimeConstantTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link InvalidJavaTimeConstant}.
*
* @author kak@google.com (Kurt Alfred Kluever)
*/
@RunWith(JUnit4.class)
public class InvalidJavaTimeConstantTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(InvalidJavaTimeConstant.class, getClass());
@Test
public void cornerCases() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.LocalDateTime;",
"import java.time.LocalTime;",
"public class TestCase {",
" // BUG: Diagnostic contains: MonthOfYear (valid values 1 - 12): 0",
" private static final LocalDateTime LDT0 = LocalDateTime.of(0, 0, 0, 0, 0);",
" private static final LocalDateTime LDT1 = LocalDateTime.of(0, 1, 1, 0, 0);",
" private static final LocalTime LT = LocalTime.ofNanoOfDay(12345678);",
"}")
.doTest();
}
@Test
public void localDate_areOk() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.LocalDate;",
"import java.time.Month;",
"public class TestCase {",
" private static final LocalDate LD0 = LocalDate.of(1985, 5, 31);",
" private static final LocalDate LD1 = LocalDate.of(1985, Month.MAY, 31);",
// we can't catch this since it's not a literal
" private static final LocalDate LD2 = LocalDate.of(1985, getBadMonth(), 31);",
" private static int getBadMonth() { return 13; }",
" private static final LocalDate EPOCH_DAY_ZERO = LocalDate.ofEpochDay(0);",
" private static final LocalDate EPOCH_DAY_LARGE = LocalDate.ofEpochDay(123467);",
"}")
.doTest();
}
@Test
public void localDate_withBadDays() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.LocalDate;",
"import java.time.Month;",
"public class TestCase {",
" // BUG: Diagnostic contains: DayOfMonth (valid values 1 - 28/31): 32",
" private static final LocalDate LD0 = LocalDate.of(1985, 5, 32);",
" // BUG: Diagnostic contains: DayOfMonth (valid values 1 - 28/31): 32",
" private static final LocalDate LD1 = LocalDate.of(1985, Month.MAY, 32);",
"}")
.doTest();
}
@Test
public void localDate_withBadMonths() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.LocalDate;",
"public class TestCase {",
" // BUG: Diagnostic contains: MonthOfYear (valid values 1 - 12): -1",
" private static final LocalDate LD0 = LocalDate.of(1985, -1, 31);",
" // BUG: Diagnostic contains: MonthOfYear (valid values 1 - 12): 0",
" private static final LocalDate LD1 = LocalDate.of(1985, 0, 31);",
" // BUG: Diagnostic contains: MonthOfYear (valid values 1 - 12): 13",
" private static final LocalDate LD2 = LocalDate.of(1985, 13, 31);",
"}")
.doTest();
}
@Test
public void localDate_withBadYears() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.LocalDate;",
"import java.time.Year;",
"public class TestCase {",
" // BUG: Diagnostic contains: Year (valid values -999999999 - 999999999):"
+ " -1000000000",
" private static final LocalDate LD0 = LocalDate.of(Year.MIN_VALUE - 1, 5, 31);",
" // BUG: Diagnostic contains: Year (valid values -999999999 - 999999999): 1000000000",
" private static final LocalDate LD1 = LocalDate.of(Year.MAX_VALUE + 1, 5, 31);",
"}")
.doTest();
}
@Test
public void localDate_withBadDayOfMonth() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.LocalDate;",
"public class TestCase {",
" private static LocalDate foo(LocalDate localDate) {",
" // BUG: Diagnostic contains: DayOfMonth (valid values 1 - 28/31): 0",
" return localDate.withDayOfMonth(0);",
" }",
"}")
.doTest();
}
@Test
public void localTime_withBadHour() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.LocalTime;",
"public class TestCase {",
" private static LocalTime foo(LocalTime localTime) {",
" // BUG: Diagnostic contains: HourOfDay (valid values 0 - 23): 25",
" return localTime.withHour(25);",
" }",
"}")
.doTest();
}
@Test
public void dayOfWeek_withBadDay() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.DayOfWeek;",
"public class TestCase {",
" // BUG: Diagnostic contains: DayOfWeek (valid values 1 - 7): 8",
" private static final DayOfWeek DOW = DayOfWeek.of(8);",
"}")
.doTest();
}
}
| 6,300
| 36.064706
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/DurationTemporalUnitTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link DurationTemporalUnit}. */
@RunWith(JUnit4.class)
public class DurationTemporalUnitTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(DurationTemporalUnit.class, getClass());
@Test
public void durationOf_good() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" private static final Duration D0 = Duration.of(1, ChronoUnit.DAYS);",
" private static final Duration D1 = Duration.of(1, ChronoUnit.HALF_DAYS);",
" private static final Duration D2 = Duration.of(1, ChronoUnit.HOURS);",
" private static final Duration D3 = Duration.of(1, ChronoUnit.MICROS);",
" private static final Duration D4 = Duration.of(1, ChronoUnit.MILLIS);",
" private static final Duration D5 = Duration.of(1, ChronoUnit.MINUTES);",
" private static final Duration D6 = Duration.of(1, ChronoUnit.NANOS);",
" private static final Duration D7 = Duration.of(1, ChronoUnit.SECONDS);",
"}")
.doTest();
}
@Test
public void durationOf_bad() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D0 = Duration.of(1, ChronoUnit.CENTURIES);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D1 = Duration.of(1, ChronoUnit.DECADES);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D2 = Duration.of(1, ChronoUnit.ERAS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D3 = Duration.of(1, ChronoUnit.FOREVER);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D4 = Duration.of(1, ChronoUnit.MILLENNIA);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D5 = Duration.of(1, ChronoUnit.MONTHS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D6 = Duration.of(1, ChronoUnit.WEEKS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D7 = Duration.of(1, ChronoUnit.YEARS);",
"}")
.doTest();
}
@Test
public void durationPlus_good() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" private static final Duration D0 = Duration.ZERO.plus(1, ChronoUnit.DAYS);",
" private static final Duration D1 = Duration.ZERO.plus(1, ChronoUnit.HALF_DAYS);",
" private static final Duration D2 = Duration.ZERO.plus(1, ChronoUnit.HOURS);",
" private static final Duration D3 = Duration.ZERO.plus(1, ChronoUnit.MICROS);",
" private static final Duration D4 = Duration.ZERO.plus(1, ChronoUnit.MILLIS);",
" private static final Duration D5 = Duration.ZERO.plus(1, ChronoUnit.MINUTES);",
" private static final Duration D6 = Duration.ZERO.plus(1, ChronoUnit.NANOS);",
" private static final Duration D7 = Duration.ZERO.plus(1, ChronoUnit.SECONDS);",
"}")
.doTest();
}
@Test
public void durationPlus_bad() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D0 = Duration.ZERO.plus(1, ChronoUnit.CENTURIES);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D1 = Duration.ZERO.plus(1, ChronoUnit.DECADES);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D2 = Duration.ZERO.plus(1, ChronoUnit.ERAS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D3 = Duration.ZERO.plus(1, ChronoUnit.FOREVER);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D4 = Duration.ZERO.plus(1, ChronoUnit.MILLENNIA);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D5 = Duration.ZERO.plus(1, ChronoUnit.MONTHS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D6 = Duration.ZERO.plus(1, ChronoUnit.WEEKS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D7 = Duration.ZERO.plus(1, ChronoUnit.YEARS);",
"}")
.doTest();
}
@Test
public void durationMinus_good() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" private static final Duration D0 = Duration.ZERO.minus(1, ChronoUnit.DAYS);",
" private static final Duration D1 = Duration.ZERO.minus(1, ChronoUnit.HALF_DAYS);",
" private static final Duration D2 = Duration.ZERO.minus(1, ChronoUnit.HOURS);",
" private static final Duration D3 = Duration.ZERO.minus(1, ChronoUnit.MICROS);",
" private static final Duration D4 = Duration.ZERO.minus(1, ChronoUnit.MILLIS);",
" private static final Duration D5 = Duration.ZERO.minus(1, ChronoUnit.MINUTES);",
" private static final Duration D6 = Duration.ZERO.minus(1, ChronoUnit.NANOS);",
" private static final Duration D7 = Duration.ZERO.minus(1, ChronoUnit.SECONDS);",
"}")
.doTest();
}
@Test
public void durationMinus_bad() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D0 = Duration.ZERO.minus(1, ChronoUnit.CENTURIES);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D1 = Duration.ZERO.minus(1, ChronoUnit.DECADES);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D2 = Duration.ZERO.minus(1, ChronoUnit.ERAS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D3 = Duration.ZERO.minus(1, ChronoUnit.FOREVER);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D4 = Duration.ZERO.minus(1, ChronoUnit.MILLENNIA);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D5 = Duration.ZERO.minus(1, ChronoUnit.MONTHS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D6 = Duration.ZERO.minus(1, ChronoUnit.WEEKS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D7 = Duration.ZERO.minus(1, ChronoUnit.YEARS);",
"}")
.doTest();
}
@Test
public void durationOfStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoUnit.NANOS;",
"import static java.time.temporal.ChronoUnit.SECONDS;",
"import static java.time.temporal.ChronoUnit.YEARS;",
"import java.time.Duration;",
"public class TestClass {",
" private static final Duration D1 = Duration.of(1, SECONDS);",
" private static final Duration D2 = Duration.of(1, NANOS);",
" // BUG: Diagnostic contains: DurationTemporalUnit",
" private static final Duration D3 = Duration.of(1, YEARS);",
"}")
.doTest();
}
@Test
public void durationOfWithRandomTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoUnit.SECONDS;",
"import static java.time.temporal.ChronoUnit.YEARS;",
"import java.time.Duration;",
"import java.time.temporal.TemporalUnit;",
"import java.util.Random;",
"public class TestClass {",
" private static final TemporalUnit random = ",
" new Random().nextBoolean() ? YEARS : SECONDS;",
// Since we don't know at compile time what 'random' is, we can't flag this
" private static final Duration D1 = Duration.of(1, random);",
"}")
.doTest();
}
@Test
public void durationOfWithAliasedTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoUnit.YEARS;",
"import java.time.Duration;",
"import java.time.temporal.Temporal;",
"import java.time.temporal.TemporalUnit;",
"public class TestClass {",
" private static final TemporalUnit SECONDS = YEARS;",
// This really should be flagged, but isn't :(
" private static final Duration D1 = Duration.of(1, SECONDS);",
"}")
.doTest();
}
@Test
public void durationOfWithCustomTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.temporal.Temporal;",
"import java.time.temporal.TemporalUnit;",
"public class TestClass {",
" private static class BadTemporalUnit implements TemporalUnit {",
" @Override",
" public long between(Temporal t1, Temporal t2) {",
" throw new AssertionError();",
" }",
" @Override",
" public <R extends Temporal> R addTo(R temporal, long amount) {",
" throw new AssertionError();",
" }",
" @Override",
" public boolean isTimeBased() {",
" throw new AssertionError();",
" }",
" @Override",
" public boolean isDateBased() {",
" throw new AssertionError();",
" }",
" @Override",
" public boolean isDurationEstimated() {",
" throw new AssertionError();",
" }",
" @Override",
" public Duration getDuration() {",
" throw new AssertionError();",
" }",
" }",
" private static final TemporalUnit MINUTES = new BadTemporalUnit();",
" private static final TemporalUnit SECONDS = new BadTemporalUnit();",
// This really should be flagged, but isn't :(
" private static final Duration D1 = Duration.of(1, SECONDS);",
" private static final Duration D2 = Duration.of(1, MINUTES);",
"}")
.doTest();
}
}
| 12,701
| 45.870849
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JodaDurationWithMillisTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link JodaDurationWithMillis}. */
@RunWith(JUnit4.class)
public class JodaDurationWithMillisTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaDurationWithMillis.class, getClass());
@Test
public void durationMillis() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" private static final Duration DURATION = Duration.millis(42);",
"}")
.doTest();
}
@Test
public void durationWithMillisIntPrimitive() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" // BUG: Diagnostic contains: use Duration.millis(long) instead",
" private static final Duration DURATION = Duration.ZERO.withMillis(42);",
"}")
.doTest();
}
@Test
public void durationWithMillisLongPrimitive() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" // BUG: Diagnostic contains: use Duration.millis(long) instead",
" private static final Duration DURATION = Duration.ZERO.withMillis(42L);",
"}")
.doTest();
}
@Test
public void durationStandardHoursWithMillisLongPrimitive() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.Duration;",
"public class TestClass {",
" // BUG: Diagnostic contains: use Duration.millis(long) instead",
" private static final Duration DURATION = Duration.standardHours(1).withMillis(42);",
"}")
.doTest();
}
@Test
public void durationConstructorIntPrimitiveInsideJoda() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final Duration DURATION = Duration.ZERO.withMillis(42);",
"}")
.doTest();
}
@Test
public void durationConstructorLongPrimitiveInsideJoda() {
helper
.addSourceLines(
"TestClass.java",
"package org.joda.time;",
"public class TestClass {",
" private static final Duration DURATION = Duration.ZERO.withMillis(42L);",
"}")
.doTest();
}
@Test
public void durationConstructorLongPrimitiveImportClash() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"public class TestClass {",
" private static final org.joda.time.Duration DURATION = ",
" // BUG: Diagnostic contains: Did you mean 'org.joda.time.Duration.millis(42L);'",
" org.joda.time.Duration.ZERO.withMillis(42L);",
"}")
.doTest();
}
}
| 3,823
| 31.40678
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/PeriodGetTemporalUnitTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link PeriodGetTemporalUnit}. */
@RunWith(JUnit4.class)
public class PeriodGetTemporalUnitTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(PeriodGetTemporalUnit.class, getClass());
@Test
public void periodGetTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Period;",
"import java.time.temporal.ChronoUnit;",
"public class TestClass {",
" private static final long years = Period.ZERO.get(ChronoUnit.YEARS);",
" private static final long months = Period.ZERO.get(ChronoUnit.MONTHS);",
" private static final long days = Period.ZERO.get(ChronoUnit.DAYS);",
" // BUG: Diagnostic contains: PeriodGetTemporalUnit",
" private static final long seconds = Period.ZERO.get(ChronoUnit.SECONDS);",
"}")
.doTest();
}
@Test
public void periodGetTemporalUnitStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoUnit.DAYS;",
"import static java.time.temporal.ChronoUnit.MONTHS;",
"import static java.time.temporal.ChronoUnit.SECONDS;",
"import static java.time.temporal.ChronoUnit.YEARS;",
"import java.time.Period;",
"public class TestClass {",
" private static final long years = Period.ZERO.get(YEARS);",
" private static final long months = Period.ZERO.get(MONTHS);",
" private static final long days = Period.ZERO.get(DAYS);",
" // BUG: Diagnostic contains: PeriodGetTemporalUnit",
" private static final long seconds = Period.ZERO.get(SECONDS);",
"}")
.doTest();
}
@Test
public void periodGetWithRandomTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoUnit.DAYS;",
"import static java.time.temporal.ChronoUnit.SECONDS;",
"import java.time.Period;",
"import java.time.temporal.TemporalUnit;",
"import java.util.Random;",
"public class TestClass {",
" private final TemporalUnit random = new Random().nextBoolean() ? DAYS : SECONDS;",
// Since we don't know at compile time what 'random' is, we can't flag this
" private final long mightWork = Period.ZERO.get(random);",
"}")
.doTest();
}
@Test
public void periodGetWithAliasedTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoUnit.SECONDS;",
"import java.time.Period;",
"import java.time.temporal.Temporal;",
"import java.time.temporal.TemporalUnit;",
"public class TestClass {",
" private static final TemporalUnit DAYS = SECONDS;",
// This really should be flagged, but isn't :(
" private static final long seconds = Period.ZERO.get(DAYS);",
"}")
.doTest();
}
@Test
public void periodGetWithCustomTemporalUnit() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.Period;",
"import java.time.temporal.Temporal;",
"import java.time.temporal.TemporalUnit;",
"public class TestClass {",
" private static class BadTemporalUnit implements TemporalUnit {",
" @Override",
" public long between(Temporal t1, Temporal t2) {",
" throw new AssertionError();",
" }",
" @Override",
" public <R extends Temporal> R addTo(R temporal, long amount) {",
" throw new AssertionError();",
" }",
" @Override",
" public boolean isTimeBased() {",
" throw new AssertionError();",
" }",
" @Override",
" public boolean isDateBased() {",
" throw new AssertionError();",
" }",
" @Override",
" public boolean isDurationEstimated() {",
" throw new AssertionError();",
" }",
" @Override",
" public Duration getDuration() {",
" throw new AssertionError();",
" }",
" }",
" private static final TemporalUnit SECONDS = new BadTemporalUnit();",
" private static final TemporalUnit DAYS = new BadTemporalUnit();",
// This really should be flagged, but isn't :(
" private static final long seconds = Period.ZERO.get(DAYS);",
" // BUG: Diagnostic contains: PeriodGetTemporalUnit",
" private static final long days = Period.ZERO.get(SECONDS);",
"}")
.doTest();
}
}
| 5,873
| 38.959184
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionCheckerTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link TimeUnitConversionChecker}. */
@RunWith(JUnit4.class)
public class TimeUnitConversionCheckerTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(TimeUnitConversionChecker.class, getClass());
@Test
public void literalConvertToSelf() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: private long value = 42L /* milliseconds */;",
" private long value = TimeUnit.MILLISECONDS.toMillis(42);",
"}")
.doTest();
}
@Test
public void literalConvertToSelf_withStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.concurrent.TimeUnit.MILLISECONDS;",
"public class TestClass {",
" // BUG: Diagnostic contains: private long value = 42L /* milliseconds */;",
" private long value = MILLISECONDS.toMillis(42);",
"}")
.doTest();
}
@Test
public void variableConvertToSelf_withStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.concurrent.TimeUnit.MILLISECONDS;",
"public class TestClass {",
" private long toConvert = 42;",
" // BUG: Diagnostic contains: private long value = toConvert /* milliseconds */;",
" private long value = MILLISECONDS.toMillis(toConvert);",
"}")
.doTest();
}
@Test
public void expressionEvaluatesToZero() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: private static final long VALUE1 = 0L /* seconds */;",
" private static final long VALUE1 = TimeUnit.MILLISECONDS.toSeconds(4);",
" // BUG: Diagnostic contains: private static final long VALUE2 = 0L /* seconds */;",
" private static final long VALUE2 = TimeUnit.MILLISECONDS.toSeconds(400);",
"}")
.doTest();
}
@Test
public void expressionEvaluatesToZero_withStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.concurrent.TimeUnit.MILLISECONDS;",
"public class TestClass {",
" // BUG: Diagnostic contains: private static final long VALUE1 = 0L /* seconds */;",
" private static final long VALUE1 = MILLISECONDS.toSeconds(4);",
" // BUG: Diagnostic contains: private static final long VALUE2 = 0L /* seconds */;",
" private static final long VALUE2 = MILLISECONDS.toSeconds(400);",
"}")
.doTest();
}
@Test
public void expressionEvaluatesToOne() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: private static final long VALUE1 = 1L /* seconds */;",
" private static final long VALUE1 = TimeUnit.MILLISECONDS.toSeconds(1000);",
" // BUG: Diagnostic contains: private static final long VALUE2 = 1L /* seconds */;",
" private static final long VALUE2 = TimeUnit.MILLISECONDS.toSeconds(1999);",
"}")
.doTest();
}
@Test
public void expressionEvaluatesToNegativeOne() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: TimeUnitConversionChecker",
" private static final long VALUE1 = TimeUnit.MILLISECONDS.toSeconds(-1000);",
" // BUG: Diagnostic contains: TimeUnitConversionChecker",
" private static final long VALUE2 = TimeUnit.MILLISECONDS.toSeconds(-1999);",
"}")
.doTest();
}
@Test
public void expressionEvaluatesToLargeNumber() {
helper
.addSourceLines(
"TestClass.java",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" // BUG: Diagnostic contains: TimeUnitConversionChecker",
" private static final long VALUE1 = TimeUnit.MILLISECONDS.toSeconds(4321);",
" // BUG: Diagnostic contains: TimeUnitConversionChecker",
" private static final long VALUE2 = TimeUnit.MILLISECONDS.toSeconds(-4321);",
"}")
.doTest();
}
@Test
public void expressionEvaluatesToLargeNumber_withStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.concurrent.TimeUnit.MILLISECONDS;",
"public class TestClass {",
" // BUG: Diagnostic contains: TimeUnitConversionChecker",
" private static final long VALUE1 = MILLISECONDS.toSeconds(4321);",
" // BUG: Diagnostic contains: TimeUnitConversionChecker",
" private static final long VALUE2 = MILLISECONDS.toSeconds(-4321);",
"}")
.doTest();
}
@Test
public void largeUnitToSmallUnit_succeeds() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.concurrent.TimeUnit.SECONDS;",
"public class TestClass {",
" private static final long VALUE1 = SECONDS.toMillis(4321);",
" private static final long VALUE2 = SECONDS.toMillis(-4321);",
"}")
.doTest();
}
}
| 6,514
| 36.877907
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/TemporalAccessorGetChronoFieldTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link TemporalAccessorGetChronoField}. */
@RunWith(JUnit4.class)
public class TemporalAccessorGetChronoFieldTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(TemporalAccessorGetChronoField.class, getClass());
@Test
public void temporalAccessor_getLong_noStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.DayOfWeek.MONDAY;",
"import java.time.temporal.ChronoField;",
"public class TestClass {",
" private static final long value1 = MONDAY.getLong(ChronoField.DAY_OF_WEEK);",
" // BUG: Diagnostic contains: TemporalAccessorGetChronoField",
" private static final long value2 = MONDAY.getLong(ChronoField.NANO_OF_DAY);",
"}")
.doTest();
}
@Test
public void temporalAccessor_getLong_staticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.DayOfWeek.MONDAY;",
"import static java.time.temporal.ChronoField.DAY_OF_WEEK;",
"import static java.time.temporal.ChronoField.NANO_OF_DAY;",
"public class TestClass {",
" private static final long value1 = MONDAY.getLong(DAY_OF_WEEK);",
" // BUG: Diagnostic contains: TemporalAccessorGetChronoField",
" private static final long value2 = MONDAY.getLong(NANO_OF_DAY);",
"}")
.doTest();
}
@Test
public void temporalAccessor_get_noStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.DayOfWeek.MONDAY;",
"import java.time.temporal.ChronoField;",
"public class TestClass {",
" private static final int value1 = MONDAY.get(ChronoField.DAY_OF_WEEK);",
" // BUG: Diagnostic contains: TemporalAccessorGetChronoField",
" private static final int value2 = MONDAY.get(ChronoField.NANO_OF_DAY);",
"}")
.doTest();
}
@Test
public void temporalAccessor_get_staticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.DayOfWeek.MONDAY;",
"import static java.time.temporal.ChronoField.DAY_OF_WEEK;",
"import static java.time.temporal.ChronoField.NANO_OF_DAY;",
"public class TestClass {",
" private static final int value1 = MONDAY.get(DAY_OF_WEEK);",
" // BUG: Diagnostic contains: TemporalAccessorGetChronoField",
" private static final int value2 = MONDAY.get(NANO_OF_DAY);",
"}")
.doTest();
}
@Test
public void temporalAccessor_realCode() {
helper
.addSourceLines(
"TestClass.java",
"import static java.time.temporal.ChronoField.MICRO_OF_SECOND;",
"import static java.time.temporal.ChronoField.DAY_OF_WEEK;",
"import java.time.Instant;",
"public class TestClass {",
" private static final int value1 = Instant.now().get(MICRO_OF_SECOND);",
" private static final long value2 = Instant.now().getLong(MICRO_OF_SECOND);",
" // BUG: Diagnostic contains: TemporalAccessorGetChronoField",
" private static final int value3 = Instant.now().get(DAY_OF_WEEK);",
" // BUG: Diagnostic contains: TemporalAccessorGetChronoField",
" private static final long value4 = Instant.now().getLong(DAY_OF_WEEK);",
"}")
.doTest();
}
}
| 4,415
| 39.145455
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/DurationToLongTimeUnitTest.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.time;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link DurationToLongTimeUnit}. */
@RunWith(JUnit4.class)
public class DurationToLongTimeUnitTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(DurationToLongTimeUnit.class, getClass());
@Test
public void correspondingUnitsAreOk() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.protobuf.Duration;",
"import com.google.protobuf.Timestamp;",
"import java.util.concurrent.Future;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" void javaTime(Future<String> f, java.time.Duration d) throws Exception {",
" f.get(42L, TimeUnit.SECONDS);",
" f.get(d.toNanos(), TimeUnit.NANOSECONDS);",
" f.get(d.toMillis(), TimeUnit.MILLISECONDS);",
" f.get(d.getSeconds(), TimeUnit.SECONDS);",
" f.get(d.toMinutes(), TimeUnit.MINUTES);",
" f.get(d.toHours(), TimeUnit.HOURS);",
" f.get(d.toDays(), TimeUnit.DAYS);",
" }",
" void javaTime(Future<String> f, java.time.Instant i) throws Exception {",
" f.get(42L, TimeUnit.SECONDS);",
" f.get(i.toEpochMilli(), TimeUnit.MILLISECONDS);",
" f.get(i.getEpochSecond(), TimeUnit.SECONDS);",
" }",
" void jodaTime(Future<String> f, org.joda.time.Duration d) throws Exception {",
" f.get(42L, TimeUnit.SECONDS);",
" f.get(d.getMillis(), TimeUnit.MILLISECONDS);",
" f.get(d.getStandardSeconds(), TimeUnit.SECONDS);",
" f.get(d.getStandardMinutes(), TimeUnit.MINUTES);",
" f.get(d.getStandardHours(), TimeUnit.HOURS);",
" f.get(d.getStandardDays(), TimeUnit.DAYS);",
" }",
" void jodaTime(Future<String> f, org.joda.time.Instant i) throws Exception {",
" f.get(42L, TimeUnit.SECONDS);",
" f.get(i.getMillis(), TimeUnit.MILLISECONDS);",
" }",
" void protoTime(Future<String> f, Duration d) throws Exception {",
" f.get(42L, TimeUnit.SECONDS);",
" f.get(d.getSeconds(), TimeUnit.SECONDS);",
" }",
" void protoTime(Future<String> f, Timestamp t) throws Exception {",
" f.get(42L, TimeUnit.SECONDS);",
" f.get(t.getSeconds(), TimeUnit.SECONDS);",
" }",
"}")
.doTest();
}
@Test
public void correspondingUnitsAreOk_staticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.concurrent.TimeUnit.DAYS;",
"import static java.util.concurrent.TimeUnit.HOURS;",
"import static java.util.concurrent.TimeUnit.MILLISECONDS;",
"import static java.util.concurrent.TimeUnit.MINUTES;",
"import static java.util.concurrent.TimeUnit.NANOSECONDS;",
"import static java.util.concurrent.TimeUnit.SECONDS;",
"import com.google.protobuf.Duration;",
"import com.google.protobuf.Timestamp;",
"import java.util.concurrent.Future;",
"public class TestClass {",
" void javaTime(Future<String> f, java.time.Duration d) throws Exception {",
" f.get(42L, SECONDS);",
" f.get(d.toNanos(), NANOSECONDS);",
" f.get(d.toMillis(), MILLISECONDS);",
" f.get(d.getSeconds(), SECONDS);",
" f.get(d.toMinutes(), MINUTES);",
" f.get(d.toHours(), HOURS);",
" f.get(d.toDays(), DAYS);",
" }",
" void javaTime(Future<String> f, java.time.Instant i) throws Exception {",
" f.get(42L, SECONDS);",
" f.get(i.toEpochMilli(), MILLISECONDS);",
" f.get(i.getEpochSecond(), SECONDS);",
" }",
" void jodaTime(Future<String> f, org.joda.time.Duration d) throws Exception {",
" f.get(42L, SECONDS);",
" f.get(d.getMillis(), MILLISECONDS);",
" f.get(d.getStandardSeconds(), SECONDS);",
" f.get(d.getStandardMinutes(), MINUTES);",
" f.get(d.getStandardHours(), HOURS);",
" f.get(d.getStandardDays(), DAYS);",
" }",
" void jodaTime(Future<String> f, org.joda.time.Instant i) throws Exception {",
" f.get(42L, SECONDS);",
" f.get(i.getMillis(), MILLISECONDS);",
" }",
" void protoTime(Future<String> f, Duration d) throws Exception {",
" f.get(42L, SECONDS);",
" f.get(d.getSeconds(), SECONDS);",
" }",
" void protoTime(Future<String> f, Timestamp t) throws Exception {",
" f.get(42L, SECONDS);",
" f.get(t.getSeconds(), SECONDS);",
" }",
"}")
.doTest();
}
@Test
public void conflictingUnitsFail() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.protobuf.Duration;",
"import com.google.protobuf.Timestamp;",
"import java.util.concurrent.Future;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" void javaTime(Future<String> f, java.time.Duration d) throws Exception {",
" // BUG: Diagnostic contains: f.get(d.toNanos(), TimeUnit.NANOSECONDS)",
" f.get(d.toNanos(), TimeUnit.MILLISECONDS);",
" // BUG: Diagnostic contains: f.get(d.toMillis(), TimeUnit.MILLISECONDS)",
" f.get(d.toMillis(), TimeUnit.NANOSECONDS);",
" // BUG: Diagnostic contains: f.get(d.getSeconds(), TimeUnit.SECONDS)",
" f.get(d.getSeconds(), TimeUnit.MINUTES);",
" // BUG: Diagnostic contains: f.get(d.toMinutes(), TimeUnit.MINUTES)",
" f.get(d.toMinutes(), TimeUnit.SECONDS);",
" // BUG: Diagnostic contains: f.get(d.toHours(), TimeUnit.HOURS)",
" f.get(d.toHours(), TimeUnit.DAYS);",
" // BUG: Diagnostic contains: f.get(d.toDays(), TimeUnit.DAYS)",
" f.get(d.toDays(), TimeUnit.HOURS);",
" }",
" void javaTime(Future<String> f, java.time.Instant i) throws Exception {",
" // BUG: Diagnostic contains: f.get(i.toEpochMilli(), TimeUnit.MILLISECONDS)",
" f.get(i.toEpochMilli(), TimeUnit.NANOSECONDS);",
" // BUG: Diagnostic contains: f.get(i.getEpochSecond(), TimeUnit.SECONDS)",
" f.get(i.getEpochSecond(), TimeUnit.MINUTES);",
" }",
" void jodaTime(Future<String> f, org.joda.time.Duration d) throws Exception {",
" // BUG: Diagnostic contains: f.get(d.getMillis(), TimeUnit.MILLISECONDS)",
" f.get(d.getMillis(), TimeUnit.NANOSECONDS);",
" // BUG: Diagnostic contains: f.get(d.getStandardSeconds(), TimeUnit.SECONDS)",
" f.get(d.getStandardSeconds(), TimeUnit.MINUTES);",
" // BUG: Diagnostic contains: f.get(d.getStandardMinutes(), TimeUnit.MINUTES)",
" f.get(d.getStandardMinutes(), TimeUnit.SECONDS);",
" // BUG: Diagnostic contains: f.get(d.getStandardHours(), TimeUnit.HOURS)",
" f.get(d.getStandardHours(), TimeUnit.DAYS);",
" // BUG: Diagnostic contains: f.get(d.getStandardDays(), TimeUnit.DAYS)",
" f.get(d.getStandardDays(), TimeUnit.HOURS);",
" }",
" void jodaTime(Future<String> f, org.joda.time.Instant i) throws Exception {",
" // BUG: Diagnostic contains: f.get(i.getMillis(), TimeUnit.MILLISECONDS)",
" f.get(i.getMillis(), TimeUnit.NANOSECONDS);",
" }",
" void protoTime(Future<String> f, Duration d) throws Exception {",
" // BUG: Diagnostic contains: f.get(d.getSeconds(), TimeUnit.SECONDS)",
" f.get(d.getSeconds(), TimeUnit.MINUTES);",
" }",
" void protoTime(Future<String> f, Timestamp t) throws Exception {",
" // BUG: Diagnostic contains: f.get(t.getSeconds(), TimeUnit.SECONDS)",
" f.get(t.getSeconds(), TimeUnit.MINUTES);",
" }",
"}")
.doTest();
}
@Test
public void conflictingUnitsFail_staticImport() {
helper
.addSourceLines(
"TestClass.java",
"import static java.util.concurrent.TimeUnit.DAYS;",
"import static java.util.concurrent.TimeUnit.HOURS;",
"import static java.util.concurrent.TimeUnit.MILLISECONDS;",
"import static java.util.concurrent.TimeUnit.MINUTES;",
"import static java.util.concurrent.TimeUnit.NANOSECONDS;",
"import static java.util.concurrent.TimeUnit.SECONDS;",
"import com.google.protobuf.Duration;",
"import com.google.protobuf.Timestamp;",
"import java.util.concurrent.Future;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" void javaTime(Future<String> f, java.time.Duration d) throws Exception {",
" // BUG: Diagnostic contains: f.get(d.toNanos(), TimeUnit.NANOSECONDS)",
" f.get(d.toNanos(), MILLISECONDS);",
" // BUG: Diagnostic contains: f.get(d.toMillis(), TimeUnit.MILLISECONDS)",
" f.get(d.toMillis(), NANOSECONDS);",
" // BUG: Diagnostic contains: f.get(d.getSeconds(), TimeUnit.SECONDS)",
" f.get(d.getSeconds(), MINUTES);",
" // BUG: Diagnostic contains: f.get(d.toMinutes(), TimeUnit.MINUTES)",
" f.get(d.toMinutes(), SECONDS);",
" // BUG: Diagnostic contains: f.get(d.toHours(), TimeUnit.HOURS)",
" f.get(d.toHours(), DAYS);",
" // BUG: Diagnostic contains: f.get(d.toDays(), TimeUnit.DAYS)",
" f.get(d.toDays(), HOURS);",
" }",
" void javaTime(Future<String> f, java.time.Instant i) throws Exception {",
" // BUG: Diagnostic contains: f.get(i.toEpochMilli(), TimeUnit.MILLISECONDS)",
" f.get(i.toEpochMilli(), NANOSECONDS);",
" // BUG: Diagnostic contains: f.get(i.getEpochSecond(), TimeUnit.SECONDS)",
" f.get(i.getEpochSecond(), MINUTES);",
" }",
" void jodaTime(Future<String> f, org.joda.time.Duration d) throws Exception {",
" // BUG: Diagnostic contains: f.get(d.getMillis(), TimeUnit.MILLISECONDS)",
" f.get(d.getMillis(), NANOSECONDS);",
" // BUG: Diagnostic contains: f.get(d.getStandardSeconds(), TimeUnit.SECONDS)",
" f.get(d.getStandardSeconds(), MINUTES);",
" // BUG: Diagnostic contains: f.get(d.getStandardMinutes(), TimeUnit.MINUTES)",
" f.get(d.getStandardMinutes(), SECONDS);",
" // BUG: Diagnostic contains: f.get(d.getStandardHours(), TimeUnit.HOURS)",
" f.get(d.getStandardHours(), DAYS);",
" // BUG: Diagnostic contains: f.get(d.getStandardDays(), TimeUnit.DAYS)",
" f.get(d.getStandardDays(), HOURS);",
" }",
" void jodaTime(Future<String> f, org.joda.time.Instant i) throws Exception {",
" // BUG: Diagnostic contains: f.get(i.getMillis(), TimeUnit.MILLISECONDS)",
" f.get(i.getMillis(), NANOSECONDS);",
" }",
" void protoTime(Future<String> f, Duration d) throws Exception {",
" // BUG: Diagnostic contains: f.get(d.getSeconds(), TimeUnit.SECONDS)",
" f.get(d.getSeconds(), MINUTES);",
" }",
" void protoTime(Future<String> f, Timestamp t) throws Exception {",
" // BUG: Diagnostic contains: f.get(t.getSeconds(), TimeUnit.SECONDS)",
" f.get(t.getSeconds(), MINUTES);",
" }",
"}")
.doTest();
}
@Test
public void nonTimeUnitVariablesAreOk() {
helper
.addSourceLines(
"TestClass.java",
"import com.google.protobuf.Duration;",
"import com.google.protobuf.Timestamp;",
"public class TestClass {",
" private enum MyEnum { DAYS };",
" void javaTime(java.time.Duration d) {",
" myMethod(d.toNanos(), MyEnum.DAYS);",
" }",
" void javaTime(java.time.Instant i) {",
" myMethod(i.toEpochMilli(), MyEnum.DAYS);",
" }",
" void jodaTime(org.joda.time.Duration d) {",
" myMethod(d.getMillis(), MyEnum.DAYS);",
" }",
" void jodaTime(org.joda.time.Instant i) {",
" myMethod(i.getMillis(), MyEnum.DAYS);",
" }",
" void protoTime(Duration d) {",
" myMethod(d.getSeconds(), MyEnum.DAYS);",
" }",
" void protoTime(Timestamp t) {",
" myMethod(t.getSeconds(), MyEnum.DAYS);",
" }",
" void myMethod(long value, MyEnum myEnum) {",
" // no op",
" }",
"}")
.doTest();
}
@Test
public void intTimeUnitParameters() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" void javaTime(Duration d) {",
// TODO(b/132492921) " // BUG: Diagnostic contains: DurationToLongTimeUnit",
" myMethod((int) d.toHours(), TimeUnit.SECONDS);",
" }",
" void myMethod(int value, TimeUnit unit) {",
" // no op",
" }",
"}")
.doTest();
}
@Test
public void timeUnitFromConvert() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.util.concurrent.TimeUnit;",
"public class TestClass {",
" void javaTime(Duration d) {",
" // BUG: Diagnostic contains: DurationToLongTimeUnit",
" myMethod(TimeUnit.SECONDS.convert(d), TimeUnit.MINUTES);",
" }",
" void myMethod(long value, TimeUnit unit) {",
" // no op",
" }",
"}")
.setArgs(ImmutableList.of("--release", "11"))
.doTest();
}
}
| 15,682
| 47.107362
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/ProtoDurationGetSecondsGetNanoTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link ProtoDurationGetSecondsGetNano}.
*
* @author kak@google.com (Kurt Alfred Kluever)
*/
@RunWith(JUnit4.class)
@Ignore("b/130667208")
public class ProtoDurationGetSecondsGetNanoTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ProtoDurationGetSecondsGetNano.class, getClass());
@Test
public void getSecondsWithGetNanos() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" long seconds = duration.getSeconds();",
" int nanos = duration.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInReturnType() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" public static int foo(Duration duration) {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" return duration.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInReturnType2() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" public static ImmutableMap<String, Object> foo(Duration duration) {",
" return ImmutableMap.of(",
" \"seconds\", duration.getSeconds(), \"nanos\", duration.getNanos());",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosDifferentScope() {
// Ideally we would also catch cases like this, but it requires scanning "too much" of the class
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" long seconds = duration.getSeconds();",
" if (true) {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" int nanos = duration.getNanos();",
" }",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInDifferentMethods() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" long seconds = duration.getSeconds();",
" }",
" public static void bar(Duration duration) {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" int nanos = duration.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnly() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" long seconds = duration.getSeconds();",
" }",
"}")
.doTest();
}
@Test
public void getNanoOnly() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" int nanos = duration.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getNanoInMethodGetSecondsInClassVariable() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" private static final Duration DURATION = Duration.getDefaultInstance();",
" private static final long seconds = DURATION.getSeconds();",
" public static void foo() {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" int nanos = DURATION.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnlyInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" static {",
" long seconds = Duration.getDefaultInstance().getSeconds();",
" }",
"}")
.doTest();
}
@Test
public void getNanoOnlyInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" static {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" int nanos = Duration.getDefaultInstance().getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnlyInClassBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" private final Duration DURATION = Duration.getDefaultInstance();",
" private final long seconds = DURATION.getSeconds();",
" private final int nanos = DURATION.getNanos();",
"}")
.doTest();
}
@Test
public void getNanoOnlyInClassBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" private final int nanos = Duration.getDefaultInstance().getNanos();",
"}")
.doTest();
}
@Test
public void getNanoInInnerClassGetSecondsInMethod() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" private static final Duration DURATION = Duration.getDefaultInstance();",
" public static void foo() {",
" long seconds = DURATION.getSeconds();",
" Object obj = new Object() {",
" @Override public String toString() {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" return String.valueOf(DURATION.getNanos()); ",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void getNanoInInnerClassGetSecondsInClassVariable() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" Duration DURATION = Duration.getDefaultInstance();",
" long seconds = DURATION.getSeconds();",
" Object obj = new Object() {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" long nanos = DURATION.getNanos();",
" };",
"}")
.doTest();
}
@Test
public void getNanoInMethodGetSecondsInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" private static final Duration DURATION = Duration.getDefaultInstance();",
" public static void foo() {",
" Runnable r = () -> DURATION.getSeconds();",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" int nanos = DURATION.getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"import java.util.function.Supplier;",
"public class TestCase {",
" private static final Duration DURATION = Duration.getDefaultInstance();",
" public void foo() {",
" doSomething(() -> DURATION.getSeconds());",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" int nanos = DURATION.getNanos();",
" }",
" public void doSomething(Supplier<Long> supplier) {",
" }",
"}")
.doTest();
}
@Test
public void getNanoInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.protobuf.Duration;",
"public class TestCase {",
" private static final Duration DURATION = Duration.getDefaultInstance();",
" public static void foo() {",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" Runnable r = () -> DURATION.getNanos();",
" long seconds = DURATION.getSeconds();",
" }",
"}")
.doTest();
}
@Test
public void getMessageGetSecondsGetNanos() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.errorprone.bugpatterns.time.Test.DurationTimestamp;",
"public class TestCase {",
" public static void foo(DurationTimestamp durationTimestamp) {",
" long seconds = durationTimestamp.getTestDuration().getSeconds();",
" int nanos = durationTimestamp.getTestDuration().getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getNestedMessageGetSecondsGetNanos() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.errorprone.bugpatterns.time.Test.DurationTimestamp;",
"public class TestCase {",
" public static void foo(DurationTimestamp dt) {",
" long seconds = dt.getNestedMessage().getNestedTestDuration().getSeconds();",
" int nanos = dt.getNestedMessage().getNestedTestDuration().getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getNestedMessageGetSecondsGetNanos_onDifferentProtoInstances() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.errorprone.bugpatterns.time.Test.DurationTimestamp;",
"public class TestCase {",
" public static void foo(DurationTimestamp dt1, DurationTimestamp dt2) {",
" long seconds = dt1.getNestedMessage().getNestedTestDuration().getSeconds();",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" int nanos = dt2.getNestedMessage().getNestedTestDuration().getNanos();",
" }",
"}")
.doTest();
}
@Test
public void getMessageGetSecondsGetNanosDifferentSubMessage() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.errorprone.bugpatterns.time.Test.DurationTimestamp;",
"public class TestCase {",
" public static void foo(DurationTimestamp durationTimestamp) {",
" long seconds = durationTimestamp.getTestDuration().getSeconds();",
" // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano",
" int nanos = durationTimestamp.getAnotherTestDuration().getNanos();",
" }",
"}")
.doTest();
}
}
| 13,788
| 33.732997
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaInstantGetSecondsGetNanoTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link JavaInstantGetSecondsGetNano}.
*
* @author kak@google.com (Kurt Alfred Kluever)
*/
@RunWith(JUnit4.class)
public class JavaInstantGetSecondsGetNanoTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JavaInstantGetSecondsGetNano.class, getClass());
@Test
public void getSecondsWithGetNanos() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" public static void foo(Instant instant) {",
" long seconds = instant.getEpochSecond();",
" int nanos = instant.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInReturnType() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.common.collect.ImmutableMap;",
"import java.time.Instant;",
"public class TestCase {",
" public static int foo(Instant instant) {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" return instant.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInReturnType2() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.common.collect.ImmutableMap;",
"import java.time.Instant;",
"public class TestCase {",
" public static ImmutableMap<String, Object> foo(Instant instant) {",
" return ImmutableMap.of(",
" \"seconds\", instant.getEpochSecond(), \"nanos\", instant.getNano());",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosDifferentScope() {
// Ideally we would also catch cases like this, but it requires scanning "too much" of the class
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" public static void foo(Instant instant) {",
" long seconds = instant.getEpochSecond();",
" if (true) {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" int nanos = instant.getNano();",
" }",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInDifferentMethods() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" public static void foo(Instant instant) {",
" long seconds = instant.getEpochSecond();",
" }",
" public static void bar(Instant instant) {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" int nanos = instant.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnly() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" public static void foo(Instant instant) {",
" long seconds = instant.getEpochSecond();",
" }",
"}")
.doTest();
}
@Test
public void getNanoOnly() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" public static void foo(Instant instant) {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" int nanos = instant.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getNanoInMethodGetSecondsInClassVariable() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" private static final Instant INSTANT = Instant.EPOCH;",
" private static final long seconds = INSTANT.getEpochSecond();",
" public static void foo() {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" int nanos = INSTANT.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnlyInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" static {",
" long seconds = Instant.EPOCH.getEpochSecond();",
" }",
"}")
.doTest();
}
@Test
public void getNanoOnlyInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" static {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" int nanos = Instant.EPOCH.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnlyInClassBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" private final long seconds = Instant.EPOCH.getEpochSecond();",
" private final int nanos = Instant.EPOCH.getNano();",
"}")
.doTest();
}
@Test
public void getNanoOnlyInClassBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" private final int nanos = Instant.EPOCH.getNano();",
"}")
.doTest();
}
@Test
public void getNanoInInnerClassGetSecondsInMethod() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" private static final Instant INSTANT = Instant.EPOCH;",
" public static void foo() {",
" long seconds = INSTANT.getEpochSecond();",
" Object obj = new Object() {",
" @Override public String toString() {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" return String.valueOf(INSTANT.getNano()); ",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void getNanoInInnerClassGetSecondsInClassVariable() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" Instant INSTANT = Instant.EPOCH;",
" long seconds = INSTANT.getEpochSecond();",
" Object obj = new Object() {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" long nanos = INSTANT.getNano();",
" };",
"}")
.doTest();
}
@Test
public void getNanoInMethodGetSecondsInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" private static final Instant INSTANT = Instant.EPOCH;",
" public static void foo() {",
" Runnable r = () -> INSTANT.getEpochSecond();",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" int nanos = INSTANT.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"import java.util.function.Supplier;",
"public class TestCase {",
" private static final Instant INSTANT = Instant.EPOCH;",
" public void foo() {",
" doSomething(() -> INSTANT.getEpochSecond());",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" int nanos = INSTANT.getNano();",
" }",
" public void doSomething(Supplier<Long> supplier) {",
" }",
"}")
.doTest();
}
@Test
public void getNanoInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Instant;",
"public class TestCase {",
" private static final Instant INSTANT = Instant.EPOCH;",
" public static void foo() {",
" // BUG: Diagnostic contains: JavaInstantGetSecondsGetNano",
" Runnable r = () -> INSTANT.getNano();",
" long seconds = INSTANT.getEpochSecond();",
" }",
"}")
.doTest();
}
}
| 10,671
| 31.536585
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaDurationGetSecondsGetNanoTest.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.time;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link JavaDurationGetSecondsGetNano}.
*
* @author kak@google.com (Kurt Alfred Kluever)
*/
@RunWith(JUnit4.class)
public class JavaDurationGetSecondsGetNanoTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JavaDurationGetSecondsGetNano.class, getClass());
@Test
public void getSecondsWithGetNanos() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" long seconds = duration.getSeconds();",
" int nanos = duration.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInReturnType() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.common.collect.ImmutableMap;",
"import java.time.Duration;",
"public class TestCase {",
" public static int foo(Duration duration) {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" return duration.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInReturnType2() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import com.google.common.collect.ImmutableMap;",
"import java.time.Duration;",
"public class TestCase {",
" public static ImmutableMap<String, Object> foo(Duration duration) {",
" return ImmutableMap.of(",
" \"seconds\", duration.getSeconds(), \"nanos\", duration.getNano());",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosDifferentScope() {
// Ideally we would also catch cases like this, but it requires scanning "too much" of the class
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" long seconds = duration.getSeconds();",
" if (true) {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" int nanos = duration.getNano();",
" }",
" }",
"}")
.doTest();
}
@Test
public void getSecondsWithGetNanosInDifferentMethods() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" long seconds = duration.getSeconds();",
" }",
" public static void bar(Duration duration) {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" int nanos = duration.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnly() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" long seconds = duration.getSeconds();",
" }",
"}")
.doTest();
}
@Test
public void getNanoOnly() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" public static void foo(Duration duration) {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" int nanos = duration.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getNanoInMethodGetSecondsInClassVariable() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" private static final Duration DURATION = Duration.ZERO;",
" private static final long seconds = DURATION.getSeconds();",
" public static void foo() {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" int nanos = DURATION.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnlyInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" static {",
" long seconds = Duration.ZERO.getSeconds();",
" }",
"}")
.doTest();
}
@Test
public void getNanoOnlyInStaticBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" static {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" int nanos = Duration.ZERO.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsOnlyInClassBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" private final long seconds = Duration.ZERO.getSeconds();",
" private final int nanos = Duration.ZERO.getNano();",
"}")
.doTest();
}
@Test
public void getNanoOnlyInClassBlock() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" private final int nanos = Duration.ZERO.getNano();",
"}")
.doTest();
}
@Test
public void getNanoInInnerClassGetSecondsInMethod() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" private static final Duration DURATION = Duration.ZERO;",
" public static void foo() {",
" long seconds = DURATION.getSeconds();",
" Object obj = new Object() {",
" @Override public String toString() {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" return String.valueOf(DURATION.getNano()); ",
" }",
" };",
" }",
"}")
.doTest();
}
@Test
public void getNanoInInnerClassGetSecondsInClassVariable() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" Duration DURATION = Duration.ZERO;",
" long seconds = DURATION.getSeconds();",
" Object obj = new Object() {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" long nanos = DURATION.getNano();",
" };",
"}")
.doTest();
}
@Test
public void getNanoInMethodGetSecondsInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" private static final Duration DURATION = Duration.ZERO;",
" public static void foo() {",
" Runnable r = () -> DURATION.getSeconds();",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" int nanos = DURATION.getNano();",
" }",
"}")
.doTest();
}
@Test
public void getSecondsInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"import java.util.function.Supplier;",
"public class TestCase {",
" private static final Duration DURATION = Duration.ZERO;",
" public void foo() {",
" doSomething(() -> DURATION.getSeconds());",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" int nanos = DURATION.getNano();",
" }",
" public void doSomething(Supplier<Long> supplier) {",
" }",
"}")
.doTest();
}
@Test
public void getNanoInLambda() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.Duration;",
"public class TestCase {",
" private static final Duration DURATION = Duration.ZERO;",
" public static void foo() {",
" // BUG: Diagnostic contains: JavaDurationGetSecondsGetNano",
" Runnable r = () -> DURATION.getNano();",
" long seconds = DURATION.getSeconds();",
" }",
"}")
.doTest();
}
}
| 10,702
| 31.631098
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/FromTemporalAccessorTest.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.time;
import static com.google.common.base.StandardSystemProperty.JAVA_VERSION;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FromTemporalAccessor}. */
@RunWith(JUnit4.class)
public class FromTemporalAccessorTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(FromTemporalAccessor.class, getClass());
@Test
public void typeFromTypeIsBad() {
helper
.addSourceLines(
"TestClass.java",
// TODO(kak): Should we just use a wildcard import instead?
"import java.time.DayOfWeek;",
"import java.time.Instant;",
"import java.time.LocalDate;",
"import java.time.LocalDateTime;",
"import java.time.LocalTime;",
"import java.time.Month;",
"import java.time.MonthDay;",
"import java.time.OffsetDateTime;",
"import java.time.OffsetTime;",
"import java.time.Year;",
"import java.time.YearMonth;",
"import java.time.ZonedDateTime;",
"import java.time.ZoneOffset;",
"public class TestClass {",
" void from(DayOfWeek value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" DayOfWeek.from(value);",
" }",
" void from(Instant value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" Instant.from(value);",
" }",
" void from(LocalDate value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" LocalDate.from(value);",
" }",
" void from(LocalDateTime value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" LocalDateTime.from(value);",
" }",
" void from(LocalTime value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" LocalTime.from(value);",
" }",
" void from(Month value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" Month.from(value);",
" }",
" void from(MonthDay value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" MonthDay.from(value);",
" }",
" void from(OffsetDateTime value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" OffsetDateTime.from(value);",
" }",
" void from(OffsetTime value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" OffsetTime.from(value);",
" }",
" void from(Year value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" Year.from(value);",
" }",
" void from(YearMonth value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" YearMonth.from(value);",
" }",
" void from(ZonedDateTime value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" ZonedDateTime.from(value);",
" }",
" void from(ZoneOffset value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" ZoneOffset.from(value);",
" }",
"}")
.doTest();
}
@Test
public void typeFromTemporalAccessor_knownGood() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.DayOfWeek;",
"import java.time.Instant;",
"import java.time.LocalDate;",
"import java.time.LocalDateTime;",
"import java.time.LocalTime;",
"import java.time.Month;",
"import java.time.MonthDay;",
"import java.time.OffsetDateTime;",
"import java.time.OffsetTime;",
"import java.time.Year;",
"import java.time.YearMonth;",
"import java.time.ZonedDateTime;",
"import java.time.ZoneOffset;",
"import java.time.temporal.TemporalAccessor;",
"public class TestClass {",
" void from(TemporalAccessor value) {",
" DayOfWeek.from(value);",
" Instant.from(value);",
" LocalDate.from(value);",
" LocalDateTime.from(value);",
" LocalTime.from(value);",
" Month.from(value);",
" MonthDay.from(value);",
" OffsetDateTime.from(value);",
" OffsetTime.from(value);",
" Year.from(value);",
" YearMonth.from(value);",
" ZonedDateTime.from(value);",
" ZoneOffset.from(value);",
" }",
"}")
.doTest();
}
@Test
public void typeFromType_knownGood() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.LocalDate;",
"import java.time.Year;",
"public class TestClass {",
" void from(LocalDate value) {",
" Year.from(value);",
" }",
"}")
.doTest();
}
@Test
public void typeFromType_threeTenExtra_knownGood() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.LocalTime;",
"import org.threeten.extra.AmPm;",
"public class TestClass {",
" void from(LocalTime value) {",
" AmPm.from(value);",
" }",
"}")
.doTest();
}
@Test
public void typeFromType_threeTenExtra_self() {
helper
.addSourceLines(
"TestClass.java",
"import org.threeten.extra.AmPm;",
"public class TestClass {",
" void from(AmPm value) {",
" // BUG: Diagnostic contains: Did you mean 'value;'",
" AmPm.from(value);",
" }",
"}")
.doTest();
}
@Test
public void typeFromType_customType() {
helper
.addSourceLines(
"Frobber.java",
"import java.time.DateTimeException;",
"import java.time.temporal.TemporalAccessor;",
"import java.time.temporal.TemporalField;",
"public class Frobber implements TemporalAccessor {",
" static Frobber from(TemporalAccessor temporalAccessor) {",
" if (temporalAccessor instanceof Frobber) {",
" return (Frobber) temporalAccessor;",
" }",
" throw new DateTimeException(\"failure\");",
" }",
" @Override public long getLong(TemporalField field) { return 0; }",
" @Override public boolean isSupported(TemporalField field) { return false; }",
"}")
.addSourceLines(
"TestClass.java",
"public class TestClass {",
" void from(Frobber value) {",
" Frobber frobber = Frobber.from(value);",
" }",
"}")
.doTest();
}
@Test
public void typeFromType_knownBadConversions() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.LocalDate;",
"import java.time.LocalDateTime;",
"import org.threeten.extra.Quarter;",
"public class TestClass {",
" void from(LocalDate localDate, Quarter quarter) {",
" // BUG: Diagnostic contains: FromTemporalAccessor",
" LocalDateTime.from(localDate);",
" // BUG: Diagnostic contains: FromTemporalAccessor",
" LocalDateTime.from(quarter);",
" }",
"}")
.doTest();
}
@Test
public void typeFromType_knownBadConversions_insideJavaTime() {
// this test doesn't pass under JDK11 because of modules
if (JAVA_VERSION.value().startsWith("1.")) {
helper
.addSourceLines(
"TestClass.java",
"package java.time;",
"import java.time.LocalDate;",
"import java.time.LocalDateTime;",
"public class TestClass {",
" void from(LocalDate localDate) {",
" LocalDateTime.from(localDate);",
" }",
"}")
.doTest();
}
}
@Test
public void typeFromType_knownBadConversions_insideThreeTenExtra() {
helper
.addSourceLines(
"TestClass.java",
"package org.threeten.extra;",
"import java.time.LocalDateTime;",
"public class TestClass {",
" void from(Quarter quarter) {",
" LocalDateTime.from(quarter);",
" }",
"}")
.doTest();
}
}
| 9,685
| 34.610294
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/testdata/TimeUnitMismatchPositiveCases.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.time.testdata;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.util.Optional;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
public class TimeUnitMismatchPositiveCases {
int startMicros;
int stopMillis;
void fields() {
// BUG: Diagnostic contains: expected microseconds but was milliseconds
startMicros = stopMillis;
// BUG: Diagnostic contains: If it instead means microseconds
startMicros = stopMillis;
// BUG: Diagnostic contains: MILLISECONDS.toMicros(stopMillis)
startMicros = stopMillis;
}
void memberSelect() {
// BUG: Diagnostic contains: expected microseconds but was milliseconds
this.startMicros = this.stopMillis;
}
void locals() {
int millis = 0;
// BUG: Diagnostic contains: expected microseconds but was milliseconds
startMicros = millis;
}
long getMicros() {
return 0;
}
void returns() {
// BUG: Diagnostic contains: expected nanoseconds but was microseconds
long fooNano = getMicros();
}
void doSomething(double startSec, double endSec) {}
void setMyMillis(int timeout) {}
void args() {
double ms = 0;
double ns = 0;
// BUG: Diagnostic contains: expected seconds but was milliseconds
doSomething(ms, ns);
// BUG: Diagnostic contains: expected seconds but was nanoseconds
doSomething(ms, ns);
// BUG: Diagnostic contains: expected milliseconds but was nanoseconds
setMyMillis((int) ns);
}
void timeUnit() {
int micros = 0;
// BUG: Diagnostic contains: expected nanoseconds but was microseconds
NANOSECONDS.toMillis(micros);
}
class Foo {
Foo(long seconds) {}
}
void constructor() {
int nanos = 0;
// BUG: Diagnostic contains: expected seconds but was nanoseconds
new Foo(nanos);
}
void boxed() {
Long nanos = 0L;
// BUG: Diagnostic contains: expected milliseconds but was nanoseconds
long millis = nanos;
}
void optionalGet() {
Optional<Long> maybeNanos = Optional.of(0L);
// BUG: Diagnostic contains: expected milliseconds but was nanoseconds
long millis = maybeNanos.get();
}
}
| 2,785
| 25.533333
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/time/testdata/TimeUnitMismatchNegativeCases.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.time.testdata;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.util.Optional;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
public class TimeUnitMismatchNegativeCases {
static final int THE_MILLIS = 0;
int startMillis;
int stopMillis;
void fields() {
startMillis = THE_MILLIS;
startMillis = stopMillis;
}
void memberSelect() {
this.startMillis = this.stopMillis;
}
void locals() {
int millis = 0;
startMillis = millis;
}
long getMicros() {
return 0;
}
void returns() {
long fooUs = getMicros();
}
void doSomething(double startSec, double endSec) {}
void args() {
double seconds = 0;
doSomething(seconds, seconds);
}
void timeUnit() {
int nanos = 0;
NANOSECONDS.toMillis(nanos);
}
class Foo {
Foo(long seconds) {}
}
void constructor() {
int seconds = 0;
new Foo(seconds);
}
String milliseconds() {
return "0";
}
void nonNumeric() {
String seconds = milliseconds();
}
void boxed() {
Long startNanos = 0L;
long endNanos = startNanos;
}
void optionalGet() {
Optional<Long> maybeNanos = Optional.of(0L);
long nanos = maybeNanos.get();
}
}
| 1,871
| 19.129032
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/apidiff/ApiDiffCheckerTest.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.apidiff;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.CLASS;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.errorprone.BaseErrorProneJavaCompiler;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.bugpatterns.apidiff.ApiDiff.ClassMemberKey;
import com.google.errorprone.bugpatterns.apidiff.ApiDiffProto.Diff;
import com.google.errorprone.bugpatterns.apidiff.CompilationBuilderHelpers.CompilationBuilder;
import com.google.errorprone.bugpatterns.apidiff.CompilationBuilderHelpers.CompilationResult;
import com.google.errorprone.bugpatterns.apidiff.CompilationBuilderHelpers.SourceBuilder;
import com.google.errorprone.scanner.ErrorProneScanner;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ApiDiffChecker}Test. */
@RunWith(JUnit4.class)
public class ApiDiffCheckerTest {
@Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
private final JavacFileManager fileManager =
new JavacFileManager(new Context(), false, StandardCharsets.UTF_8);
@Retention(CLASS)
@Target({ANNOTATION_TYPE, CONSTRUCTOR, FIELD, METHOD, TYPE})
public @interface RequiresNewApiVersion {}
private final CompilationTestHelper compilationHelper;
/** An {@link ApiDiffChecker} for testing. */
@BugPattern(name = "SampleChecker", severity = SeverityLevel.ERROR, summary = "")
private static class SampleApiDiffChecker extends ApiDiffChecker {
SampleApiDiffChecker(ApiDiff apiDiff) {
super(apiDiff);
}
}
/** An {@link ApiDiffChecker} that recognizes only {@link RequiresNewApiVersion} annotations. */
@BugPattern(
name = "AnnotationChecker",
severity = SeverityLevel.ERROR,
summary = "",
suppressionAnnotations = {RequiresNewApiVersion.class, SuppressWarnings.class})
public static class AnnotationOnlyApiDiffChecker extends ApiDiffChecker {
public AnnotationOnlyApiDiffChecker() {
super(ApiDiff.fromProto(Diff.getDefaultInstance()), RequiresNewApiVersion.class);
}
}
public ApiDiffCheckerTest() {
compilationHelper =
CompilationTestHelper.newInstance(AnnotationOnlyApiDiffChecker.class, getClass());
}
@Test
public void newDerivedMethod() throws Exception {
ApiDiff diff =
ApiDiff.fromMembers(
Collections.emptySet(),
ImmutableSetMultimap.of("lib/Derived", ClassMemberKey.create("g", "()V")));
Path originalJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"Base.java", //
"package lib;",
"public class Base {",
" public void f() {}",
"}")
.addSourceLines(
"Derived.java", //
"package lib;",
"public class Derived extends Base {",
"}")
.build())
.compileOutputToJarOrDie();
Path newJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setClasspath(Collections.singleton(originalJar))
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"Derived.java", //
"package lib;",
"public class Derived extends Base {",
" public void f() {}",
" public void g() {}",
"}")
.build())
.compileOutputToJarOrDie();
BaseErrorProneJavaCompiler errorProneCompiler =
new BaseErrorProneJavaCompiler(
ScannerSupplier.fromScanner(new ErrorProneScanner(new SampleApiDiffChecker(diff))));
CompilationResult result =
new CompilationBuilder(errorProneCompiler, tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"Test.java",
"import lib.*;", //
"class Test {",
" void f() {",
" new Derived().f();",
" new Derived().g();",
" }",
"}")
.build())
.setClasspath(Arrays.asList(newJar, originalJar))
.compile();
assertThat(getOnlyElement(result.diagnostics()).getMessage(Locale.ENGLISH))
.contains("g() is not available in lib.Derived");
}
@Test
public void addedSuperAndMethod() throws Exception {
ApiDiff diff =
ApiDiff.fromMembers(
ImmutableSet.of("lib/A"),
ImmutableSetMultimap.of("lib/B", ClassMemberKey.create("f", "()V")));
Path originalJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"B.java", //
"package lib;",
"public class B {",
"}")
.build())
.compileOutputToJarOrDie();
Path newJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"A.java", //
"package lib;",
"interface A {",
" default void f() {}",
"}")
.addSourceLines(
"B.java", //
"package lib;",
"public class B implements A {",
"}")
.build())
.compileOutputToJarOrDie();
BaseErrorProneJavaCompiler errorProneCompiler =
new BaseErrorProneJavaCompiler(
ScannerSupplier.fromScanner(new ErrorProneScanner(new SampleApiDiffChecker(diff))));
CompilationResult result =
new CompilationBuilder(errorProneCompiler, tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"Test.java",
"import lib.*;", //
"class Test {",
" void f(B b) {",
" b.f();",
" }",
"}")
.build())
.setClasspath(Arrays.asList(newJar, originalJar))
.compile();
// This should be an error (the inherited A.f() is not backwards compatible), but we don't
// detect newly added methods in newly added super types.
assertThat(result.diagnostics()).isEmpty();
}
@Test
public void movedMethodToNewSuper() throws Exception {
ApiDiff diff = ApiDiff.fromMembers(ImmutableSet.of("lib/A"), ImmutableSetMultimap.of());
Path originalJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"B.java", //
"package lib;",
"public class B {",
" public void f() {}",
"}")
.build())
.compileOutputToJarOrDie();
Path newJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"A.java", //
"package lib;",
"interface A {",
" default void f() {}",
"}")
.addSourceLines(
"B.java", //
"package lib;",
"public class B implements A {}")
.build())
.compileOutputToJarOrDie();
BaseErrorProneJavaCompiler errorProneCompiler =
new BaseErrorProneJavaCompiler(
ScannerSupplier.fromScanner(new ErrorProneScanner(new SampleApiDiffChecker(diff))));
CompilationResult result =
new CompilationBuilder(errorProneCompiler, tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"Test.java",
"import lib.*;", //
"class Test {",
" void f(B b) {",
" b.f();",
" }",
"}")
.build())
.setClasspath(Arrays.asList(newJar, originalJar))
.compile();
assertThat(result.diagnostics()).isEmpty();
}
@Test
public void movedToSuperMethodFromMiddle() throws Exception {
ApiDiff diff =
ApiDiff.fromMembers(
ImmutableSet.of(), ImmutableSetMultimap.of("lib/A", ClassMemberKey.create("f", "()V")));
Path originalJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"A.java", //
"package lib;",
"public class A {",
"}")
.addSourceLines(
"B.java", //
"package lib;",
"public class B extends A {",
" public void f() {}",
"}")
.addSourceLines(
"C.java", //
"package lib;",
"public class C extends B {",
"}")
.build())
.compileOutputToJarOrDie();
Path newJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"A.java", //
"package lib;",
"public class A {",
" public void f() {}",
"}")
.addSourceLines(
"B.java", //
"package lib;",
"public class B extends A {",
"}")
.addSourceLines(
"C.java", //
"package lib;",
"public class C extends B {",
"}")
.build())
.compileOutputToJarOrDie();
BaseErrorProneJavaCompiler errorProneCompiler =
new BaseErrorProneJavaCompiler(
ScannerSupplier.fromScanner(new ErrorProneScanner(new SampleApiDiffChecker(diff))));
CompilationResult result =
new CompilationBuilder(errorProneCompiler, tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"Test.java",
"import lib.*;", //
"class Test {",
" void f(C c) {",
" c.f();",
" }",
"}")
.build())
.setClasspath(Arrays.asList(newJar, originalJar))
.compile();
// This is actually OK, but we see it as a call to the newly-added A.f, and don't consider that
// B.f is available in the old version of the API. It's not clear how to avoid this false
// positive.
assertThat(result.diagnostics()).hasSize(1);
assertThat(getOnlyElement(result.diagnostics()).getMessage(Locale.ENGLISH))
.contains("lib.A#f() is not available in lib.C");
}
@Test
public void subType() throws Exception {
ApiDiff diff =
ApiDiff.fromMembers(
ImmutableSet.of(), ImmutableSetMultimap.of("lib/A", ClassMemberKey.create("f", "()V")));
Path originalJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"A.java", //
"package lib;",
"public class A {",
"}")
.build())
.compileOutputToJarOrDie();
Path newJar =
new CompilationBuilder(JavacTool.create(), tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"A.java", //
"package lib;",
"public class A {",
" public void f() {}",
"}")
.build())
.compileOutputToJarOrDie();
BaseErrorProneJavaCompiler errorProneCompiler =
new BaseErrorProneJavaCompiler(
ScannerSupplier.fromScanner(new ErrorProneScanner(new SampleApiDiffChecker(diff))));
CompilationResult result =
new CompilationBuilder(errorProneCompiler, tempFolder.newFolder(), fileManager)
.setSources(
new SourceBuilder(tempFolder.newFolder())
.addSourceLines(
"Test.java",
"import lib.A;", //
"class Test {",
" void g() {",
" new A() {}.f();",
" }",
"}")
.build())
.setClasspath(Arrays.asList(newJar, originalJar))
.compile();
assertThat(result.diagnostics()).hasSize(1);
assertThat(getOnlyElement(result.diagnostics()).getMessage(Locale.ENGLISH))
.contains("lib.A#f() is not available in <anonymous Test$1>");
}
@Test
public void positiveAnnotatedClass() {
compilationHelper
.addSourceLines(
"Lib.java",
"package my.lib;",
"import"
+ " com.google.errorprone.bugpatterns.apidiff.ApiDiffCheckerTest.RequiresNewApiVersion;",
"@RequiresNewApiVersion",
"public final class Lib {}")
.addSourceLines(
"Test.java",
"import my.lib.Lib;",
"class Test {",
" // BUG: Diagnostic contains: Lib",
" Lib l;",
"}")
.doTest();
}
@Test
public void positiveAnnotatedClassSuppressedBySameAnnotation() {
compilationHelper
.addSourceLines(
"Lib.java",
"package my.lib;",
"import"
+ " com.google.errorprone.bugpatterns.apidiff.ApiDiffCheckerTest.RequiresNewApiVersion;",
"@RequiresNewApiVersion",
"public final class Lib {}")
.addSourceLines(
"Test.java",
"import"
+ " com.google.errorprone.bugpatterns.apidiff.ApiDiffCheckerTest.RequiresNewApiVersion;",
"import my.lib.Lib;",
"class Test {",
" @RequiresNewApiVersion",
" Lib l;",
"}")
.doTest();
}
@Test
public void positiveAnnotatedMethod() {
compilationHelper
.addSourceLines(
"Lib.java",
"package my.lib;",
"import"
+ " com.google.errorprone.bugpatterns.apidiff.ApiDiffCheckerTest.RequiresNewApiVersion;",
"public final class Lib {",
" @RequiresNewApiVersion",
" public void foo() {}",
"}")
.addSourceLines(
"Test.java",
"import my.lib.Lib;",
"class Test {",
" void bar() {",
" // BUG: Diagnostic contains: foo",
" new Lib().foo();",
" }",
"}")
.doTest();
}
@Test
public void positiveAnnotatedField() {
compilationHelper
.addSourceLines(
"Lib.java",
"package my.lib;",
"import"
+ " com.google.errorprone.bugpatterns.apidiff.ApiDiffCheckerTest.RequiresNewApiVersion;",
"public final class Lib {",
" @RequiresNewApiVersion",
" public static final int FOO = 1;",
"}")
.addSourceLines(
"Test.java",
"import my.lib.Lib;",
"class Test {",
" void bar() {",
" // BUG: Diagnostic contains: FOO",
" System.out.println(Lib.FOO);",
" }",
"}")
.doTest();
}
}
| 19,188
| 36.922925
| 105
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/apidiff/AndroidJdkLibsCheckerTest.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.apidiff;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link AndroidJdkLibsChecker}Test. */
@RunWith(JUnit4.class)
public class AndroidJdkLibsCheckerTest extends Java7ApiCheckerTest {
private final CompilationTestHelper allowJava8Helper =
CompilationTestHelper.newInstance(AndroidJdkLibsChecker.class, getClass())
.setArgs(ImmutableList.of("-XepOpt:Android:Java8Libs"));
public AndroidJdkLibsCheckerTest() {
super(AndroidJdkLibsChecker.class);
}
@Test
public void repeatedAnnotationAllowed() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.lang.annotation.Repeatable;",
"@Repeatable(Test.Container.class)",
"public @interface Test {",
" public @interface Container {",
" Test[] value();",
" }",
"}")
.doTest();
}
@Test
public void typeAnnotationAllowed() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.lang.annotation.Target;",
"import java.lang.annotation.ElementType;",
"@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})",
"public @interface Test {",
"}")
.doTest();
}
@Test
public void defaultMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Map;",
"public class Test {",
" abstract static class A implements Map<Object, Object> {}",
" abstract static class B implements Map<Object, Object> {",
" @Override",
" public Object getOrDefault(Object key, Object defaultValue) {",
" return null;",
" }",
" }",
" void f(A a, B b) {",
" // BUG: Diagnostic contains: java.util.Map#getOrDefault(java.lang.Object,V)"
+ " is not available in Test.A",
" a.getOrDefault(null, null);",
" b.getOrDefault(null, null); // OK: overrides getOrDefault",
" }",
"}")
.doTest();
}
@Test
public void typeKind() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains:",
" javax.lang.model.type.TypeKind tk;",
"}")
.doTest();
}
@Test
public void stopwatchElapsed() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Stopwatch;",
"import java.util.concurrent.TimeUnit;",
"public class Test {",
" void o() {",
" // BUG: Diagnostic contains:",
" Stopwatch.createStarted().elapsed();",
" Stopwatch.createStarted().elapsed(TimeUnit.MILLISECONDS);",
" }",
"}")
.doTest();
}
@Test
public void allowJava8Flag_packageAllowed() {
allowJava8Helper
.addSourceLines(
"Test.java",
"import java.time.Duration;",
"import java.util.stream.Stream;",
"import com.google.common.base.Predicates;",
"import java.util.Arrays;",
"public class Test {",
" Duration d = Duration.ofSeconds(10);",
" public static void test(Stream s) {",
" s.forEach(i -> {});",
" }",
"}")
.doTest();
}
@Test
public void allowJava8Flag_memberAllowed() {
allowJava8Helper
.addSourceLines(
"Test.java",
"import java.util.Arrays;",
"public class Test {",
" public static void main(String... args) {",
" Arrays.stream(args);",
" }",
"}")
.doTest();
}
@Test
public void allowJava8Flag_memberBanned() {
allowJava8Helper
.addSourceLines(
"Test.java",
"import java.util.stream.Stream;",
"public class Test {",
" public static void test(Stream s) {",
" // BUG: Diagnostic contains: parallel",
" s.parallel();",
" }",
"}")
.doTest();
}
@Test
public void allowJava8Flag_getTimeZone() {
allowJava8Helper
.addSourceLines(
"Test.java",
"import java.time.ZoneId;",
"import java.util.TimeZone;",
"public class Test {",
" public static void test() {",
" TimeZone.getTimeZone(\"a\");",
" TimeZone.getTimeZone(ZoneId.of(\"a\"));",
" }",
"}")
.doTest();
}
@Test
public void allowJava8Flag_explicitNestedClass() {
allowJava8Helper
.addSourceLines(
"Test.java",
"import java.util.Spliterator;",
"public abstract class Test implements Spliterator.OfInt {",
"}")
.doTest();
}
@Test
public void forEach() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Collection;",
"class T {",
" void f(Iterable<?> i, Collection<?> c) {",
" // BUG: Diagnostic contains: java.lang.Iterable#forEach",
" i.forEach(System.err::println);",
" // BUG: Diagnostic contains: java.lang.Iterable#forEach",
" c.forEach(System.err::println);",
" }",
"}")
.doTest();
}
@Test
public void allowJava8Flag_forEach() {
allowJava8Helper
.addSourceLines(
"Test.java",
"import java.util.Collection;",
"class T {",
" void f(Iterable<?> i, Collection<?> c) {",
" i.forEach(System.err::println);",
" c.forEach(System.err::println);",
" }",
"}")
.doTest();
}
@Test
public void moduleInfo() {
compilationHelper
.addSourceLines(
"module-info.java", //
"module testmodule {",
" requires java.base;",
"}")
.doTest();
}
}
| 7,013
| 28.846809
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/apidiff/Java8ApiCheckerTest.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.apidiff;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link Java8ApiChecker}Test */
@RunWith(JUnit4.class)
public class Java8ApiCheckerTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(Java8ApiChecker.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" boolean f(Optional<String> o) {",
" // BUG: Diagnostic contains: java.util.Optional#isEmpty() is not available",
" return o.isEmpty();",
" }",
"}")
.doTest();
}
@Test
public void bufferPositive() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.nio.ByteBuffer;",
"class Test {",
" void f(ByteBuffer b, int i) {",
" // BUG: Diagnostic contains: ByteBuffer#position(int) is not available",
" b.position(i);",
" }",
"}")
.doTest();
}
@Test
public void bufferNegative() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.nio.ByteBuffer;",
"class Test {",
" void f(ByteBuffer b, int i) {",
" b.position(i);",
" }",
"}")
.setArgs("-XepOpt:Java8ApiChecker:checkBuffer=false")
.doTest();
}
@Test
public void checksumPositive() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.zip.CRC32;",
"class Test {",
" void f(CRC32 c, byte[] b) {",
" // BUG: Diagnostic contains: Checksum#update(byte[]) is not available",
" c.update(b);",
" }",
"}")
.doTest();
}
@Test
public void checksumNegative() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.zip.CRC32;",
"class Test {",
" void f(CRC32 c, byte[] b) {",
" c.update(b);",
" }",
"}")
.setArgs("-XepOpt:Java8ApiChecker:checkChecksum=false")
.doTest();
}
}
| 3,053
| 27.811321
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/apidiff/CompilationBuilderHelpers.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.apidiff;
import static com.google.common.truth.Truth.assertWithMessage;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.sun.tools.javac.file.JavacFileManager;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
/** Compilation test helpers for ApiDiff tools. */
public final class CompilationBuilderHelpers {
/** A collection of sources to compile. */
public static class SourceBuilder {
final File tempFolder;
final List<Path> sources = new ArrayList<>();
public SourceBuilder(File tempFolder) {
this.tempFolder = tempFolder;
}
@CanIgnoreReturnValue
public SourceBuilder addSourceLines(String name, String... lines) throws IOException {
Path filePath = Paths.get(tempFolder.getAbsolutePath(), name);
sources.add(filePath);
Files.write(filePath, Arrays.asList(lines), UTF_8, StandardOpenOption.CREATE);
return this;
}
public List<Path> build() {
return ImmutableList.copyOf(sources);
}
}
/** A wrapper around {@link JavaCompiler}. */
public static class CompilationBuilder {
final JavaCompiler compiler;
final File tempFolder;
final JavacFileManager fileManager;
private Collection<Path> sources = Collections.emptyList();
private Collection<Path> classpath = Collections.emptyList();
private Iterable<String> javacopts = Collections.emptyList();
public CompilationBuilder(
JavaCompiler compiler, File tempFolder, JavacFileManager fileManager) {
this.compiler = compiler;
this.tempFolder = tempFolder;
this.fileManager = fileManager;
}
@CanIgnoreReturnValue
public CompilationBuilder setSources(Collection<Path> sources) {
this.sources = sources;
return this;
}
@CanIgnoreReturnValue
public CompilationBuilder setClasspath(Collection<Path> classpath) {
this.classpath = classpath;
return this;
}
@CanIgnoreReturnValue
CompilationBuilder setJavacopts(Iterable<String> javacopts) {
this.javacopts = javacopts;
return this;
}
CompilationResult compile() throws IOException {
Path output = tempFolder.toPath();
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
StringWriter errorOutput = new StringWriter();
fileManager.setLocationFromPaths(StandardLocation.CLASS_PATH, classpath);
fileManager.setLocationFromPaths(StandardLocation.SOURCE_PATH, Collections.<Path>emptyList());
fileManager.setLocationFromPaths(
StandardLocation.ANNOTATION_PROCESSOR_PATH, Collections.<Path>emptyList());
fileManager.setLocationFromPaths(
StandardLocation.CLASS_OUTPUT, Collections.singleton(output));
boolean ok =
compiler
.getTask(
new PrintWriter(errorOutput, true),
fileManager,
diagnosticCollector,
javacopts,
/* classes= */ Collections.<String>emptyList(),
fileManager.getJavaFileObjects(sources.toArray(new Path[0])))
.call();
return CompilationResult.create(
ok, diagnosticCollector.getDiagnostics(), errorOutput.toString(), output);
}
CompilationResult compileOrDie() throws IOException {
CompilationResult result = compile();
assertWithMessage("Compilation failed unexpectedly")
.withMessage(Joiner.on('\n').join(result.diagnostics()))
.that(result.ok())
.isTrue();
return result;
}
public Path compileOutputToJarOrDie() throws IOException {
Path outputDir = compileOrDie().classOutput();
Path outputJar = outputDir.resolve("output.jar");
try (OutputStream os = Files.newOutputStream(outputJar);
JarOutputStream jos = new JarOutputStream(os)) {
Files.walkFileTree(
outputDir,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs)
throws IOException {
if (path.toString().endsWith(".class")) {
// Manually join so that we use / instead of the platform default.
jos.putNextEntry(new JarEntry(Joiner.on('/').join(outputDir.relativize(path))));
Files.copy(path, jos);
}
return FileVisitResult.CONTINUE;
}
});
}
return outputJar;
}
}
/** The output from a compilation. */
@AutoValue
abstract static class CompilationResult {
abstract boolean ok();
abstract ImmutableList<Diagnostic<? extends JavaFileObject>> diagnostics();
abstract String errorOutput();
abstract Path classOutput();
static CompilationResult create(
boolean ok,
Iterable<Diagnostic<? extends JavaFileObject>> diagnostics,
String errorOutput,
Path classOutput) {
return new AutoValue_CompilationBuilderHelpers_CompilationResult(
ok, ImmutableList.copyOf(diagnostics), errorOutput, classOutput);
}
}
private CompilationBuilderHelpers() {}
}
| 6,731
| 33.172589
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/apidiff/Java7ApiCheckerTest.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.apidiff;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link Java7ApiChecker}Test */
@RunWith(JUnit4.class)
public class Java7ApiCheckerTest {
protected final CompilationTestHelper compilationHelper;
public Java7ApiCheckerTest() {
this(Java7ApiChecker.class);
}
protected Java7ApiCheckerTest(Class<? extends ApiDiffChecker> checker) {
compilationHelper = CompilationTestHelper.newInstance(checker, getClass());
}
@Test
public void positiveClass() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" // BUG: Diagnostic contains: java.util.Optional",
" Optional<String> o;",
"}")
.doTest();
}
@Test
public void positiveMethod() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"class Test {",
" void f(List<Integer> xs) {",
" // BUG: Diagnostic contains: stream() is not available in java.util.List",
" xs.stream();",
" }",
"}")
.doTest();
}
@Test
public void positiveField() {
compilationHelper
.addSourceLines(
"Test.java",
"import javax.lang.model.SourceVersion;",
"class Test {",
" // BUG: Diagnostic contains: RELEASE_8",
" SourceVersion version8 = SourceVersion.RELEASE_8;",
"}")
.doTest();
}
@Test
public void negativeInherited() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.LinkedHashMap;",
"import java.util.concurrent.ConcurrentHashMap;",
"import java.util.Set;",
"class Test {",
" Set<String> getKeySet(LinkedHashMap<String, String> map) {",
" return map.keySet();",
" }",
" Set<String> getKeySet(ConcurrentHashMap<String, String> map) {",
" // BUG: Diagnostic contains: keySet()",
" return map.keySet();",
" }",
"}")
.doTest();
}
}
| 2,941
| 28.717172
| 91
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/CompatibleWithMisuseTest.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.collectionincompatibletype;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link CompatibleWithMisuse} */
@RunWith(JUnit4.class)
public class CompatibleWithMisuseTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(CompatibleWithMisuse.class, getClass());
@Test
public void oK() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompatibleWith;",
"class Test<X> {",
" static final String CONSTANT = \"X\";",
" void doSomething(@CompatibleWith(\"X\") Object ok) {}",
" void doSomethingWithConstant(@CompatibleWith(CONSTANT) Object ok) {}",
" <Y extends String> void doSomethingElse(@CompatibleWith(\"Y\") Object ok) {}",
" <X,Z> void doSomethingTwice(@CompatibleWith(\"X\") Object ok) {}",
"}")
.doTest();
}
@Test
public void bad() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompatibleWith;",
"class Test<X> {",
" static final String CONSTANT = \"Y\";",
" // BUG: Diagnostic contains: Valid arguments are: X",
" void doSomething(@CompatibleWith(\"Y\") Object bad) {}",
" // BUG: Diagnostic contains: Valid arguments are: X",
" void doSomethingWithConstant(@CompatibleWith(CONSTANT) Object bad) {}",
" // BUG: Diagnostic contains: not be empty (valid arguments are X)",
" void doSomethingEmpty(@CompatibleWith(\"\") Object bad) {}",
" // BUG: Diagnostic contains: Valid arguments are: Z, X",
" <Z> void doSomethingElse(@CompatibleWith(\"Y\") Object ok) {}",
"}")
.doTest();
}
@Test
public void overridesAlreadyAnnotated() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompatibleWith;",
"class Test<X> {",
" void doSomething(@CompatibleWith(\"X\") Object bad) {}",
"}",
"class Foo<X> extends Test<X> {",
" // BUG: Diagnostic contains: in Test that already has @CompatibleWith",
" void doSomething(@CompatibleWith(\"X\") Object bad) {}",
"}")
.doTest();
}
@Test
public void noTypeArgs() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompatibleWith;",
"class Test {",
" // BUG: Diagnostic contains: There are no type arguments",
" void doSomething(@CompatibleWith(\"Y\") Object bad) {}",
"}")
.doTest();
}
@Test
public void allowedOnVarargs() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompatibleWith;",
"class Test<Y> {",
" void doSomething(@CompatibleWith(\"Y\") Object... ok) {}",
"}")
.doTest();
}
@Test
public void innerTypes() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompatibleWith;",
"class Test<X> {",
" class Test2<Y> {",
" class Test3<Z> {",
" // BUG: Diagnostic contains: Valid arguments are: Z, Y, X",
" void doSomething(@CompatibleWith(\"P\") Object bad) {}",
" // BUG: Diagnostic contains: Valid arguments are: Q, Z, Y, X",
" <Q> void doSomethingElse(@CompatibleWith(\"P\") Object bad) {}",
" }",
" }",
"}")
.doTest();
}
@Test
public void nestedTypes() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompatibleWith;",
"class Test<X> {",
" static class Test2<Y> {",
" class Test3<Z> {",
" // BUG: Diagnostic contains: Valid arguments are: Z, Y",
" void doSomething(@CompatibleWith(\"X\") Object bad) {}",
" // BUG: Diagnostic contains: Valid arguments are: Q, Z, Y",
" <Q> void doSomethingElse(@CompatibleWith(\"X\") Object bad) {}",
" }",
" // BUG: Diagnostic contains: Valid arguments are: Y",
" void doSomething(@CompatibleWith(\"X\") Object bad) {}",
" }",
"}")
.doTest();
}
}
| 5,425
| 35.662162
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/IncompatibleArgumentTypeTest.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.collectionincompatibletype;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link IncompatibleArgumentType} */
@RunWith(JUnit4.class)
public class IncompatibleArgumentTypeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(IncompatibleArgumentType.class, getClass());
@Test
public void genericMethod() {
compilationHelper.addSourceFile("IncompatibleArgumentTypeGenericMethod.java").doTest();
}
@Test
public void owningTypes() {
compilationHelper.addSourceFile("IncompatibleArgumentTypeEnclosingTypes.java").doTest();
}
@Test
public void multimapIntegration() {
compilationHelper.addSourceFile("IncompatibleArgumentTypeMultimapIntegration.java").doTest();
}
@Test
public void intersectionTypes() {
compilationHelper.addSourceFile("IncompatibleArgumentTypeIntersectionTypes.java").doTest();
}
@Test
public void typeWithinLambda() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.errorprone.annotations.CompatibleWith;",
"import java.util.Map;",
"import java.util.Optional;",
"abstract class Test {",
" abstract <K, V> Optional<V> getOrEmpty(Map<K, V> map, @CompatibleWith(\"K\") Object"
+ " key);",
" void test(Map<Long, String> map, ImmutableList<Long> xs) {",
" // BUG: Diagnostic contains:",
" getOrEmpty(map, xs);",
" Optional<String> x = Optional.empty().flatMap(k -> getOrEmpty(map, xs));",
" }",
"}")
.doTest();
}
}
| 2,467
| 33.277778
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/CollectionUndefinedEqualityTest.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.collectionincompatibletype;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link CollectionUndefinedEquality}. */
@RunWith(JUnit4.class)
public final class CollectionUndefinedEqualityTest {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(CollectionUndefinedEquality.class, getClass());
@Test
public void collectionOfCollections() {
helper
.addSourceLines(
"Test.java",
"import java.util.Collection;",
"class Test {",
" boolean foo(Collection<Collection<Integer>> xs, Collection<Integer> x) {",
" // BUG: Diagnostic contains:",
" return xs.contains(x);",
" }",
"}")
.doTest();
}
@Test
public void collectionOfLists_noFinding() {
helper
.addSourceLines(
"Test.java",
"import java.util.Collection;",
"import java.util.List;",
"class Test {",
" boolean foo(Collection<List<Integer>> xs, List<Integer> x) {",
" return xs.contains(x);",
" }",
"}")
.doTest();
}
@Test
public void treeMap_noFinding() {
helper
.addSourceLines(
"Test.java",
"import java.util.Collection;",
"import java.util.TreeMap;",
"class Test {",
" boolean foo(TreeMap<Collection<Integer>, Integer> xs, Collection<Integer> x) {",
" return xs.containsKey(x);",
" }",
"}")
.doTest();
}
@Test
public void sortedMap_noFinding() {
helper
.addSourceLines(
"Test.java",
"import java.util.Collection;",
"import java.util.SortedMap;",
"class Test {",
" boolean foo(SortedMap<Collection<Integer>, Integer> xs, Collection<Integer> x) {",
" return xs.containsKey(x);",
" }",
"}")
.doTest();
}
@Test
public void sortedSet_noFinding() {
helper
.addSourceLines(
"Test.java",
"import java.util.Collection;",
"import java.util.SortedSet;",
"class Test {",
" boolean foo(SortedSet<Collection<Integer>> xs, Collection<Integer> x) {",
" return xs.contains(x);",
" }",
"}")
.doTest();
}
}
| 3,174
| 29.238095
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/CollectionIncompatibleTypeTest.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.collectionincompatibletype;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author alexeagle@google.com (Alex Eagle)
*/
@RunWith(JUnit4.class)
public class CollectionIncompatibleTypeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(CollectionIncompatibleType.class, getClass());
private final BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(CollectionIncompatibleType.class, getClass());
@Test
public void positiveCases() {
compilationHelper.addSourceFile("CollectionIncompatibleTypePositiveCases.java").doTest();
}
@Test
public void negativeCases() {
compilationHelper.addSourceFile("CollectionIncompatibleTypeNegativeCases.java").doTest();
}
@Test
public void outOfBounds() {
compilationHelper.addSourceFile("CollectionIncompatibleTypeOutOfBounds.java").doTest();
}
@Test
public void classCast() {
compilationHelper.addSourceFile("CollectionIncompatibleTypeClassCast.java").doTest();
}
@Test
public void castFixes() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Collection;",
"public class Test {",
" public void doIt(Collection<String> c1, Collection<Integer> c2) {",
" // BUG: Diagnostic contains: c1.contains((Object) 1);",
" c1.contains(1);",
" // BUG: Diagnostic contains: c1.containsAll((Collection<?>) c2);",
" c1.containsAll(c2);",
" }",
"}")
.setArgs(ImmutableList.of("-XepOpt:CollectionIncompatibleType:FixType=CAST"))
.doTest();
}
@Test
public void suppressWarningsFix() {
refactorTestHelper
.addInputLines(
"in/Test.java",
"import java.util.Collection;",
"public class Test {",
" public void doIt(Collection<String> c1, Collection<Integer> c2) {",
" c1.contains(1);",
" c1.containsAll(c2);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.Collection;",
"public class Test {",
" @SuppressWarnings(\"CollectionIncompatibleType\")",
// In this test environment, the fix doesn't include formatting
"public void doIt(Collection<String> c1, Collection<Integer> c2) {",
" c1.contains(/* expected: String, actual: int */ 1);",
" c1.containsAll(/* expected: String, actual: Integer */ c2);",
" }",
"}")
.setArgs("-XepOpt:CollectionIncompatibleType:FixType=SUPPRESS_WARNINGS")
.doTest(TestMode.TEXT_MATCH);
}
// This test is disabled because calling Types#asSuper in the check removes the upper bound on K.
@Test
@Ignore
public void boundedTypeParameters() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.HashMap;",
"public class Test {",
" private static class MyHashMap<K extends Integer, V extends String>",
" extends HashMap<K, V> {}",
" public boolean boundedTypeParameters(MyHashMap<?, ?> myHashMap) {",
" // BUG: Diagnostic contains:",
" return myHashMap.containsKey(\"bad\");",
" }",
"}")
.doTest();
}
@Test
public void disjoint() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Collections;",
"import java.util.List;",
"public class Test {",
" void f(List<String> a, List<String> b) {",
" Collections.disjoint(a, b);",
" }",
" void g(List<String> a, List<Integer> b) {",
" // BUG: Diagnostic contains: not compatible",
" Collections.disjoint(a, b);",
" }",
" void h(List<?> a, List<Integer> b) {",
" Collections.disjoint(a, b);",
" }",
"}")
.doTest();
}
@Test
public void difference() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Set;",
"import com.google.common.collect.Sets;",
"public class Test {",
" void f(Set<String> a, Set<String> b) {",
" Sets.difference(a, b);",
" }",
" void g(Set<String> a, Set<Integer> b) {",
" // BUG: Diagnostic contains: not compatible",
" Sets.difference(a, b);",
" }",
" void h(Set<?> a, Set<Integer> b) {",
" Sets.difference(a, b);",
" }",
"}")
.doTest();
}
@Test
public void methodReference() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"public class Test {",
" java.util.stream.Stream filter(List<Integer> xs, List<String> ss) {",
" // BUG: Diagnostic contains:",
" return xs.stream().filter(ss::contains);",
" }",
"}")
.doTest();
}
@Test
public void methodReferenceBinOp() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"public class Test {",
" void removeAll(List<List<Integer>> xs, List<String> ss) {",
" // BUG: Diagnostic contains:",
" xs.forEach(ss::removeAll);",
" }",
"}")
.doTest();
}
@Test
public void methodReference_compatibleType() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"public class Test {",
" java.util.stream.Stream filter(List<Integer> xs, List<Object> ss) {",
" return xs.stream().filter(ss::contains);",
" }",
"}")
.doTest();
}
@Test
public void memberReferenceWithBoundedGenerics() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Sets;",
"import java.util.function.BiFunction;",
"import java.util.Set;",
"public class Test {",
" <T extends String, M extends Integer> void a(",
" BiFunction<Set<T>, Set<M>, Set<T>> b) {}",
" void b() {",
" // BUG: Diagnostic contains:",
" a(Sets::difference);",
" }",
"}")
.doTest();
}
@Test
public void memberReferenceWithBoundedGenericsDependentOnEachOther() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Sets;",
"import java.util.function.BiFunction;",
"import java.util.Set;",
"public class Test {",
" <T extends String, M extends T> void a(",
" BiFunction<Set<T>, Set<M>, Set<T>> b) {}",
" void b() {",
" a(Sets::difference);",
" }",
"}")
.doTest();
}
@Test
public void memberReferenceWithConcreteIncompatibleTypes() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Sets;",
"import java.util.function.BiFunction;",
"import java.util.Set;",
"public class Test {",
" void a(BiFunction<Set<Integer>, Set<String>, Set<Integer>> b) {}",
" void b() {",
" // BUG: Diagnostic contains:",
" a(Sets::difference);",
" }",
"}")
.doTest();
}
@Test
public void memberReferenceWithConcreteCompatibleTypes() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Sets;",
"import java.util.function.BiFunction;",
"import java.util.Set;",
"public class Test {",
" void a(BiFunction<Set<Integer>, Set<Number>, Set<Integer>> b) {}",
" void b() {",
" a(Sets::difference);",
" }",
"}")
.doTest();
}
@Test
public void memberReferenceWithCustomFunctionalInterface() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.Sets;",
"import java.util.function.BiFunction;",
"import java.util.Set;",
"public interface Test {",
" Set<Integer> test(Set<Integer> a, Set<String> b);",
" static void a(Test b) {}",
" static void b() {",
" // BUG: Diagnostic contains: Integer is not compatible with String",
" a(Sets::difference);",
" }",
"}")
.doTest();
}
@Test
public void wildcardBoundedCollectionTypes() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"import java.util.Set;",
"public interface Test {",
" static void test(Set<? extends List<Integer>> xs, Set<? extends Set<Integer>> ys) {",
" // BUG: Diagnostic contains:",
" xs.containsAll(ys);",
" }",
"}")
.doTest();
}
}
| 10,499
| 32.018868
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/TruthIncompatibleTypeTest.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.collectionincompatibletype;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link TruthIncompatibleType}Test */
@RunWith(JUnit4.class)
public class TruthIncompatibleTypeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(TruthIncompatibleType.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"public class Test {",
" static final class A {}",
" static final class B {}",
" public void f(A a, B b) {",
" // BUG: Diagnostic contains:",
" assertThat(a).isEqualTo(b);",
" // BUG: Diagnostic contains:",
" assertThat(a).isNotEqualTo(b);",
" }",
"}")
.doTest();
}
@Test
public void assume() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.TruthJUnit.assume;",
"public class Test {",
" static final class A {}",
" static final class B {}",
" public void f(A a, B b) {",
" // BUG: Diagnostic contains:",
" assume().that(a).isEqualTo(b);",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"public class Test {",
" static final class A {}",
" static final class B {}",
" public void f(A a, B b) {",
" assertThat(a).isEqualTo(a);",
" assertThat(b).isEqualTo(b);",
" assertThat(\"a\").isEqualTo(\"b\");",
" }",
"}")
.doTest();
}
@Test
public void mixedNumberTypes_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"public class Test {",
" public void f() {",
" assertThat(2L).isEqualTo(2);",
" }",
"}")
.doTest();
}
@Test
public void mixedBoxedNumberTypes_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"public class Test {",
" public void f() {",
" assertThat(Byte.valueOf((byte) 2)).isEqualTo(2);",
" }",
"}")
.doTest();
}
@Test
public void chainedThrowAssertion_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"public class Test {",
" public void f(Exception e) {",
" assertThat(e).hasMessageThat().isEqualTo(\"foo\");",
" }",
"}")
.doTest();
}
@Test
public void clazz() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"public class Test {",
" public void f(Class<InterruptedException> a, Class<? extends Throwable> b) {",
" try {",
" } catch (Exception e) {",
" assertThat(e.getCause().getClass()).isEqualTo(IllegalArgumentException.class);",
" }",
" }",
"}")
.doTest();
}
@Test
public void containment() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"public class Test {",
" public void f(Iterable<Long> xs, String x) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).contains(x);",
" }",
"}")
.doTest();
}
@Test
public void containment_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"public class Test {",
" public void f(Iterable<Long> xs, Number x) {",
" assertThat(xs).contains(x);",
" }",
"}")
.doTest();
}
@Test
public void vectorContainment() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"public class Test {",
" public void f(Iterable<Long> xs, String x) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).containsExactlyElementsIn(ImmutableList.of(x));",
" }",
"}")
.doTest();
}
@Test
public void vectorContainment_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"public class Test {",
" public void f(Iterable<Long> xs, Number x) {",
" assertThat(xs).containsExactlyElementsIn(ImmutableList.of(x));",
" }",
"}")
.doTest();
}
@Test
public void variadicCall_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"public class Test {",
" public void f(Iterable<Long> xs, Number... x) {",
" assertThat(xs).containsExactly((Object[]) x);",
" }",
"}")
.doTest();
}
@Test
public void variadicCall_notActuallyAnArray_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"public class Test {",
" public void f(Iterable<Long> xs, Object x) {",
" assertThat(xs).containsExactlyElementsIn((Object[]) x);",
" }",
"}")
.doTest();
}
@Test
public void variadicCall_checked() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"public class Test {",
" public void f(Iterable<Long> xs, String... x) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).containsExactly(x);",
" }",
"}")
.doTest();
}
@Test
public void variadicCall_primitiveArray() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"public class Test {",
" public void f(Iterable<byte[]> xs, byte[] ys) {",
" assertThat(xs).containsExactly(ys);",
" }",
"}")
.doTest();
}
@Test
public void containsExactlyElementsIn_withArray_match() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"public class Test {",
" public void f(Iterable<String> xs, Object... x) {",
" assertThat(xs).containsExactlyElementsIn(x);",
" }",
"}")
.doTest();
}
@Test
public void containsExactlyElementsIn_withArray_mismatched() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"public class Test {",
" public void f(Iterable<Long> xs, String... x) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).containsExactlyElementsIn(x);",
" }",
"}")
.doTest();
}
@Test
public void containsExactlyElementsIn_numericTypes_notSpecialCased() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"public class Test {",
" public void f(Iterable<Long> xs, ImmutableList<Integer> ys) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).containsExactlyElementsIn(ys);",
" }",
"}")
.doTest();
}
@Test
public void comparingElementsUsingRawCorrespondence_noFinding() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.truth.Correspondence;",
"public class Test {",
" @SuppressWarnings(\"unchecked\")",
" public void f(Iterable<Long> xs, Correspondence c) {",
" assertThat(xs).comparingElementsUsing(c).doesNotContain(\"\");",
" }",
"}")
.doTest();
}
@Test
public void comparingElementsUsing_typeMismatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.truth.Correspondence;",
"public class Test {",
" public void f(Iterable<Long> xs, Correspondence<Integer, String> c) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).comparingElementsUsing(c).doesNotContain(\"\");",
" }",
"}")
.doTest();
}
@Test
public void comparingElementsUsing_typesMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.truth.Correspondence;",
"public class Test {",
" public void f(Iterable<Long> xs, Correspondence<Long, String> c) {",
" assertThat(xs).comparingElementsUsing(c).doesNotContain(\"\");",
" }",
"}")
.doTest();
}
@Test
public void mapContainsExactlyEntriesIn_keyTypesDiffer() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.util.Map;",
"public class Test {",
" public void f(Map<String, Long> xs, Map<Long, Long> ys) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).containsExactlyEntriesIn(ys);",
" }",
"}")
.doTest();
}
@Test
public void mapContainsExactlyEntriesIn_valueTypesDiffer() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.util.Map;",
"public class Test {",
" public void f(Map<String, Long> xs, Map<String, String> ys) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).containsExactlyEntriesIn(ys);",
" }",
"}")
.doTest();
}
@Test
public void mapContainsExactly() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.util.Map;",
"public class Test {",
" public void f(Map<String, Long> xs) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).containsExactly(\"\", 1L, \"foo\", 2L, \"bar\", 3);",
" }",
"}")
.doTest();
}
@Test
public void mapContainsExactly_varargs() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import java.util.Map;",
"public class Test {",
" public void f(Map<String, Long> xs, String a, Long b, Object... rest) {",
" assertThat(xs).containsExactly(a, b, rest);",
" }",
"}")
.doTest();
}
@Test
public void multimapContainsExactly() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.Multimap;",
"public class Test {",
" public void f(Multimap<String, Long> xs) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).containsExactly(\"\", 1L, \"foo\", 2L, \"bar\", 3);",
" }",
"}")
.doTest();
}
@Test
public void streamContainsExactly() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth8.assertThat;",
"import com.google.common.collect.Multimap;",
"import java.util.stream.Stream;",
"public class Test {",
" public void f(Stream<String> xs) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).containsExactly(1, 2);",
" }",
"}")
.doTest();
}
@Test
public void protoTruth_positiveCase() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"final class Test {",
" void test(TestFieldProtoMessage a, TestProtoMessage b) {",
" // BUG: Diagnostic contains:",
" assertThat(a).isNotEqualTo(b);",
" }",
"}")
.doTest();
}
@Test
public void protoTruth_withModifiers_positiveCase() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"final class Test {",
" void test(TestFieldProtoMessage a, TestProtoMessage b) {",
" // BUG: Diagnostic contains:",
" assertThat(a).ignoringFields(1).isNotEqualTo(b);",
" }",
"}")
.doTest();
}
@Test
public void protoTruth_contains() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"final class Test {",
" void test(Iterable<TestFieldProtoMessage> a, TestProtoMessage b) {",
" // BUG: Diagnostic contains:",
" assertThat(a).containsExactly(b);",
" }",
"}")
.doTest();
}
@Test
public void protoTruth_negativeCase() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"final class Test {",
" void test(TestFieldProtoMessage a, TestFieldProtoMessage b) {",
" assertThat(a).isNotEqualTo(b);",
" }",
"}")
.doTest();
}
@Test
public void protoTruth_comparingElementsUsinng() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.truth.Correspondence;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"public class Test {",
" public void f(",
" Iterable<TestProtoMessage> xs,",
" Correspondence<TestFieldProtoMessage, TestProtoMessage> c) {",
" // BUG: Diagnostic contains:",
" assertThat(xs).comparingElementsUsing(c)",
" .doesNotContain(TestProtoMessage.getDefaultInstance());",
" }",
"}")
.doTest();
}
@Test
public void comparingElementsUsingRawCollection_noFinding() {
compilationHelper
.addSourceLines(
"Test.java",
"import static com.google.common.truth.Truth.assertThat;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.truth.Correspondence;",
"public class Test {",
" @SuppressWarnings(\"unchecked\")",
" public void f(Iterable xs, Correspondence<Long, String> c) {",
" assertThat(xs).comparingElementsUsing(c).doesNotContain(\"\");",
" }",
"}")
.doTest();
}
}
| 19,111
| 32.946714
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/testdata/CollectionIncompatibleTypeNegativeCases.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.collectionincompatibletype.testdata;
import com.google.common.base.Optional;
import com.google.common.collect.ClassToInstanceMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Deque;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
/** Negative test cases for {@link CollectionIncompatibleType}. */
public class CollectionIncompatibleTypeNegativeCases {
/* Tests for API coverage */
public boolean collection(Collection<String> collection1, Collection<String> collection2) {
boolean result = collection1.contains("ok");
result &= collection1.contains(null);
result &= collection1.remove("ok");
result &= collection1.remove(null);
result &= collection1.containsAll(collection2);
result &= collection1.containsAll(null);
result &= collection1.removeAll(collection2);
result &= collection1.removeAll(null);
result &= collection1.retainAll(collection2);
return result && collection1.retainAll(null);
}
public boolean collectionSubtype(ArrayList<String> arrayList1, ArrayList<String> arrayList2) {
boolean result = arrayList1.contains("ok");
result &= arrayList1.contains(null);
result &= arrayList1.remove("ok");
result &= arrayList1.remove(null);
result &= arrayList1.containsAll(arrayList2);
result &= arrayList1.containsAll(null);
result &= arrayList1.removeAll(arrayList2);
result &= arrayList1.removeAll(null);
result &= arrayList1.retainAll(arrayList2);
return result && arrayList1.retainAll(null);
}
public boolean deque(Deque<String> deque) {
boolean result = deque.removeFirstOccurrence("ok");
result &= deque.removeFirstOccurrence(null);
result &= deque.removeLastOccurrence("ok");
return result && deque.removeLastOccurrence(null);
}
public boolean dequeSubtype(LinkedList<String> linkedList) {
boolean result = linkedList.removeFirstOccurrence("ok");
result &= linkedList.removeFirstOccurrence(null);
result &= linkedList.removeLastOccurrence("ok");
return result && linkedList.removeLastOccurrence(null);
}
public int dictionary(Dictionary<String, Integer> dictionary) {
int result = dictionary.get("ok");
result += dictionary.get(null);
result += dictionary.remove("ok");
return result + dictionary.remove(null);
}
public int dictionarySubtype(Hashtable<String, Integer> hashtable) {
int result = hashtable.get("ok");
result += hashtable.get(null);
result += hashtable.remove("ok");
return result + hashtable.remove(null);
}
public int list() {
List<String> list = new ArrayList<String>();
int result = list.indexOf("ok");
result += list.indexOf(null);
result += list.lastIndexOf("ok");
return result + list.lastIndexOf(null);
}
public int listSubtype() {
ArrayList<String> arrayList = new ArrayList<>();
int result = arrayList.indexOf("ok");
result += arrayList.indexOf(null);
result += arrayList.lastIndexOf("ok");
return result + arrayList.lastIndexOf(null);
}
public boolean map() {
Map<Integer, String> map = new HashMap<>();
String result = map.get(1);
result = map.getOrDefault(1, "hello");
boolean result2 = map.containsKey(1);
result2 = map.containsValue("ok");
result2 &= map.containsValue(null);
result = map.remove(1);
return result2;
}
public boolean mapSubtype() {
ConcurrentNavigableMap<Integer, String> concurrentNavigableMap = new ConcurrentSkipListMap<>();
String result = concurrentNavigableMap.get(1);
boolean result2 = concurrentNavigableMap.containsKey(1);
result2 &= concurrentNavigableMap.containsValue("ok");
result2 &= concurrentNavigableMap.containsValue(null);
result = concurrentNavigableMap.remove(1);
return result2;
}
public int stack(Stack<String> stack) {
int result = stack.search("ok");
return result + stack.search(null);
}
private static class MyStack<E> extends Stack<E> {}
public int stackSubtype(MyStack<String> myStack) {
int result = myStack.search("ok");
return result + myStack.search(null);
}
public int vector(Vector<String> vector) {
int result = vector.indexOf("ok", 0);
result += vector.indexOf(null, 0);
result += vector.lastIndexOf("ok", 0);
return result + vector.lastIndexOf(null, 0);
}
public int vectorSubtype(Stack<String> stack) {
int result = stack.indexOf("ok", 0);
result += stack.indexOf(null, 0);
result += stack.lastIndexOf("ok", 0);
return result + stack.lastIndexOf(null, 0);
}
/* Tests for behavior */
private class B extends Date {}
public boolean argTypeExtendsContainedType() {
Collection<Date> collection = new ArrayList<>();
return collection.contains(new B());
}
public boolean containedTypeExtendsArgType() {
Collection<String> collection = new ArrayList<>();
Object actuallyAString = "ok";
return collection.contains(actuallyAString);
}
public boolean boundedWildcard() {
Collection<? extends Date> collection = new ArrayList<>();
return collection.contains(new Date()) || collection.contains(new B());
}
public boolean unboundedWildcard() {
Collection<?> collection = new ArrayList<>();
return collection.contains("ok") || collection.contains(new Object());
}
public boolean rawType() {
Collection collection = new ArrayList();
return collection.contains("ok");
}
private class DoesntExtendCollection<E> {
public boolean contains(Object o) {
return true;
}
}
public boolean doesntExtendCollection() {
DoesntExtendCollection<String> collection = new DoesntExtendCollection<>();
return collection.contains(new Date());
}
private static class Pair<A, B> {
public A first;
public B second;
}
public boolean declaredTypeVsExpressionType(Pair<Integer, String> pair, List<Integer> list) {
return list.contains(pair.first);
}
public boolean containsParameterizedType(
Collection<Class<? extends String>> collection, Class<?> clazz) {
return collection.contains(clazz);
}
public boolean containsWildcard(Collection<String> collection, Optional<?> optional) {
return collection.contains(optional.get());
}
public <T extends String> T subclassHasDifferentTypeParameters(
ClassToInstanceMap<String> map, Class<T> klass) {
return klass.cast(map.get(klass));
}
// Ensure we don't match Hashtable.contains and ConcurrentHashtable.contains because there is a
// separate check, HashtableContains, specifically for them.
public boolean hashtableContains() {
Hashtable<Integer, String> hashtable = new Hashtable<>();
ConcurrentHashMap<Integer, String> concurrentHashMap = new ConcurrentHashMap<>();
return hashtable.contains(1) || concurrentHashMap.contains(1);
}
private static class MyHashMap<K extends Integer, V extends String> extends HashMap<K, V> {}
public boolean boundedTypeParameters(MyHashMap<?, ?> myHashMap) {
return myHashMap.containsKey(1);
}
interface Interface1 {}
interface Interface2 {}
private static class NonFinalClass {}
public boolean bothInterfaces(Collection<Interface1> collection, Interface2 iface2) {
return collection.contains(iface2);
}
public boolean oneInterfaceAndOneNonFinalClass(
Collection<Interface1> collection, NonFinalClass nonFinalClass) {
return collection.contains(nonFinalClass);
}
public boolean oneNonFinalClassAndOneInterface(
Collection<NonFinalClass> collection, Interface1 iface) {
return collection.contains(iface);
}
public void methodArgHasSubtypeTypeArgument(
Collection<Number> collection1, Collection<Integer> collection2) {
collection1.containsAll(collection2);
}
public void methodArgHasSuperTypeArgument(
Collection<Integer> collection1, Collection<Number> collection2) {
collection1.containsAll(collection2);
}
public void methodArgHasWildcardTypeArgument(
Collection<? extends Number> collection1, Collection<? extends Integer> collection2) {
collection1.containsAll(collection2);
}
public void methodArgCastToCollectionWildcard(
Collection<Integer> collection1, Collection<String> collection2) {
collection1.containsAll((Collection<?>) collection2);
}
public void classToken(
Set<Class<? extends Iterable<?>>> iterables, Class<ArrayList> arrayListClass) {
iterables.contains(arrayListClass);
}
}
| 9,452
| 32.402827
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/testdata/CollectionIncompatibleTypePositiveCases.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.collectionincompatibletype.testdata;
import com.google.common.collect.ClassToInstanceMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Deque;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.Vector;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
/** Positive test cases for {@link CollectionIncompatibleType}. */
public class CollectionIncompatibleTypePositiveCases {
/* Tests for API coverage */
public void collection(Collection<Integer> collection1, Collection<String> collection2) {
// BUG: Diagnostic contains: Argument '"bad"' should not be passed to this method
// its type String is not compatible with its collection's type argument Integer
collection1.contains("bad");
// BUG: Diagnostic contains:
collection1.remove("bad");
// BUG: Diagnostic contains: Argument 'collection2' should not be passed to this method
// its type Collection<String> has a type argument String that is not compatible with its
// collection's type argument Integer
collection1.containsAll(collection2);
// BUG: Diagnostic contains:
collection1.removeAll(collection2);
// BUG: Diagnostic contains:
collection1.retainAll(collection2);
}
public void collectionSubtype(ArrayList<Integer> arrayList1, ArrayList<String> arrayList2) {
// BUG: Diagnostic contains: Argument '"bad"' should not be passed to this method
// its type String is not compatible with its collection's type argument Integer
arrayList1.contains("bad");
// BUG: Diagnostic contains:
arrayList1.remove("bad");
// BUG: Diagnostic contains: Argument 'arrayList2' should not be passed to this method
// its type ArrayList<String> has a type argument String that is not compatible with its
// collection's type argument Integer
arrayList1.containsAll(arrayList2);
// BUG: Diagnostic contains:
arrayList1.removeAll(arrayList2);
// BUG: Diagnostic contains:
arrayList1.retainAll(arrayList2);
}
public boolean deque(Deque<Integer> deque) {
// BUG: Diagnostic contains:
boolean result = deque.removeFirstOccurrence("bad");
// BUG: Diagnostic contains:
return result && deque.removeLastOccurrence("bad");
}
public boolean dequeSubtype(LinkedList<Integer> linkedList) {
// BUG: Diagnostic contains:
boolean result = linkedList.removeFirstOccurrence("bad");
// BUG: Diagnostic contains:
return result && linkedList.removeLastOccurrence("bad");
}
public String dictionary(Dictionary<Integer, String> dictionary) {
// BUG: Diagnostic contains:
String result = dictionary.get("bad");
// BUG: Diagnostic contains:
return result + dictionary.remove("bad");
}
public String dictionarySubtype(Hashtable<Integer, String> hashtable) {
// BUG: Diagnostic contains:
String result = hashtable.get("bad");
// BUG: Diagnostic contains:
return result + hashtable.remove("bad");
}
public int list() {
List<String> list = new ArrayList<String>();
// BUG: Diagnostic contains:
int result = list.indexOf(1);
// BUG: Diagnostic contains:
return result + list.lastIndexOf(1);
}
public void listSubtype() {
ArrayList<String> arrayList = new ArrayList<>();
// BUG: Diagnostic contains:
int result = arrayList.indexOf(1);
// BUG: Diagnostic contains:
result = arrayList.lastIndexOf(1);
}
public boolean map() {
Map<Integer, String> map = new HashMap<>();
// BUG: Diagnostic contains:
String result = map.get("bad");
// BUG: Diagnostic contains:
result = map.getOrDefault("bad", "soBad");
// BUG: Diagnostic contains:
boolean result2 = map.containsKey("bad");
// BUG: Diagnostic contains:
result2 = map.containsValue(1);
// BUG: Diagnostic contains:
result = map.remove("bad");
return false;
}
public boolean mapSubtype() {
ConcurrentNavigableMap<Integer, String> concurrentNavigableMap = new ConcurrentSkipListMap<>();
// BUG: Diagnostic contains:
String result = concurrentNavigableMap.get("bad");
// BUG: Diagnostic contains:
boolean result2 = concurrentNavigableMap.containsKey("bad");
// BUG: Diagnostic contains:
result2 = concurrentNavigableMap.containsValue(1);
// BUG: Diagnostic contains:
result = concurrentNavigableMap.remove("bad");
return false;
}
public int stack(Stack<Integer> stack) {
// BUG: Diagnostic contains:
return stack.search("bad");
}
private static class MyStack<E> extends Stack<E> {}
public int stackSubtype(MyStack<Integer> myStack) {
// BUG: Diagnostic contains:
return myStack.search("bad");
}
public int vector(Vector<Integer> vector) {
// BUG: Diagnostic contains:
int result = vector.indexOf("bad", 0);
// BUG: Diagnostic contains:
return result + vector.lastIndexOf("bad", 0);
}
public int vectorSubtype(Stack<Integer> stack) {
// BUG: Diagnostic contains:
int result = stack.indexOf("bad", 0);
// BUG: Diagnostic contains:
return result + stack.lastIndexOf("bad", 0);
}
/* Tests for behavior */
public boolean errorMessageUsesSimpleNames(Collection<Integer> collection) {
// BUG: Diagnostic contains: Argument '"bad"' should not be passed to this method
// its type String is not compatible with its collection's type argument Integer
return collection.contains("bad");
}
private static class Date {}
public boolean errorMessageUsesFullyQualifedNamesWhenSimpleNamesAreTheSame(
Collection<java.util.Date> collection1, Collection<Date> collection2) {
// BUG: Diagnostic contains: Argument 'new Date()' should not be passed to this method
// its type
// com.google.errorprone.bugpatterns.collectionincompatibletype.testdata.CollectionIncompatibleTypePositiveCases.Date is not compatible with its collection's type argument java.util.Date
return collection1.contains(new Date());
}
public boolean boundedWildcard() {
Collection<? extends Date> collection = new ArrayList<>();
// BUG: Diagnostic contains:
return collection.contains("bad");
}
private static class Pair<A, B> {
public A first;
public B second;
}
public boolean declaredTypeVsExpressionType(Pair<Integer, String> pair, List<Integer> list) {
// BUG: Diagnostic contains:
return list.contains(pair.second);
}
public String subclassHasDifferentTypeParameters(ClassToInstanceMap<String> map, String s) {
// BUG: Diagnostic contains:
return map.get(s);
}
private static class MyArrayList extends ArrayList<Integer> {}
public void methodArgumentIsSubclassWithDifferentTypeParameters(
Collection<String> collection, MyArrayList myArrayList) {
// BUG: Diagnostic contains:
collection.containsAll(myArrayList);
}
private static class IncompatibleBounds<K extends String, V extends Number> {
private boolean function(Map<K, V> map, K key) {
// BUG: Diagnostic contains:
return map.containsValue(key);
}
}
interface Interface {}
private static final class FinalClass1 {}
private static final class FinalClass2 {}
private static class NonFinalClass1 {}
private static class NonFinalClass2 {}
public boolean oneInterfaceAndOneFinalClass(
Collection<Interface> collection, FinalClass1 finalClass1) {
// BUG: Diagnostic contains:
return collection.contains(finalClass1);
}
public boolean oneFinalClassAndOneInterface(Collection<FinalClass1> collection, Interface iface) {
// BUG: Diagnostic contains:
return collection.contains(iface);
}
public boolean bothNonFinalClasses(
Collection<NonFinalClass1> collection, NonFinalClass2 nonFinalClass2) {
// BUG: Diagnostic contains:
return collection.contains(nonFinalClass2);
}
public boolean bothFinalClasses(Collection<FinalClass1> collection, FinalClass2 finalClass2) {
// BUG: Diagnostic contains:
return collection.contains(finalClass2);
}
public boolean oneNonFinalClassAndOneFinalClass(
Collection<NonFinalClass1> collection, FinalClass1 finalClass1) {
// BUG: Diagnostic contains:
return collection.contains(finalClass1);
}
public boolean oneFinalClassAndOneNonFinalClass(
Collection<FinalClass1> collection, NonFinalClass1 nonFinalClass1) {
// BUG: Diagnostic contains:
return collection.contains(nonFinalClass1);
}
}
| 9,267
| 33.58209
| 190
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/testdata/IncompatibleArgumentTypeIntersectionTypes.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.collectionincompatibletype.testdata;
import com.google.errorprone.annotations.CompatibleWith;
/** Test intersection types. */
public class IncompatibleArgumentTypeIntersectionTypes {
interface Nothing {}
interface Something {}
interface Everything extends Nothing, Something {}
class Test<X extends Nothing & Something> {
void doSomething(@CompatibleWith("X") Object whatever) {}
}
class ArrayTest<X> {
void doSomething(@CompatibleWith("X") Object whatever) {}
}
void testStuff(Test<Everything> someTest, Everything[] everythings, Nothing nothing) {
// Final classes (Integer) can't be cast to an interface they don't implement
// BUG: Diagnostic contains: int is not compatible with the required type: Everything
someTest.doSomething(123);
// Non-final classes can.
someTest.doSomething((Object) 123);
// Arrays can't, since they can only be cast to Serializable
// BUG: Diagnostic contains: Everything[] is not compatible with the required type: Everything
someTest.doSomething(everythings);
// BUG: Diagnostic contains: Everything[][] is not compatible with the required type: Everything
someTest.doSomething(new Everything[][] {everythings});
// OK (since some other implementer of Nothing could implement Everything)
someTest.doSomething(nothing);
}
void testArraySpecialization(
ArrayTest<Number[]> arrayTest, Integer[] ints, Object[] objz, String[] strings) {
arrayTest.doSomething(ints);
arrayTest.doSomething(objz);
// BUG: Diagnostic contains: String[] is not compatible with the required type: Number[]
arrayTest.doSomething(strings);
}
}
| 2,316
| 33.58209
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/testdata/CollectionIncompatibleTypeOutOfBounds.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.collectionincompatibletype.testdata;
import java.util.Properties;
/** This is a regression test for Issue 222. */
public class CollectionIncompatibleTypeOutOfBounds {
public void test() {
Properties properties = new Properties();
properties.get("");
}
}
| 919
| 31.857143
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/testdata/IncompatibleArgumentTypeEnclosingTypes.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.collectionincompatibletype.testdata;
import com.google.errorprone.annotations.CompatibleWith;
import java.util.Set;
/** Test case for enclosing type */
public class IncompatibleArgumentTypeEnclosingTypes {
static class Foo<Y> {
class Bar {
void doSomething(@CompatibleWith("Y") Object x) {}
}
class Sub<X> {
class SubSub<X> {
void doSomething(@CompatibleWith("X") Object nestedResolution) {}
<X> X methodVarIsReturn(@CompatibleWith("X") Object nestedResolution) {
return null;
}
<X> void methodVarIsFree(@CompatibleWith("X") Object nestedResolution) {}
void compatibleWithBase(@CompatibleWith("Y") Object nestedResolution) {}
}
}
static class Baz {
// Shouldn't resolve to anything, would be a compile error due to CompatibleWithMisuse
static void doSomething(@CompatibleWith("X") Object x) {}
}
}
void testSubs() {
new Foo<String>().new Bar().doSomething("a");
// BUG: Diagnostic contains: int is not compatible with the required type: String
new Foo<String>().new Bar().doSomething(123);
new Foo<Integer>().new Bar().doSomething(123);
Foo.Bar rawtype = new Foo<String>().new Bar();
rawtype.doSomething(123); // Weakness, rawtype isn't specialized in Foo
Foo.Baz.doSomething(123); // No resolution of X
}
void testMegasub() {
new Foo<String>().new Sub<Integer>().new SubSub<Boolean>().doSomething(true);
// BUG: Diagnostic contains: int is not compatible with the required type: Boolean
new Foo<String>().new Sub<Integer>().new SubSub<Boolean>().doSomething(123);
// X in method is unbound
new Foo<String>().new Sub<Integer>().new SubSub<Boolean>().methodVarIsReturn(123);
// BUG: Diagnostic contains: int is not compatible with the required type: Set<?>
new Foo<String>().new Sub<Integer>().new SubSub<Boolean>().<Set<?>>methodVarIsReturn(123);
// BUG: Diagnostic contains: int is not compatible with the required type: String
new Foo<String>().new Sub<Integer>().new SubSub<Boolean>().<Set<?>>compatibleWithBase(123);
}
void extraStuff() {
// Javac throws away the type of <X> since it's not used in params/return type, so we can't
// enforce it here.
new Foo<String>().new Sub<Integer>().new SubSub<Boolean>().<Set<?>>methodVarIsFree(123);
}
}
| 3,010
| 35.719512
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/testdata/IncompatibleArgumentTypeGenericMethod.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.collectionincompatibletype.testdata;
import com.google.errorprone.annotations.CompatibleWith;
/** Test IncompatibleArgumentType with a generic method */
public class IncompatibleArgumentTypeGenericMethod {
class A<B> {
<C> C remove(@CompatibleWith("B") Object b, @CompatibleWith("C") Object c) {
return null;
}
<C> C varargs(@CompatibleWith("B") Object b, @CompatibleWith("C") Object... cs) {
return (C) cs[0];
}
}
class C extends A<String> {}
void testfoo(C c, A<?> unbound, A<? extends Number> boundToNumber) {
c.remove("a", null); // OK, match null to Double
c.remove("a", 123.0); // OK, match Double to Double
c.remove("a", 123); // OK, 2nd arg is unbound
unbound.remove(null, 123); // OK, variables unbound
// BUG: Diagnostic contains: String is not compatible with the required type: Number
boundToNumber.remove("123", null);
// BUG: Diagnostic contains: int is not compatible with the required type: Double
Double d = c.remove("a", 123);
// BUG: Diagnostic contains: int is not compatible with the required type: Double
c.<Double>remove("a", 123);
// BUG: Diagnostic contains: float is not compatible with the required type: Double
c.<Double>remove(123, 123.0f);
}
void testVarargs(A<String> stringA) {
// OK, all varargs elements compatible with Integer
Integer first = stringA.varargs("hi", 2, 3, 4);
// BUG: Diagnostic contains: long is not compatible with the required type: Integer
first = stringA.varargs("foo", 2, 3L);
// OK, everything compatible w/ Object
Object o = stringA.varargs("foo", 2L, 1.0d, "a");
}
}
| 2,303
| 34.446154
| 88
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/testdata/CollectionIncompatibleTypeClassCast.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.collectionincompatibletype.testdata;
import java.util.HashMap;
/** This is a regression test for Issue 222. */
public class CollectionIncompatibleTypeClassCast<K, V> extends HashMap<K, V> {
public void test(K k) {
get(k);
}
}
| 887
| 31.888889
| 78
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/testdata/IncompatibleArgumentTypeMultimapIntegration.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.collectionincompatibletype.testdata;
import com.google.errorprone.annotations.CompatibleWith;
/** Integration test testing a hypothetical multimap interface */
public class IncompatibleArgumentTypeMultimapIntegration {
interface Multimap<K, V> {
boolean containsKey(@CompatibleWith("K") Object key);
boolean containsValue(@CompatibleWith("V") Object value);
boolean containsEntry(@CompatibleWith("K") Object key, @CompatibleWith("V") Object value);
boolean containsAllKeys(@CompatibleWith("K") Object key, Object... others);
}
class MyMultimap<K, V> implements Multimap<K, V> {
@Override
public boolean containsKey(Object key) {
return false;
}
@Override
public boolean containsValue(Object value) {
return false;
}
@Override
public boolean containsEntry(Object key, Object value) {
return false;
}
@Override
public boolean containsAllKeys(Object key, Object... keys) {
return false;
}
}
void testRegularValid(Multimap<Integer, String> intToString) {
intToString.containsKey(123);
intToString.containsEntry(123, "abc");
intToString.containsValue("def");
// 0-entry vararg doesn't crash
intToString.containsAllKeys(123);
}
static <K extends Number, V extends String> void testIncompatibleWildcards(
Multimap<? extends K, ? extends V> map, K key, V value) {
map.containsKey(key);
map.containsValue(value);
map.containsEntry(key, value);
// BUG: Diagnostic contains: V is not compatible with the required type: K
map.containsEntry(value, key);
// BUG: Diagnostic contains: K is not compatible with the required type: V
map.containsValue(key);
// BUG: Diagnostic contains: V is not compatible with the required type: K
map.containsKey(value);
}
void testVarArgs(Multimap<Integer, String> intToString) {
// Validates the first, not the varags params
intToString.containsAllKeys(123, 123, 123);
// TODO(glorioso): If we make it work with varargs, this should fail
intToString.containsAllKeys(123, 123, "a");
Integer[] keys = {123, 345};
intToString.containsAllKeys(123, (Object[]) keys);
}
}
| 2,845
| 31.712644
| 94
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/ParcelableCreatorTest.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.android;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link ParcelableCreator}.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@RunWith(JUnit4.class)
public class ParcelableCreatorTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ParcelableCreator.class, getClass())
.addSourceFile("testdata/stubs/android/os/Parcel.java")
.addSourceFile("testdata/stubs/android/os/Parcelable.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void positive() {
compilationHelper.addSourceFile("ParcelableCreatorPositiveCases.java").doTest();
}
@Test
public void negative() {
compilationHelper.addSourceFile("ParcelableCreatorNegativeCases.java").doTest();
}
}
| 1,600
| 32.354167
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/MislabeledAndroidStringTest.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.android;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author kmb@google.com (Kevin Bierhoff)
*/
@RunWith(JUnit4.class)
public class MislabeledAndroidStringTest {
@Test
public void matchFullyQualified() {
createCompilationTestHelper()
.addSourceLines(
"com/google/errorprone/bugpatterns/android/MatchFullyQualifiedTest.java",
"package com.google.errorprone.bugpatterns.android;",
"public class MatchFullyQualifiedTest {",
" public int getStringId() {",
" // BUG: Diagnostic contains: android.R.string.ok",
" // android.R.string.yes is not \"Yes\" but \"OK\"; prefer android.R.string.ok",
" return android.R.string.yes;",
" }",
"}")
.doTest();
}
@Test
public void matchWithImport() {
createCompilationTestHelper()
.addSourceLines(
"com/google/errorprone/bugpatterns/android/MatchWithImportTest.java",
"package com.google.errorprone.bugpatterns.android;",
"import android.R;",
"public class MatchWithImportTest {",
" public int getStringId() {",
" // BUG: Diagnostic contains: R.string.cancel",
" // android.R.string.no is not \"No\" but \"Cancel\";",
" // prefer android.R.string.cancel",
" return R.string.no;",
" }",
"}")
.doTest();
}
@Test
public void useInField() {
createCompilationTestHelper()
.addSourceLines(
"com/google/errorprone/bugpatterns/android/MatchUseInFieldTest.java",
"package com.google.errorprone.bugpatterns.android;",
"public class MatchUseInFieldTest {",
" // BUG: Diagnostic contains: android.R.string.ok",
" // android.R.string.yes is not \"Yes\" but \"OK\"; prefer android.R.string.ok",
" private static final int SAY_YES = android.R.string.yes;",
"}")
.doTest();
}
@Test
public void negativeCase() {
createCompilationTestHelper()
.addSourceLines(
"com/google/errorprone/bugpatterns/android/FineStringTest.java",
"package com.google.errorprone.bugpatterns.android;",
"import android.R;",
"public class FineStringTest {",
" public int getStringId() {",
" return R.string.copy;",
" }",
"}")
.doTest();
}
/**
* Ensures that {@link MislabeledAndroidString#ASSUMED_MEANINGS} is complete, which is important
* for generating readable diagnostic messages.
*/
@Test
public void assumedMeanings() {
for (Map.Entry<String, String> label : MislabeledAndroidString.MISLEADING.entrySet()) {
assertThat(MislabeledAndroidString.ASSUMED_MEANINGS).containsKey(label.getKey());
assertThat(MislabeledAndroidString.ASSUMED_MEANINGS).containsKey(label.getValue());
}
}
private CompilationTestHelper createCompilationTestHelper() {
return CompilationTestHelper.newInstance(MislabeledAndroidString.class, getClass())
.addSourceFile("testdata/stubs/android/R.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
}
}
| 4,137
| 34.982609
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/HardCodedSdCardPathTest.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.android;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author avenet@google.com (Arnaud J. Venet)
*/
@RunWith(JUnit4.class)
public class HardCodedSdCardPathTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(HardCodedSdCardPath.class, getClass());
@Test
public void matchingCode_onAndroid() {
compilationHelper
.setArgs(ImmutableList.of("-XDandroidCompatible=true"))
.addSourceFile("HardCodedSdCardPathPositiveCases.java")
.doTest();
}
@Test
public void matchingCode_notOnAndroid() {
compilationHelper
.setArgs(ImmutableList.of("-XDandroidCompatible=false"))
.addSourceLines(
"HardCodedSdCardPathMatchingCode.java",
"public class HardCodedSdCardPathMatchingCode {",
" static final String PATH1 = \"/sdcard\";",
"}")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.setArgs(ImmutableList.of("-XDandroidCompatible=true"))
.addSourceFile("HardCodedSdCardPathNegativeCases.java")
.doTest();
}
}
| 1,921
| 30.508197
| 79
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/BinderIdentityRestoredDangerouslyTest.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.android;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author pvisontay@google.com
*/
@RunWith(JUnit4.class)
public final class BinderIdentityRestoredDangerouslyTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(BinderIdentityRestoredDangerously.class, getClass())
.addSourceFile("testdata/stubs/android/os/Binder.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void releasedInFinallyBlock_shouldBeOkay() {
compilationHelper
.addSourceLines(
"InFinally.java",
"import android.os.Binder;",
"public class InFinally {",
" void foo() {",
" long identity = Binder.clearCallingIdentity();",
" try {",
" // Do something (typically Binder IPC) ",
" } finally {",
" Binder.restoreCallingIdentity(identity);",
" }",
" }",
"}")
.doTest();
}
@Test
public void releasedInFinallyBlock_shouldWarn() {
compilationHelper
.addSourceLines(
"InFinally.java",
"import android.os.Binder;",
"public class InFinally {",
" void foo() {",
" long identity = Binder.clearCallingIdentity();",
" // Do something (typically Binder IPC) ",
" // BUG: Diagnostic contains: Binder.restoreCallingIdentity() in a finally block",
" Binder.restoreCallingIdentity(identity);",
" }",
"}")
.doTest();
}
}
| 2,428
| 32.736111
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/IsLoggableTagLengthTest.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.android;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author epmjohnston@google.com (Emily P.M. Johnston)
*/
@RunWith(JUnit4.class)
public final class IsLoggableTagLengthTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(IsLoggableTagLength.class, getClass())
.addSourceFile("testdata/stubs/android/util/Log.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void negativeCaseLiteral() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.util.Log;",
"class Test {",
" public void log() { Log.isLoggable(\"SHORT_ENOUGH\", Log.INFO); }",
"}")
.doTest();
}
@Test
public void positiveCaseLiteral() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.util.Log;",
"class Test {",
" // BUG: Diagnostic contains: IsLoggableTagLength",
" public void log() { Log.isLoggable(\"THIS_TAG_NAME_IS_WAY_TOO_LONG\", Log.INFO); }",
"}")
.doTest();
}
@Test
public void negativeCaseLiteralUnicode() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.util.Log;",
"class Test {",
" public void log() { Log.isLoggable(\"🚀🚀🚀🚀\", Log.INFO); }",
"}")
.doTest();
}
@Test
public void positiveCaseLiteralUnicode() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.util.Log;",
"class Test {",
" // BUG: Diagnostic contains: IsLoggableTagLength",
" public void log() { Log.isLoggable(\"☔☔☔☔☔☔☔☔☔☔☔☔\", Log.INFO); }",
"}")
.doTest();
}
@Test
public void negativeCaseFinalField() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.util.Log;",
"class Test {",
" static final String TAG = \"SHORT_ENOUGH\";",
" public void log() { Log.isLoggable(TAG, Log.INFO); }",
"}")
.doTest();
}
@Test
public void positiveCaseFinalField() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.util.Log;",
"class Test {",
" static final String TAG = \"THIS_TAG_NAME_IS_WAY_TOO_LONG\";",
" // BUG: Diagnostic contains: IsLoggableTagLength",
" public void log() { Log.isLoggable(TAG, Log.INFO); }",
"}")
.doTest();
}
@Test
public void negativeCaseClassName() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.util.Log;",
"class Test {",
" public void log() { Log.isLoggable(Test.class.getSimpleName(), Log.INFO); }",
"}")
.doTest();
}
@Test
public void positiveCaseClassName() {
compilationHelper
.addSourceLines(
"ThisClassNameIsWayTooLong.java",
"import android.util.Log;",
"class ThisClassNameIsWayTooLong {",
" public void log() {",
" // BUG: Diagnostic contains: IsLoggableTagLength",
" Log.isLoggable(ThisClassNameIsWayTooLong.class.getSimpleName(), Log.INFO);",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseFinalFieldClassName() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.util.Log;",
"class Test {",
" static final String TAG = Test.class.getSimpleName();",
" public void log() {",
" Log.isLoggable(TAG, Log.INFO);",
" }",
"}")
.doTest();
}
@Test
public void positiveCaseFinalFieldClassName() {
compilationHelper
.addSourceLines(
"ThisClassNameIsWayTooLong.java",
"import android.util.Log;",
"class ThisClassNameIsWayTooLong {",
" static final String TAG = ThisClassNameIsWayTooLong.class.getSimpleName();",
" public void log() {",
" // BUG: Diagnostic contains: IsLoggableTagLength",
" Log.isLoggable(TAG, Log.INFO);",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseNonFinalFieldUninitialized() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.util.Log;",
"class Test {",
" String unknownValue;",
" public void log() { Log.isLoggable(unknownValue, Log.INFO); }",
"}")
.doTest();
}
@Test
public void negativeCaseNonFinalFieldClassNameTooLong() {
compilationHelper
.addSourceLines(
"ThisClassNameIsWayTooLong.java",
"import android.util.Log;",
"class ThisClassNameIsWayTooLong {",
" String TAG = ThisClassNameIsWayTooLong.class.getSimpleName();",
" public void log() {",
" Log.isLoggable(TAG, Log.INFO);",
" }",
"}")
.doTest();
}
}
| 6,068
| 29.497487
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/WakelockReleasedDangerouslyTest.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.android;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author epmjohnston@google.com
*/
@RunWith(JUnit4.class)
public class WakelockReleasedDangerouslyTest {
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(WakelockReleasedDangerously.class, getClass())
.setArgs(ImmutableList.of("-XDandroidCompatible=true"))
.addInput("testdata/stubs/android/os/PowerManager.java")
.expectUnchanged();
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(WakelockReleasedDangerously.class, getClass())
.addSourceFile("testdata/stubs/android/os/PowerManager.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void dangerousWakelockRelease_refactoring() {
refactoringHelper
.addInputLines(
"in/TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" if (wakelock.isHeld()) {",
" doSomethingElse();",
" wakelock.release();",
"",
" // Make sure comments are preserved",
" }",
" }",
" void doSomethingElse() {}",
"}")
.addOutputLines(
"out/TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" doSomethingElse();",
" try {",
" wakelock.release();",
" } catch (RuntimeException unused) {",
" // Ignore: wakelock already released by timeout.",
" // TODO: Log this exception.",
" }",
"",
" // Make sure comments are preserved",
" }",
" void doSomethingElse() {}",
"}")
.doTest();
// TODO(b/33069946): use TestMode.TEXT_MATCH to check comment is preserved.
}
@Test
public void doesNotRemoveIsHeldOnDifferentSymbol() {
refactoringHelper
.addInputLines(
"in/TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wl1, WakeLock wl2) {",
" wl1.acquire(100);",
" if (wl2.isHeld()) {",
" wl1.release();",
" }",
" }",
"}")
.addOutputLines(
"out/TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wl1, WakeLock wl2) {",
" wl1.acquire(100);",
" if (wl2.isHeld()) {",
" try {",
" wl1.release();",
" } catch (RuntimeException unused) {",
" // Ignore: wakelock already released by timeout.",
" // TODO: Log this exception.",
" }",
" }",
" }",
"}")
.doTest();
}
@Test
public void dangerousWakelockRelease_lambda_refactoring() {
refactoringHelper
.addInputLines(
"in/TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" doThing(() -> wakelock.release());",
" }",
" void doThing(Runnable thing) {}",
"}")
.addOutputLines(
"out/TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" doThing(() -> {",
" try {",
" wakelock.release();",
" } catch (RuntimeException unused) {",
" // Ignore: wakelock already released by timeout.",
" // TODO: Log this exception.",
" }",
" });",
" }",
" void doThing(Runnable thing) {}",
"}")
.doTest();
}
@Test
public void acquiredWithoutTimeout_shouldBeOkay() {
compilationHelper
.addSourceLines(
"WithoutTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class WithoutTimeout {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire();",
" wakelock.release();",
" }",
"}")
.doTest();
}
@Test
public void catchesRuntimeException_shouldBeOkay() {
compilationHelper
.addSourceLines(
"TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" try {",
" wakelock.release();",
" } catch (RuntimeException e) {}",
" }",
"}")
.doTest();
}
@Test
public void noCatch_shouldWarn() {
compilationHelper
.addSourceLines(
"TestApp.java",
"import android.os.PowerManager.WakeLock;",
"import java.io.BufferedReader;",
"import java.io.FileReader;",
"import java.io.IOException;",
"public class TestApp {",
" void foo(WakeLock wakelock) throws IOException {",
" wakelock.acquire(100);",
// try-with-resources so catch block is optional.
" try (BufferedReader br = new BufferedReader(new FileReader(\"\"))) {",
" // BUG: Diagnostic contains: Wakelock",
" wakelock.release();",
" }",
" }",
"}")
.doTest();
}
@Test
public void catchesSuperclassOfRuntimeException_shouldBeOkay() {
compilationHelper
.addSourceLines(
"TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" try {",
" wakelock.release();",
" } catch (Exception e) {}",
" }",
"}")
.doTest();
}
@Test
public void catchesSubclassOfRuntimeException_shouldWarn() {
compilationHelper
.addSourceLines(
"MyRuntimeException.java",
"public class MyRuntimeException extends RuntimeException {}")
.addSourceLines(
"TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" try {",
" // BUG: Diagnostic contains: Wakelock",
" wakelock.release();",
" } catch (MyRuntimeException e) {}",
" }",
"}")
.doTest();
}
@Test
public void catchesOtherException_shouldWarn() {
compilationHelper
.addSourceLines(
"MyOtherException.java", "public class MyOtherException extends Exception {}")
.addSourceLines(
"TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" try {",
" // BUG: Diagnostic contains: Wakelock",
" wakelock.release();",
" throw new MyOtherException();",
" } catch (MyOtherException e) {}",
" }",
"}")
.doTest();
}
@Test
public void nestedCatch_shouldWarn() {
compilationHelper
.addSourceLines(
"MyOtherException.java", "public class MyOtherException extends Exception {}")
.addSourceLines(
"TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" try {",
" try {",
" // BUG: Diagnostic contains: Wakelock",
" wakelock.release();",
" throw new MyOtherException();",
" } catch (MyOtherException e) {}",
" } catch (RuntimeException err) {}",
" }",
"}")
.doTest();
}
@Test
public void catchesUnion_withRuntimeException_shouldBeOkay() {
compilationHelper
.addSourceLines(
"MyOtherException.java", "public class MyOtherException extends Exception {}")
.addSourceLines(
"TestApp.java",
"import android.os.PowerManager.WakeLock;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" try {",
" wakelock.release();",
" throw new MyOtherException();",
" } catch (RuntimeException|MyOtherException e) {}",
" }",
"}")
.doTest();
}
@Test
public void catchesUnion_withLeastUpperBoundException_shouldWarn() {
compilationHelper
.addSourceLines(
"TestApp.java",
"import android.os.PowerManager.WakeLock;",
"import java.io.IOException;",
"public class TestApp {",
" void foo(WakeLock wakelock) {",
" wakelock.acquire(100);",
" try {",
" // BUG: Diagnostic contains: Wakelock",
" wakelock.release();",
" throw new IOException();",
" } catch (IOException | NullPointerException e) {",
" // union with a 'least upper bound' of Exception, won't catch RuntimeException.",
" }",
" }",
"}")
.doTest();
}
@Test
public void acquiredElsewhere_shouldBeRecognized() {
compilationHelper
.addSourceLines(
"WithTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class WithTimeout {",
" WakeLock wakelock;",
" WithTimeout(WakeLock wl) {",
" this.wakelock = wl;",
" this.wakelock.acquire(100);",
" }",
" void foo() {",
" // BUG: Diagnostic contains: Wakelock",
" wakelock.release();",
" }",
"}")
.addSourceLines(
"WithoutTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class WithoutTimeout {",
" WakeLock wakelock;",
" WithoutTimeout(WakeLock wl) {",
" this.wakelock = wl;",
" this.wakelock.acquire();",
" }",
" void foo() {",
" wakelock.release();",
" }",
"}")
.doTest();
}
@Test
public void differentWakelock_shouldNotBeRecognized() {
compilationHelper
.addSourceLines(
"WithTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class WithTimeout {",
" void bar(WakeLock wakelock) {",
" wakelock.acquire(100);",
" }",
" void foo(WakeLock wakelock) {",
" wakelock.release();",
" }",
"}")
.addSourceLines(
"WithoutTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class WithoutTimeout {",
" void bar(WakeLock wakelock) {",
" wakelock.acquire();",
" }",
" void foo(WakeLock wakelock) {",
" wakelock.release();",
" }",
"}")
.doTest();
}
@Test
public void wakelockFromMethod() {
compilationHelper
.addSourceLines(
"WithTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class WithTimeout {",
" WakeLock wakelock;",
" WakeLock getWakelock() { return wakelock; }",
" void bar() {",
" getWakelock().acquire(100);",
" }",
" void foo() {",
" // BUG: Diagnostic contains: Wakelock",
" getWakelock().release();",
" }",
"}")
.addSourceLines(
"WithoutTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class WithoutTimeout {",
" WakeLock wakelock;",
" WakeLock getWakelock() { return wakelock; }",
" void bar(WakeLock wakelock) {",
" getWakelock().acquire();",
" }",
" void foo(WakeLock wakelock) {",
" getWakelock().release();",
" }",
"}")
.doTest();
}
@Test
public void wakelockNotReferenceCounted_shouldBeOkay() {
compilationHelper
.addSourceLines(
"NotReferenceCountedTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class NotReferenceCountedTimeout {",
" void foo(WakeLock wakelock) {",
" wakelock.setReferenceCounted(false);",
" wakelock.acquire(100);",
" wakelock.release();",
" }",
"}")
.addSourceLines(
"ExplicitlyReferenceCountedTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class ExplicitlyReferenceCountedTimeout {",
" void foo(WakeLock wakelock) {",
" wakelock.setReferenceCounted(true);",
" wakelock.acquire(100);",
" // BUG: Diagnostic contains: Wakelock",
" wakelock.release();",
" }",
"}")
.addSourceLines(
"NotReferenceCountedNoTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class NotReferenceCountedNoTimeout {",
" void foo(WakeLock wakelock) {",
" wakelock.setReferenceCounted(false);",
" wakelock.acquire();",
" wakelock.release();",
" }",
"}")
.addSourceLines(
"ExplicitlyReferenceCountedNoTimeout.java",
"import android.os.PowerManager.WakeLock;",
"public class ExplicitlyReferenceCountedNoTimeout {",
" void foo(WakeLock wakelock) {",
" wakelock.setReferenceCounted(true);",
" wakelock.acquire();",
" wakelock.release();",
" }",
"}")
.doTest();
}
@Test
public void innerClass_negative() {
compilationHelper
.addSourceLines(
"OuterClass.java",
"import android.os.PowerManager.WakeLock;",
"public class OuterClass {",
" WakeLock wakelock;",
" OuterClass(WakeLock wl) {",
" this.wakelock = wl;",
" this.wakelock.setReferenceCounted(false);",
" }",
" public class InnerClass {",
" void foo() {",
" wakelock.acquire(100);",
" wakelock.release();",
" }",
" }",
"}")
.doTest();
}
@Test
public void innerClass_positive() {
compilationHelper
.addSourceLines(
"OuterClass.java",
"import android.os.PowerManager.WakeLock;",
"public class OuterClass {",
" WakeLock wakelock;",
" OuterClass(WakeLock wl) {",
" wakelock = wl;",
" wakelock.acquire(100);",
" }",
" public class InnerClass {",
" void foo() {",
" // BUG: Diagnostic contains: Wakelock",
" wakelock.release();",
" }",
" }",
"}")
.doTest();
}
}
| 17,416
| 33.084149
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/FragmentNotInstantiableTest.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.android;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author avenet@google.com (Arnaud J. Venet)
*/
@RunWith(JUnit4.class)
public class FragmentNotInstantiableTest {
/** Used for testing a custom FragmentNotInstantiable. */
@BugPattern(
summary =
"Subclasses of CustomFragment must be instantiable via Class#newInstance():"
+ " the class must be public, static and have a public nullary constructor",
severity = WARNING)
public static class CustomFragmentNotInstantiable extends FragmentNotInstantiable {
public CustomFragmentNotInstantiable() {
super(ImmutableSet.of("com.google.errorprone.bugpatterns.android.testdata.CustomFragment"));
}
}
@Test
public void positiveCases() {
createCompilationTestHelper(FragmentNotInstantiable.class)
.addSourceFile("FragmentNotInstantiablePositiveCases.java")
.doTest();
}
@Test
public void negativeCase() {
createCompilationTestHelper(FragmentNotInstantiable.class)
.addSourceFile("FragmentNotInstantiableNegativeCases.java")
.doTest();
}
@Test
public void positiveCases_custom() {
createCompilationTestHelper(CustomFragmentNotInstantiable.class)
.addSourceFile("FragmentNotInstantiablePositiveCases.java")
.addSourceFile("CustomFragment.java")
.addSourceFile("CustomFragmentNotInstantiablePositiveCases.java")
.doTest();
}
@Test
public void negativeCase_custom() {
createCompilationTestHelper(CustomFragmentNotInstantiable.class)
.addSourceFile("FragmentNotInstantiableNegativeCases.java")
.addSourceFile("CustomFragment.java")
.addSourceFile("CustomFragmentNotInstantiableNegativeCases.java")
.doTest();
}
private CompilationTestHelper createCompilationTestHelper(
Class<? extends FragmentNotInstantiable> bugCheckerClass) {
return CompilationTestHelper.newInstance(bugCheckerClass, getClass())
.addSourceFile("testdata/stubs/android/app/Fragment.java")
.addSourceFile("testdata/stubs/android/support/v4/app/Fragment.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
}
}
| 3,128
| 35.383721
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/FragmentInjectionTest.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.android;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author epmjohnston@google.com (Emily P.M. Johnston)
*/
@RunWith(JUnit4.class)
public final class FragmentInjectionTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(FragmentInjection.class, getClass())
.addSourceFile("testdata/stubs/android/preference/PreferenceActivity.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void isValidFragmentNotImplementedOnPreferenceActivity() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"// BUG: Diagnostic contains: does not implement isValidFragment",
"class MyPrefActivity extends PreferenceActivity {}")
.doTest();
}
@Test
public void methodNamedIsValidFragmentButDoesNotOverride() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"// BUG: Diagnostic contains: does not implement isValidFragment",
"class MyPrefActivity extends PreferenceActivity {",
" protected boolean isValidFragment(String fragment, String unused) {",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void isValidFragmentTriviallyImplemented() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MyPrefActivity extends PreferenceActivity {",
" // BUG: Diagnostic contains: isValidFragment unconditionally returns true",
" protected boolean isValidFragment(String fragment) {",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void isValidFragmentReturnsConstantField() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MyPrefActivity extends PreferenceActivity {",
" static final boolean known = true;",
" // BUG: Diagnostic contains: isValidFragment unconditionally returns true",
" protected boolean isValidFragment(String fragment) {",
" return known;",
" }",
"}")
.doTest();
}
@Test
public void isValidFragmentReturnsFalse() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MyPrefActivity extends PreferenceActivity {",
" protected boolean isValidFragment(String fragment) {",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void isValidFragmentReturnsBoxedTrue() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MyPrefActivity extends PreferenceActivity {",
" protected boolean isValidFragment(String fragment) {",
" return Boolean.valueOf(true);", // No warning, not a compile time constant.
" }",
"}")
.doTest();
}
@Test
public void isValidFragmentReturnsVariable() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MyPrefActivity extends PreferenceActivity {",
" boolean unknown;",
" protected boolean isValidFragment(String fragment) {",
" return unknown;",
" }",
"}")
.doTest();
}
@Test
public void isValidFragmentFullyImplemented() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MyPrefActivity extends PreferenceActivity {",
" protected boolean isValidFragment(String fragment) {",
" if (\"VALID_FRAGMENT\".equals(fragment)) {",
" return true;",
" }",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void methodWithSameSignatureImplementedOnOtherClass() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"class MyPrefActivity {",
" protected boolean isValidFragment(String fragment) {",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void isValidFragmentImplementedOnSuperClass() {
compilationHelper
.addSourceLines(
"MySuperPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MySuperPrefActivity extends PreferenceActivity {",
" protected boolean isValidFragment(String fragment) {",
" if (\"VALID_FRAGMENT\".equals(fragment)) {",
" return true;",
" }",
" return false;",
" }",
"}")
.addSourceLines(
"MyPrefActivity.java",
// Okay, implemented on super class.
"class MyPrefActivity extends MySuperPrefActivity {}")
.doTest();
}
@Test
public void isValidFragmentImplementedOnAbstractSuperClass() {
compilationHelper
.addSourceLines(
"MySuperPrefActivity.java",
"import android.preference.PreferenceActivity;",
"abstract class MySuperPrefActivity extends PreferenceActivity {",
" protected boolean isValidFragment(String fragment) {",
" if (\"VALID_FRAGMENT\".equals(fragment)) {",
" return true;",
" }",
" return false;",
" }",
"}")
.addSourceLines(
"MyPrefActivity.java",
// Okay, implemented on super class.
"class MyPrefActivity extends MySuperPrefActivity {}")
.doTest();
}
@Test
public void abstractClassWithoutIsValidFragmentIsOkay() {
compilationHelper
.addSourceLines(
"MyAbstractPrefActivity.java",
"import android.preference.PreferenceActivity;",
// Okay, abstract so implementing class can implement isValidFragment.
"abstract class MyAbstractPrefActivity extends PreferenceActivity {}")
.doTest();
}
@Test
public void noIsValidFragmentOnAbstractSuperClassOrImplementation() {
compilationHelper
.addSourceLines(
"MyAbstractPrefActivity.java",
"import android.preference.PreferenceActivity;",
// Don't emit warning since it's abstract.
"abstract class MyAbstractPrefActivity extends PreferenceActivity {}")
.addSourceLines(
"MyPrefActivity.java",
"// BUG: Diagnostic contains: does not implement isValidFragment",
"class MyPrefActivity extends MyAbstractPrefActivity {}")
.doTest();
}
@Test
public void isValidFragmentTriviallyImplementedOnAbstractClass() {
compilationHelper
.addSourceLines(
"MyAbstractPrefActivity.java",
"import android.preference.PreferenceActivity;",
"abstract class MyAbstractPrefActivity extends PreferenceActivity {",
" // BUG: Diagnostic contains: isValidFragment unconditionally returns true",
" protected boolean isValidFragment(String fragment) {",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void isValidFragmentThrowsExceptionReturnsTrue() {
// N.B. In future we may make an exception for methods which include throw statements.
// In that case, just reverse this test (remove the BUG comment below).
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MyPrefActivity extends PreferenceActivity {",
" // BUG: Diagnostic contains: isValidFragment unconditionally returns true",
" protected boolean isValidFragment(String fragment) {",
" if (\"VALID_FRAGMENT\".equals(fragment)) {",
" throw new RuntimeException(\"Not a valid fragment!\");",
" }",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void ifTrueElseTrue() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MyPrefActivity extends PreferenceActivity {",
" // BUG: Diagnostic contains: isValidFragment unconditionally returns true",
" protected boolean isValidFragment(String fragment) {",
" if (\"VALID_FRAGMENT\".equals(fragment)) {",
" return true;",
" }",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void finalLocalVariableIsConstant() {
compilationHelper
.addSourceLines(
"MyPrefActivity.java",
"import android.preference.PreferenceActivity;",
"class MyPrefActivity extends PreferenceActivity {",
" // BUG: Diagnostic contains: isValidFragment unconditionally returns true",
" protected boolean isValidFragment(String fragment) {",
" final boolean constTrue = true;",
" return constTrue;",
" }",
"}")
.doTest();
}
}
| 10,688
| 34.277228
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/BundleDeserializationCastTest.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.android;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author epmjohnston@google.com (Emily P.M. Johnston)
*/
@RunWith(JUnit4.class)
public class BundleDeserializationCastTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(BundleDeserializationCast.class, getClass())
.addSourceFile("testdata/stubs/android/os/Bundle.java")
.addSourceFile("testdata/stubs/android/os/Parcel.java")
.addSourceFile("testdata/stubs/android/os/Parcelable.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void positiveCaseGetCustomList() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"import java.util.LinkedList;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" // BUG: Diagnostic matches: X",
" LinkedList myList = (LinkedList) bundle.getSerializable(\"key\");",
" }",
"}")
.expectErrorMessage(
"X",
Predicates.and(
Predicates.containsPattern("LinkedList may be transformed"),
Predicates.containsPattern("cast to List")))
.doTest();
}
@Test
public void positiveCaseGetCustomMap() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"import java.util.Hashtable;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" // BUG: Diagnostic matches: X",
" Hashtable myMap = (Hashtable) bundle.getSerializable(\"key\");",
" }",
"}")
.expectErrorMessage(
"X",
Predicates.and(
Predicates.containsPattern("Hashtable may be transformed"),
Predicates.containsPattern("cast to Map")))
.doTest();
}
@Test
public void negativeCaseGetArrayList() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"import java.util.ArrayList;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" ArrayList<String> myList = (ArrayList<String>) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseGetHashMap() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"import java.util.HashMap;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" HashMap myMap = (HashMap) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseGetParcelableList() {
compilationHelper
.addSourceFile("CustomParcelableList.java")
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"import java.util.List;",
"import com.google.errorprone.bugpatterns.android.testdata.CustomParcelableList;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" CustomParcelableList myList =",
" (CustomParcelableList) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseNoCast() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseOtherCast() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"import java.lang.Integer;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" Integer myObj = (Integer) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseGetList() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"import java.util.List;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" List myList = (List) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseGetMap() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"import java.util.Map;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" Map myMap = (Map) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseGetPrimitive() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" int myInt = (int) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseGetPrimitiveArray() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" int[] myArray = (int[]) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void negativeCaseGetReferenceArray() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"import java.util.TreeMap;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" TreeMap[] myArray = (TreeMap[]) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
@Test
public void positiveCaseGetCustomCharSequenceArray() {
compilationHelper
.addSourceLines(
"CustomCharSequence.java",
"public class CustomCharSequence implements CharSequence {",
" @Override",
" public int length() { return 0; }",
" @Override",
" public char charAt(int index) { return 0; }",
" @Override",
" public CharSequence subSequence(int start, int end) { return null; }",
"}")
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" // BUG: Diagnostic matches: X",
" CustomCharSequence[] cs = (CustomCharSequence[]) bundle.getSerializable(\"key\");",
" }",
"}")
.expectErrorMessage(
"X",
Predicates.and(
Predicates.containsPattern("CustomCharSequence\\[\\] may be transformed"),
Predicates.containsPattern("cast to CharSequence\\[\\]")))
.doTest();
}
@Test
public void negativeCaseGetStringArray() {
compilationHelper
.addSourceLines(
"Test.java",
"import android.os.Bundle;",
"public class Test {",
" void test() {",
" Bundle bundle = new Bundle();",
" String[] myArray = (String[]) bundle.getSerializable(\"key\");",
" }",
"}")
.doTest();
}
}
| 9,108
| 30.628472
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/StaticOrDefaultInterfaceMethodTest.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.android;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author epmjohnston@google.com (Emily P.M. Johnston)
*/
@RunWith(JUnit4.class)
public final class StaticOrDefaultInterfaceMethodTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(StaticOrDefaultInterfaceMethod.class, getClass())
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void positiveCaseDefault() {
compilationHelper
.addSourceLines(
"Test.java",
"interface Test {",
" // BUG: Diagnostic contains: StaticOrDefaultInterfaceMethod",
" default void test() { System.out.println(); }",
"}")
.doTest();
}
@Test
public void positiveCaseStatic() {
compilationHelper
.addSourceLines(
"Test.java",
"interface Test {",
" // BUG: Diagnostic contains: StaticOrDefaultInterfaceMethod",
" static void test() { System.out.println(); }",
"}")
.doTest();
}
@Test
public void negativeCaseNoBody() {
compilationHelper.addSourceLines("Test.java", "interface Test { void test(); }").doTest();
}
@Test
public void negativeCaseClass() {
compilationHelper
.addSourceLines("Test.java", "class Test { static void test() { System.out.println(); } }")
.doTest();
}
}
| 2,208
| 30.112676
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/RectIntersectReturnValueIgnoredTest.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.android;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author avenet@google.com (Arnaud J. Venet)
*/
@RunWith(JUnit4.class)
public class RectIntersectReturnValueIgnoredTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(RectIntersectReturnValueIgnored.class, getClass())
.addSourceFile("testdata/stubs/android/graphics/Rect.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void positiveCases() {
compilationHelper.addSourceFile("RectIntersectReturnValueIgnoredPositiveCases.java").doTest();
}
@Test
public void negativeCase() {
compilationHelper.addSourceFile("RectIntersectReturnValueIgnoredNegativeCases.java").doTest();
}
}
| 1,555
| 33.577778
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/FragmentNotInstantiablePositiveCases.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.android.testdata;
import android.app.Fragment;
/**
* @author avenet@google.com (Arnaud J. Venet)
*/
public class FragmentNotInstantiablePositiveCases {
// BUG: Diagnostic contains: public
static class PrivateFragment extends Fragment {
public PrivateFragment() {}
}
// BUG: Diagnostic contains: public
static class PrivateV4Fragment extends android.support.v4.app.Fragment {
public PrivateV4Fragment() {}
}
public static class PrivateConstructor extends Fragment {
// BUG: Diagnostic contains: public
PrivateConstructor() {}
}
// BUG: Diagnostic contains: nullary constructor
public static class NoConstructor extends Fragment {
public NoConstructor(int x) {}
}
// BUG: Diagnostic contains: nullary constructor
public static class NoConstructorV4 extends android.support.v4.app.Fragment {
public NoConstructorV4(int x) {}
}
public static class ParentFragment extends Fragment {
public ParentFragment() {}
}
public static class ParentFragmentV4 extends android.support.v4.app.Fragment {
public ParentFragmentV4() {}
}
// BUG: Diagnostic contains: nullary constructor
public static class DerivedFragmentNoConstructor extends ParentFragment {
public DerivedFragmentNoConstructor(int x) {}
}
// BUG: Diagnostic contains: nullary constructor
public static class DerivedFragmentNoConstructorV4 extends ParentFragmentV4 {
public DerivedFragmentNoConstructorV4(boolean b) {}
}
public class EnclosingClass {
// BUG: Diagnostic contains: static
public class InnerFragment extends Fragment {
public InnerFragment() {}
}
public Fragment create1() {
// BUG: Diagnostic contains: public
return new Fragment() {};
}
public Fragment create2() {
// BUG: Diagnostic contains: public
class LocalFragment extends Fragment {}
return new LocalFragment();
}
}
}
| 2,561
| 28.790698
| 80
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/ParcelableCreatorPositiveCases.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.android.testdata;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @author bhagwani@google.com (Sumit Bhagwani)
*/
public class ParcelableCreatorPositiveCases {
// BUG: Diagnostic contains: ParcelableCreator
public static class PublicParcelableClassWithoutCreator implements Parcelable {
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// no op
}
}
// BUG: Diagnostic contains: ParcelableCreator
public static class ParcelableClassWithoutStaticCreator implements Parcelable {
public final Parcelable.Creator<ParcelableClassWithoutStaticCreator> CREATOR =
new Parcelable.Creator<ParcelableClassWithoutStaticCreator>() {
public ParcelableClassWithoutStaticCreator createFromParcel(Parcel in) {
return new ParcelableClassWithoutStaticCreator();
}
public ParcelableClassWithoutStaticCreator[] newArray(int size) {
return new ParcelableClassWithoutStaticCreator[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// no op
}
}
// BUG: Diagnostic contains: ParcelableCreator
public static class ParcelableClassWithoutPublicCreator implements Parcelable {
static final Parcelable.Creator<ParcelableClassWithoutPublicCreator> CREATOR =
new Parcelable.Creator<ParcelableClassWithoutPublicCreator>() {
public ParcelableClassWithoutPublicCreator createFromParcel(Parcel in) {
return new ParcelableClassWithoutPublicCreator();
}
public ParcelableClassWithoutPublicCreator[] newArray(int size) {
return new ParcelableClassWithoutPublicCreator[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// no op
}
}
// BUG: Diagnostic contains: ParcelableCreator
public static class ParcelableClassWithCreatorOfWrongType implements Parcelable {
public static final Parcelable.Creator<ParcelableClassWithoutPublicCreator> CREATOR =
new Parcelable.Creator<ParcelableClassWithoutPublicCreator>() {
public ParcelableClassWithoutPublicCreator createFromParcel(Parcel in) {
return new ParcelableClassWithoutPublicCreator();
}
public ParcelableClassWithoutPublicCreator[] newArray(int size) {
return new ParcelableClassWithoutPublicCreator[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// no op
}
}
}
| 3,368
| 30.485981
| 89
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/CustomFragmentNotInstantiableNegativeCases.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.android.testdata;
/**
* @author jasonlong@google.com (Jason Long)
*/
public class CustomFragmentNotInstantiableNegativeCases {
public static class NotAFragment1 {
public NotAFragment1(int x) {}
}
public static class NotAFragment2 {
private NotAFragment2() {}
}
private static class NotAFragment3 {}
public class NotAFragment4 {}
private abstract class AbstractFragment extends CustomFragment {
public AbstractFragment(int x) {}
}
public static class MyFragment extends CustomFragment {
private int a;
public int value() {
return a;
}
}
public static class DerivedFragment extends MyFragment {}
public static class MyFragment2 extends CustomFragment {
public MyFragment2() {}
public MyFragment2(int x) {}
}
public static class DerivedFragment2 extends MyFragment2 {
public DerivedFragment2() {}
public DerivedFragment2(boolean b) {}
}
public static class EnclosingClass {
public static class InnerFragment extends CustomFragment {
public InnerFragment() {}
}
}
interface AnInterface {
public class ImplicitlyStaticInnerFragment extends CustomFragment {}
class ImplicitlyStaticAndPublicInnerFragment extends CustomFragment {}
}
}
| 1,902
| 25.068493
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/RectIntersectReturnValueIgnoredNegativeCases.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.android.testdata;
import android.graphics.Rect;
/**
* @author avenet@google.com (Arnaud J. Venet)
*/
public class RectIntersectReturnValueIgnoredNegativeCases {
boolean checkSimpleCall(Rect rect, int aLeft, int aTop, int aRight, int aBottom) {
return rect.intersect(aLeft, aTop, aRight, aBottom);
}
boolean checkOverload(Rect rect1, Rect rect2) {
return rect1.intersect(rect2);
}
void checkInTest(Rect rect, int aLeft, int aTop, int aRight, int aBottom) {
if (!rect.intersect(aLeft, aTop, aRight, aBottom)) {
rect.setEmpty();
}
}
class InternalScope {
class Rect {
int left;
int right;
int top;
int bottom;
boolean intersect(int aLeft, int aTop, int aRight, int aBottom) {
throw new RuntimeException("Not implemented");
}
}
void checkHomonym(Rect rect, int aLeft, int aTop, int aRight, int aBottom) {
rect.intersect(aLeft, aTop, aRight, aBottom);
}
}
class RectContainer {
int xPos;
int yPos;
Rect rect;
boolean intersect(int length, int width) {
return rect.intersect(xPos, yPos, xPos + length, yPos + width);
}
}
void checkInMethod(int length, int width) {
RectContainer container = new RectContainer();
container.intersect(length, width);
}
}
| 1,955
| 26.549296
| 84
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.