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/testdata/DeleteGeneratedConstructorTestCase.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.testdata; public class DeleteGeneratedConstructorTestCase { // generated constructor goes here }
739
32.636364
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/testdata/ExtendedMultipleTopLevelClassesWithErrors.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.testdata; public class ExtendedMultipleTopLevelClassesWithErrors extends MultipleTopLevelClassesWithErrors {}
750
36.55
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/scanner/ScannerSupplierTest.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.scanner; import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.scanner.BuiltInCheckerSuppliers.getSuppliers; import static org.junit.Assert.assertThrows; import com.google.common.base.Joiner; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.jimfs.Jimfs; import com.google.common.truth.FailureMetadata; import com.google.common.truth.MapSubject; import com.google.common.truth.Subject; import com.google.errorprone.BugCheckerInfo; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.ErrorProneJavaCompilerTest; import com.google.errorprone.ErrorProneJavaCompilerTest.UnsuppressibleArrayEquals; import com.google.errorprone.ErrorProneOptions; import com.google.errorprone.FileManagers; import com.google.errorprone.InvalidCommandLineOptionException; import com.google.errorprone.bugpatterns.ArrayEquals; import com.google.errorprone.bugpatterns.BadShiftAmount; import com.google.errorprone.bugpatterns.BooleanParameter; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.ChainingConstructorIgnoresParameter; import com.google.errorprone.bugpatterns.ConstantField; import com.google.errorprone.bugpatterns.DepAnn; import com.google.errorprone.bugpatterns.EqualsIncompatibleType; import com.google.errorprone.bugpatterns.LongLiteralLowerCaseSuffix; import com.google.errorprone.bugpatterns.MethodCanBeStatic; import com.google.errorprone.bugpatterns.MissingBraces; import com.google.errorprone.bugpatterns.PackageLocation; import com.google.errorprone.bugpatterns.ReferenceEquality; import com.google.errorprone.bugpatterns.StaticQualifiedUsingExpression; import com.google.errorprone.bugpatterns.nullness.UnnecessaryCheckNotNull; import com.sun.source.util.JavacTask; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.file.JavacFileManager; import java.io.IOException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Map; import java.util.function.Supplier; import javax.tools.JavaFileObject.Kind; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardLocation; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link ScannerSupplier}. */ @RunWith(JUnit4.class) public class ScannerSupplierTest { @Test public void fromBugCheckerClassesWorks() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( ArrayEquals.class, StaticQualifiedUsingExpression.class); assertScanner(ss).hasEnabledChecks(ArrayEquals.class, StaticQualifiedUsingExpression.class); } @Test public void fromBugCheckersWorks() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerInfos( ImmutableList.of( BugCheckerInfo.create(ArrayEquals.class), BugCheckerInfo.create(StaticQualifiedUsingExpression.class))); assertScanner(ss).hasEnabledChecks(ArrayEquals.class, StaticQualifiedUsingExpression.class); } @Test public void plusWorks() { ScannerSupplier ss1 = ScannerSupplier.fromBugCheckerClasses( ArrayEquals.class, StaticQualifiedUsingExpression.class); ScannerSupplier ss2 = ScannerSupplier.fromBugCheckerClasses(BadShiftAmount.class, UnnecessaryCheckNotNull.class); assertScanner(ss1.plus(ss2)) .hasEnabledChecks( ArrayEquals.class, StaticQualifiedUsingExpression.class, BadShiftAmount.class, UnnecessaryCheckNotNull.class); } // Allow different instances of classes to be merged, provided they have the same name. // This allows e.g. seeing the same check built in to Error Prone and loaded on the // processorpath. @Test public void plusAllowsDuplicateClassLoading() throws Exception { FileSystem fileSystem = Jimfs.newFileSystem(); Class<? extends BugChecker> class1 = compileAndLoadChecker( fileSystem, "com.google.errorprone.bugpatterns.TestChecker", "package com.google.errorprone.bugpatterns;", "import com.google.errorprone.BugPattern;", "@BugPattern(name = \"TestChecker\", summary = \"\"," + " severity = BugPattern.SeverityLevel.WARNING)", "public class TestChecker extends BugChecker {}"); Class<? extends BugChecker> class2 = compileAndLoadChecker( fileSystem, "com.google.errorprone.bugpatterns.TestChecker", "package com.google.errorprone.bugpatterns;", "import com.google.errorprone.BugPattern;", "@BugPattern(name = \"TestChecker\", summary = \"\"," + " severity = BugPattern.SeverityLevel.WARNING)", "public class TestChecker extends BugChecker {}"); ScannerSupplier ss1 = ScannerSupplier.fromBugCheckerClasses(ArrayEquals.class, class1).filter(c -> false); ScannerSupplier ss2 = ScannerSupplier.fromBugCheckerClasses(class2); assertThat(class1).isNotEqualTo(class2); ScannerSupplier ss = ss1.plus(ss2); assertThat(ss.getAllChecks()).hasSize(2); assertThat(ss.getAllChecks().values().stream().map(c -> c.checkerClass())) .containsExactly(ArrayEquals.class, class1); assertScanner(ss).hasEnabledChecks(class1); } /** Another check with the canonical name ArrayEquals, for testing. */ @BugPattern(name = "ArrayEquals", summary = "", severity = ERROR) public static class OtherArrayEquals extends BugChecker {} @Test public void plusDisallowsDuplicates() { ScannerSupplier ss1 = ScannerSupplier.fromBugCheckerClasses(ArrayEquals.class); ScannerSupplier ss2 = ScannerSupplier.fromBugCheckerClasses(OtherArrayEquals.class); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> ss1.plus(ss2)); assertThat(thrown) .hasMessageThat() .contains( "different implementations of 'ArrayEquals':" + " com.google.errorprone.scanner.ScannerSupplierTest$OtherArrayEquals," + " com.google.errorprone.bugpatterns.ArrayEquals"); } @Test public void plusDisallowsDifferentSeverities() throws Exception { FileSystem fileSystem = Jimfs.newFileSystem(); Class<? extends BugChecker> class1 = compileAndLoadChecker( fileSystem, "com.google.errorprone.bugpatterns.TestChecker", "package com.google.errorprone.bugpatterns;", "import com.google.errorprone.BugPattern;", "@BugPattern(name = \"TestChecker\", summary = \"\"," + " severity = BugPattern.SeverityLevel.ERROR)", "public class TestChecker extends BugChecker {}"); Class<? extends BugChecker> class2 = compileAndLoadChecker( fileSystem, "com.google.errorprone.bugpatterns.TestChecker", "package com.google.errorprone.bugpatterns;", "import com.google.errorprone.BugPattern;", "@BugPattern(name = \"TestChecker\", summary = \"\"," + " severity = BugPattern.SeverityLevel.WARNING)", "public class TestChecker extends BugChecker {}"); ScannerSupplier ss1 = ScannerSupplier.fromBugCheckerClasses(class1); ScannerSupplier ss2 = ScannerSupplier.fromBugCheckerClasses(class2); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> ss1.plus(ss2)); assertThat(class1).isNotEqualTo(class2); assertThat(thrown) .hasMessageThat() .contains("different severities for 'TestChecker': WARNING, ERROR"); } static Class<? extends BugChecker> compileAndLoadChecker( FileSystem fileSystem, String name, String... lines) throws IOException, ClassNotFoundException { JavacTool javacTool = JavacTool.create(); JavacFileManager fileManager = FileManagers.testFileManager(); Path tmp = fileSystem.getPath("tmp"); Files.createDirectories(tmp); Path output = Files.createTempDirectory(tmp, "output"); fileManager.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, ImmutableList.of(output)); JavacTask task = javacTool.getTask( null, fileManager, null, Collections.emptyList(), null, Collections.singletonList( new SimpleJavaFileObject( URI.create(name.replace('.', '/') + ".java"), Kind.SOURCE) { @Override public CharSequence getCharContent(boolean b) { return Joiner.on('\n').join(lines); } })); assertThat(task.call()).isTrue(); return Class.forName(name, true, new URLClassLoader(new URL[] {output.toUri().toURL()})) .asSubclass(BugChecker.class); } @Test public void filterWorks() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( ArrayEquals.class, BadShiftAmount.class, StaticQualifiedUsingExpression.class); assertScanner(ss.filter(input -> input.canonicalName().equals("BadShiftAmount"))) .hasEnabledChecks(BadShiftAmount.class); } @Test public void applyOverridesWorksOnEmptySeverityMap() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( ChainingConstructorIgnoresParameter.class, DepAnn.class, LongLiteralLowerCaseSuffix.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(Collections.emptyList()); ScannerSupplier overridden = ss.applyOverrides(epOptions); assertScanner(overridden) .hasEnabledChecks( ChainingConstructorIgnoresParameter.class, DepAnn.class, LongLiteralLowerCaseSuffix.class); } @Test public void applyOverridesWorksOnEmptyFlagsMap() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses(); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(Collections.emptyList()); ScannerSupplier overridden = ss.applyOverrides(epOptions); assertScanner(overridden).flagsMap().isEmpty(); } @Test public void applyOverridesHandlesErrorProneFlagsMerging() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses(); ScannerSupplier overridden = ss.applyOverrides( ErrorProneOptions.processArgs(ImmutableList.of("-XepOpt:A:B", "-XepOpt:Foo=2"))); assertScanner(overridden).flagsMap().containsExactly("A:B", "true", "Foo", "2"); overridden = overridden.applyOverrides( ErrorProneOptions.processArgs(ImmutableList.of("-XepOpt:A:B=false", "-XepOpt:Bar=1"))); assertScanner(overridden).flagsMap().containsExactly("A:B", "false", "Foo", "2", "Bar", "1"); } @Test public void applyOverridesEnablesCheck() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( ArrayEquals.class, BadShiftAmount.class, StaticQualifiedUsingExpression.class) .filter(Predicates.alwaysFalse()); // disables all checks ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-Xep:ArrayEquals", "-Xep:BadShiftAmount")); assertScanner(ss.applyOverrides(epOptions)) .hasEnabledChecks(ArrayEquals.class, BadShiftAmount.class); } @Test public void applyOverridesEnableAllChecks() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( ArrayEquals.class, BadShiftAmount.class, StaticQualifiedUsingExpression.class) .filter(Predicates.alwaysFalse()); // disables all checks assertScanner(ss).hasEnabledChecks(); // assert empty scanner has no enabled checks ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-XepAllDisabledChecksAsWarnings")); assertScanner(ss.applyOverrides(epOptions)) .hasEnabledChecks( ArrayEquals.class, BadShiftAmount.class, StaticQualifiedUsingExpression.class); epOptions = ErrorProneOptions.processArgs( ImmutableList.of("-XepAllDisabledChecksAsWarnings", "-Xep:ArrayEquals:OFF")); assertScanner(ss.applyOverrides(epOptions)) .hasEnabledChecks(BadShiftAmount.class, StaticQualifiedUsingExpression.class); // The 'AllDisabledChecksAsWarnings' flag doesn't populate through to additional plugins assertScanner( ss.applyOverrides(epOptions) .plus( ScannerSupplier.fromBugCheckerClasses(MethodCanBeStatic.class) .filter(t -> false))) .hasEnabledChecks(BadShiftAmount.class, StaticQualifiedUsingExpression.class); } @Test public void applyOverridesDisableErrors() { // BadShiftAmount (error), ArrayEquals (unsuppressible error), ReferenceEquality (warning) ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( BadShiftAmount.class, UnsuppressibleArrayEquals.class, ReferenceEquality.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-XepAllErrorsAsWarnings")); assertScanner(ss.applyOverrides(epOptions)) .hasSeverities( ImmutableMap.of( "ArrayEquals", SeverityLevel.ERROR, // Unsuppressible, not demoted "BadShiftAmount", SeverityLevel.WARNING, // Demoted from error to warning "ReferenceEquality", SeverityLevel.WARNING)); // Already warning, unaffected // Flags after AllErrorsAsWarnings flag should override it. epOptions = ErrorProneOptions.processArgs( ImmutableList.of("-XepAllErrorsAsWarnings", "-Xep:ReferenceEquality:ERROR")); assertScanner(ss.applyOverrides(epOptions)) .hasSeverities( ImmutableMap.of( "ArrayEquals", SeverityLevel.ERROR, "BadShiftAmount", SeverityLevel.WARNING, "ReferenceEquality", SeverityLevel.ERROR)); // AllErrorsAsWarnings flag should override all error-level severity flags that come before it. epOptions = ErrorProneOptions.processArgs( ImmutableList.of("-Xep:ReferenceEquality:ERROR", "-XepAllErrorsAsWarnings")); assertScanner(ss.applyOverrides(epOptions)) .hasSeverities( ImmutableMap.of( "ArrayEquals", SeverityLevel.ERROR, "BadShiftAmount", SeverityLevel.WARNING, "ReferenceEquality", SeverityLevel.WARNING)); // AllErrorsAsWarnings only overrides error-level severity flags. // That is, checks disabled before the flag are left disabled, not promoted to warnings. epOptions = ErrorProneOptions.processArgs( ImmutableList.of("-Xep:BadShiftAmount:OFF", "-XepAllErrorsAsWarnings")); assertScanner(ss.applyOverrides(epOptions)) .hasSeverities( ImmutableMap.of( "ArrayEquals", SeverityLevel.ERROR, "ReferenceEquality", SeverityLevel.WARNING)); assertScanner(ss.applyOverrides(epOptions)) .hasEnabledChecks(UnsuppressibleArrayEquals.class, ReferenceEquality.class); } @Test public void applyOverridesDisableErrorsOnlyForEnabledChecks() { Supplier<ScannerSupplier> filteredScanner = () -> ScannerSupplier.fromBugCheckerClasses( BadShiftAmount.class, UnsuppressibleArrayEquals.class, EqualsIncompatibleType.class) .filter(p -> !p.checkerClass().equals(EqualsIncompatibleType.class)); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-XepAllErrorsAsWarnings")); assertScanner(filteredScanner.get().applyOverrides(epOptions)) .hasEnabledChecks(UnsuppressibleArrayEquals.class, BadShiftAmount.class); epOptions = ErrorProneOptions.processArgs( ImmutableList.of("-XepAllErrorsAsWarnings", "-Xep:BadShiftAmount:OFF")); assertScanner(filteredScanner.get().applyOverrides(epOptions)) .hasEnabledChecks(UnsuppressibleArrayEquals.class); } @Test public void applyOverridesDisablesChecks() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( ChainingConstructorIgnoresParameter.class, DepAnn.class, LongLiteralLowerCaseSuffix.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs( ImmutableList.of( "-Xep:LongLiteralLowerCaseSuffix:OFF", "-Xep:ChainingConstructorIgnoresParameter:OFF")); assertScanner(ss.applyOverrides(epOptions)).hasEnabledChecks(DepAnn.class); } @Test public void applyOverridesThrowsExceptionWhenDisablingNonDisablableCheck() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( ErrorProneJavaCompilerTest.UnsuppressibleArrayEquals.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-Xep:ArrayEquals:OFF")); InvalidCommandLineOptionException exception = assertThrows(InvalidCommandLineOptionException.class, () -> ss.applyOverrides(epOptions)); assertThat(exception).hasMessageThat().contains("may not be disabled"); } @Test public void applyOverridesThrowsExceptionWhenDemotingNonDisablableCheck() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( ErrorProneJavaCompilerTest.UnsuppressibleArrayEquals.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-Xep:ArrayEquals:WARN")); InvalidCommandLineOptionException exception = assertThrows(InvalidCommandLineOptionException.class, () -> ss.applyOverrides(epOptions)); assertThat(exception).hasMessageThat().contains("may not be demoted to a warning"); } @Test public void applyOverridesSucceedsWhenDisablingUnknownCheckAndIgnoreUnknownCheckNamesIsSet() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses(ArrayEquals.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs( ImmutableList.of("-XepIgnoreUnknownCheckNames", "-Xep:foo:OFF")); assertScanner(ss.applyOverrides(epOptions)).hasEnabledChecks(ArrayEquals.class); } @Test public void applyOverridesSetsSeverity() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( BadShiftAmount.class, ChainingConstructorIgnoresParameter.class, ReferenceEquality.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs( ImmutableList.of( "-Xep:ChainingConstructorIgnoresParameter:WARN", "-Xep:ReferenceEquality:ERROR")); ScannerSupplier overriddenScannerSupplier = ss.applyOverrides(epOptions); ImmutableMap<String, SeverityLevel> expected = ImmutableMap.of( "BadShiftAmount", SeverityLevel.ERROR, "ChainingConstructorIgnoresParameter", SeverityLevel.WARNING, "ReferenceEquality", SeverityLevel.ERROR); assertScanner(overriddenScannerSupplier).hasSeverities(expected); } @Test public void applyOverridesSetsFlags() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses(); assertThat(ss.getFlags().isEmpty()).isTrue(); ErrorProneOptions epOptions = ErrorProneOptions.processArgs( ImmutableList.of( "-XepOpt:FirstFlag=overridden", "-XepOpt:SecondFlag=AValue", "-XepOpt:FirstFlag")); ScannerSupplier overriddenScannerSupplier = ss.applyOverrides(epOptions); ImmutableMap<String, String> expected = ImmutableMap.of( "FirstFlag", "true", "SecondFlag", "AValue"); assertThat(overriddenScannerSupplier.getFlags().getFlagsMap()) .containsExactlyEntriesIn(expected); } @Test public void allChecksAsWarningsWorks() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( BadShiftAmount.class, ChainingConstructorIgnoresParameter.class, ReferenceEquality.class) .filter(Predicates.alwaysFalse()); assertScanner(ss).hasEnabledChecks(); // Everything's off ErrorProneOptions epOptions = ErrorProneOptions.processArgs( ImmutableList.of("-Xep:ReferenceEquality:OFF", "-XepAllDisabledChecksAsWarnings")); ScannerSupplier withOverrides = ss.applyOverrides(epOptions); assertScanner(withOverrides) .hasEnabledChecks( BadShiftAmount.class, ChainingConstructorIgnoresParameter.class, ReferenceEquality.class); ImmutableMap<String, SeverityLevel> expectedSeverities = ImmutableMap.of( "BadShiftAmount", SeverityLevel.WARNING, "ChainingConstructorIgnoresParameter", SeverityLevel.WARNING, "ReferenceEquality", SeverityLevel.WARNING); assertScanner(withOverrides).hasSeverities(expectedSeverities); epOptions = ErrorProneOptions.processArgs( ImmutableList.of( "-Xep:ReferenceEquality:OFF", "-XepAllDisabledChecksAsWarnings", "-Xep:ReferenceEquality:OFF")); withOverrides = ss.applyOverrides(epOptions); assertScanner(withOverrides) .hasEnabledChecks(BadShiftAmount.class, ChainingConstructorIgnoresParameter.class); expectedSeverities = ImmutableMap.of( "BadShiftAmount", SeverityLevel.WARNING, "ChainingConstructorIgnoresParameter", SeverityLevel.WARNING); assertScanner(withOverrides).hasSeverities(expectedSeverities); } @Test public void allSuggestionsAsWarnings() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses( BooleanParameter.class, ConstantField.class, MissingBraces.class); assertScanner(ss) .hasEnabledChecks(BooleanParameter.class, ConstantField.class, MissingBraces.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-XepAllSuggestionsAsWarnings")); ImmutableMap<String, SeverityLevel> expectedSeverities = ImmutableMap.of( "BooleanParameter", SeverityLevel.WARNING, "ConstantField", SeverityLevel.WARNING, "MissingBraces", SeverityLevel.WARNING); assertScanner(ss.applyOverrides(epOptions)).hasSeverities(expectedSeverities); } @Test public void canSuppressViaAltName() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses(WithAltName.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-Xep:HeresMyAltName:OFF")); ScannerSupplier overrides = ss.applyOverrides(epOptions); assertScanner(overrides).hasEnabledChecks(/* empty */ ); } /** An unsuppressible version of {@link PackageLocation}. */ @BugPattern( name = "PackageLocation", summary = "", altNames = {"AlternativePackageLocation"}, severity = ERROR, suppressionAnnotations = {}, disableable = false) public static class UnsuppressiblePackageLocation extends PackageLocation {} @BugPattern(altNames = "HeresMyAltName", summary = "", severity = ERROR) public static class WithAltName extends PackageLocation {} @Test public void disablingPackageLocation_unsuppressible() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses(UnsuppressiblePackageLocation.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-Xep:PackageLocation:OFF")); InvalidCommandLineOptionException exception = assertThrows(InvalidCommandLineOptionException.class, () -> ss.applyOverrides(epOptions)); assertThat(exception).hasMessageThat().contains("may not be disabled"); } @Test public void disablingPackageLocation_viaAltName_unsuppressible() { ScannerSupplier ss = ScannerSupplier.fromBugCheckerClasses(UnsuppressiblePackageLocation.class); ErrorProneOptions epOptions = ErrorProneOptions.processArgs(ImmutableList.of("-Xep:AlternativePackageLocation:OFF")); InvalidCommandLineOptionException exception = assertThrows(InvalidCommandLineOptionException.class, () -> ss.applyOverrides(epOptions)); assertThat(exception).hasMessageThat().contains("may not be disabled"); } private static class ScannerSupplierSubject extends Subject { private final ScannerSupplier actual; ScannerSupplierSubject(FailureMetadata failureMetadata, ScannerSupplier scannerSupplier) { super(failureMetadata, scannerSupplier); this.actual = scannerSupplier; } final void hasSeverities(Map<String, SeverityLevel> severities) { check("severities()").that(actual.severities()).containsExactlyEntriesIn(severities); } @SafeVarargs final void hasEnabledChecks(Class<? extends BugChecker>... bugCheckers) { check("getEnabledChecks()") .that(actual.getEnabledChecks()) .containsExactlyElementsIn(getSuppliers(bugCheckers)); } final MapSubject flagsMap() { return check("getFlags().getFlagsMap()").that(actual.getFlags().getFlagsMap()); } } /** A check missing `@Inject`. */ @SuppressWarnings("InjectOnBugCheckers") // intentional for testing @BugPattern(summary = "", severity = ERROR) public static class MissingInject extends BugChecker { public MissingInject(ErrorProneFlags flags) {} } @Test public void missingInject_stillProvisioned() { ScannerSupplier ss1 = ScannerSupplier.fromBugCheckerClasses(MissingInject.class); // We're only testing that this doesn't fail. var unused = ss1.get(); } private static ScannerSupplierSubject assertScanner(ScannerSupplier scannerSupplier) { return assertAbout(ScannerSupplierSubject::new).that(scannerSupplier); } }
27,057
39.085926
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/scanner/ScannerTest.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.scanner; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.IdentifierTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.tree.IdentifierTree; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link Scanner}. */ @RunWith(JUnit4.class) public class ScannerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ShouldNotUseFoo.class, getClass()); @Test public void notSuppressedByAnnotationOnType() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.scanner.ScannerTest.Foo;", "class Test {", " // BUG: Diagnostic contains: ShouldNotUseFoo", " Foo foo;", "}") .doTest(); } @Test public void notSuppressedByAnnotationOnParameterizedType() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.scanner.ScannerTest.Foo;", "class Test {", " // BUG: Diagnostic contains: ShouldNotUseFoo", " Foo<String> foo;", "}") .doTest(); } @Test public void suppressedByAnnotationOnUsage() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.scanner.ScannerTest.Foo;", "import com.google.errorprone.scanner.ScannerTest.OkToUseFoo;", "class Test {", " @OkToUseFoo", " Foo foo;", "}") .doTest(); } @Test public void suppressionAnnotationIgnoredWithOptions() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.scanner.ScannerTest.Foo;", "import com.google.errorprone.scanner.ScannerTest.OkToUseFoo;", "class Test {", " @OkToUseFoo", " // BUG: Diagnostic contains: ShouldNotUseFoo", " Foo foo;", "}") .setArgs(ImmutableList.of("-XepIgnoreSuppressionAnnotations")) .doTest(); } @OkToUseFoo // Foo can use itself. But this shouldn't suppress errors on *usages* of Foo. public static final class Foo<T> {} public @interface OkToUseFoo {} @BugPattern( summary = "Code should not use Foo.", severity = ERROR, suppressionAnnotations = OkToUseFoo.class) public static class ShouldNotUseFoo extends BugChecker implements IdentifierTreeMatcher { @Override public Description matchIdentifier(IdentifierTree tree, VisitorState state) { return getSymbol(tree).getQualifiedName().contentEquals(Foo.class.getCanonicalName()) ? describeMatch(tree) : NO_MATCH; } } }
3,878
32.439655
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NoAllocationCheckerTest.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author agoode@google.com (Adam Goode) */ @RunWith(JUnit4.class) public class NoAllocationCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(NoAllocationChecker.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("NoAllocationCheckerPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("NoAllocationCheckerNegativeCases.java").doTest(); } }
1,310
29.488372
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AnnotationPositionTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import static org.junit.Assume.assumeTrue; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link AnnotationPosition} bugpattern. * * @author ghm@google.com (Graeme Morgan) */ @RunWith(JUnit4.class) public final class AnnotationPositionTest { private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(AnnotationPosition.class, getClass()) .addInputLines( "TypeUse.java", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Target;", "@Target({ElementType.TYPE_USE})", "@interface TypeUse {", " String value() default \"\";", "}") .expectUnchanged() .addInputLines( "EitherUse.java", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Target;", "@Target({ElementType.TYPE_USE, ElementType.METHOD, ElementType.TYPE})", "@interface EitherUse {", " String value() default \"\";", "}") .expectUnchanged() .addInputLines( "NonTypeUse.java", // "@interface NonTypeUse {}") .expectUnchanged(); private final CompilationTestHelper helper = CompilationTestHelper.newInstance(AnnotationPosition.class, getClass()) .addSourceLines( "TypeUse.java", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Target;", "@Target({ElementType.TYPE_USE, ElementType.METHOD, ElementType.TYPE})", "@interface TypeUse {", " String value() default \"\";", "}") .addSourceLines( "NonTypeUse.java", // "@interface NonTypeUse {}") .addSourceLines( "EitherUse.java", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Target;", "@Target({ElementType.TYPE_USE, ElementType.METHOD, ElementType.TYPE})", "@interface EitherUse {", " String value() default \"\";", "}"); @Test public void nonTypeAnnotation() { refactoringHelper .addInputLines( "Test.java", // "interface Test {", // " public @Override boolean equals(Object o);", "}") .addOutputLines( "Test.java", // "interface Test {", " @Override public boolean equals(Object o);", "}") .doTest(TEXT_MATCH); } @Test public void interspersedJavadoc() { refactoringHelper .addInputLines( "Test.java", "interface Test {", " @NonTypeUse", " /** Javadoc! */", " public void foo();", "}") .addOutputLines( "Test.java", "interface Test {", " /** Javadoc! */", " @NonTypeUse", " public void foo();", "}") .doTest(TEXT_MATCH); } @Test public void interspersedJavadoc_treeAlreadyHasJavadoc_noSuggestion() { refactoringHelper .addInputLines( "Test.java", "interface Test {", " /** Actually Javadoc. */", " @NonTypeUse", " /** Javadoc! */", " public void foo();", "}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void interspersedJavadoc_withComment() { refactoringHelper .addInputLines( "Test.java", "interface Test {", " @NonTypeUse", " /** Javadoc! */", " // TODO: fix", " public void foo();", "}") .addOutputLines( "Test.java", "interface Test {", " /** Javadoc! */", " @NonTypeUse", " // TODO: fix", " public void foo();", "}") .doTest(TEXT_MATCH); } @Test public void negatives() { refactoringHelper .addInputLines( "Test.java", "interface Test {", " /** Javadoc */", " @NonTypeUse", " public boolean foo();", " @NonTypeUse", " public boolean bar();", " public @EitherUse boolean baz();", " /** Javadoc */", " @NonTypeUse", " // comment", " public boolean quux();", "}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void negative_parameter() { refactoringHelper .addInputLines( "Test.java", "interface Test {", " public boolean foo(final @NonTypeUse String s);", "}") .addOutputLines( "Test.java", "interface Test {", " public boolean foo(@NonTypeUse final String s);", "}") .doTest(TEXT_MATCH); } @Test public void typeAnnotation() { refactoringHelper .addInputLines( "Test.java", "interface Test {", " /** Javadoc */", " public @NonTypeUse @EitherUse String foo();", " /** Javadoc */", " public @EitherUse @NonTypeUse String bar();", " public @EitherUse /** Javadoc */ @NonTypeUse String baz();", " public @EitherUse static @NonTypeUse int quux() { return 1; }", "}") .addOutputLines( "Test.java", "interface Test {", " /** Javadoc */", " @NonTypeUse public @EitherUse String foo();", " /** Javadoc */", " @NonTypeUse public @EitherUse String bar();", " /** Javadoc */", " @NonTypeUse public @EitherUse String baz();", " @NonTypeUse public static @EitherUse int quux() { return 1; }", "}") .doTest(TEXT_MATCH); } @Test public void variables() { refactoringHelper .addInputLines( "Test.java", "interface Test {", " public @EitherUse static /** Javadoc */ @NonTypeUse int foo = 1;", "}") .addOutputLines( "Test.java", "interface Test {", " /** Javadoc */", " @NonTypeUse public static @EitherUse int foo = 1;", "}") .doTest(TEXT_MATCH); } @Test public void classes() { refactoringHelper .addInputLines( "Test.java", // "public @NonTypeUse", "interface Test {}") .addOutputLines( "Test.java", // "@NonTypeUse", "public interface Test {}") .doTest(TEXT_MATCH); } @Test public void class_typeUseBeforeModifiers() { refactoringHelper .addInputLines( "Test.java", // "public @EitherUse interface Test {}") .addOutputLines( "Test.java", // "@EitherUse", "public interface Test {}") .doTest(TEXT_MATCH); } @Test public void class_intermingledJavadoc() { refactoringHelper .addInputLines( "Test.java", // "@NonTypeUse public /** Javadoc */ final class Test {}") .addOutputLines( "Test.java", // "/** Javadoc */", "@NonTypeUse public final class Test {}") .doTest(TEXT_MATCH); } @Test public void betweenModifiers() { refactoringHelper .addInputLines( "Test.java", "interface Test {", " public @EitherUse static @NonTypeUse int foo() { return 1; }", " public @EitherUse @NonTypeUse static int bar() { return 1; }", "}") .addOutputLines( "Test.java", "interface Test {", " @NonTypeUse public static @EitherUse int foo() { return 1; }", " @NonTypeUse public static @EitherUse int bar() { return 1; }", "}") .doTest(TEXT_MATCH); } @Test public void betweenModifiersWithValue() { refactoringHelper .addInputLines( "Test.java", "class Test {", " public final @EitherUse(\"foo\") int foo(final int a) { return 1; }", "}") .addOutputLines( "Test.java", "class Test {", " public final @EitherUse(\"foo\") int foo(final int a) { return 1; }", "}") .doTest(TEXT_MATCH); } @Test public void interspersedComments() { refactoringHelper .addInputLines( "Test.java", "interface Test {", " public @EitherUse /** Javadoc */ @NonTypeUse String baz();", " /* a */ public /* b */ @EitherUse /* c */ static /* d */ " + "@NonTypeUse /* e */ int quux() { return 1; }", "}") .addOutputLines( "Test.java", "interface Test {", " /** Javadoc */", " @NonTypeUse public @EitherUse String baz();", " /* a */ @NonTypeUse public /* b */ /* c */ static @EitherUse " + "/* d */ /* e */ int quux() { return 1; }", "}") .doTest(TEXT_MATCH); } @Test public void messages() { helper .addSourceLines( "Test.java", "interface Test {", " // BUG: Diagnostic contains: @Override is not a TYPE_USE annotation", " public @Override boolean equals(Object o);", " // BUG: Diagnostic contains: @Override, @NonTypeUse are not TYPE_USE annotations", " public @Override @NonTypeUse int hashCode();", " // BUG: Diagnostic contains: Javadocs should appear before any modifiers", " @NonTypeUse /** Javadoc */ public boolean bar();", "}") .doTest(); } @Test public void diagnostic() { helper .addSourceLines( "Test.java", // "interface Test {", " // BUG: Diagnostic contains: is a TYPE_USE", " public @EitherUse static int foo = 1;", "}") .doTest(); } // TODO(b/168625474): 'sealed' doesn't have a TokenKind @Test public void sealedInterface() { assumeTrue(RuntimeVersion.isAtLeast15()); refactoringHelper .addInputLines( "Test.java", // "/** Javadoc! */", "sealed @Deprecated interface Test {", " final class A implements Test {}", "}") .addOutputLines( "Test.java", // "/** Javadoc! */", "sealed @Deprecated interface Test {", " final class A implements Test {}", "}") .setArgs("--enable-preview", "--release", Integer.toString(RuntimeVersion.release())) .doTest(TEXT_MATCH); } @Test public void typeArgument_annotationOfEitherUse_canRemainBefore() { refactoringHelper .addInputLines( "Test.java", // "interface T {", " @EitherUse <T> T f();", "}") .addOutputLines( "Test.java", // "interface T {", " @EitherUse <T> T f();", "}") .doTest(TEXT_MATCH); } @Test public void typeArgument_typeUseAnnotation_movesAfter() { refactoringHelper .addInputLines( "Test.java", // "interface T {", " @TypeUse <T> T f();", "}") .addOutputLines( "Test.java", // "interface T {", " <T> @TypeUse T f();", "}") .doTest(TEXT_MATCH); } @Test public void genericsWithBounds() { refactoringHelper .addInputLines( "Test.java", // "import java.util.List;", "interface T {", " @TypeUse <T extends List<T>> T f();", "}") .addOutputLines( "Test.java", // "import java.util.List;", "interface T {", " <T extends List<T>> @TypeUse T f();", "}") .doTest(TEXT_MATCH); } @Test public void typeUseAndNonTypeUse_inWrongOrder() { refactoringHelper .addInputLines( "Test.java", // "interface T {", " @TypeUse @NonTypeUse T f();", "}") .addOutputLines( "Test.java", // "interface T {", " @NonTypeUse @TypeUse T f();", "}") .doTest(TEXT_MATCH); } @Test public void annotationOfEitherUse_isAllowedToRemainBeforeModifiers() { refactoringHelper .addInputLines( "Test.java", // "interface T {", " @NonTypeUse @EitherUse public T a();", " @NonTypeUse public @EitherUse T b();", "}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void constructor() { refactoringHelper .addInputLines( "Test.java", // "import javax.inject.Inject;", "class T {", " @Inject T(int x) {}", " @Inject T() {", " System.err.println();", " }", "}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void parameters_withAnnotationsOutOfOrder() { refactoringHelper .addInputLines( "Test.java", // "class T {", " Object foo(@TypeUse @NonTypeUse Object a) {", " return null;", " }", "}") .addOutputLines( "Test.java", // "class T {", " Object foo(@NonTypeUse @TypeUse Object a) {", " return null;", " }", "}") .doTest(TEXT_MATCH); } @Test public void parameters_withInterspersedModifiers() { refactoringHelper .addInputLines( "Test.java", // "class T {", " Object foo(@TypeUse final Object a) {", " return null;", " }", "}") .addOutputLines( "Test.java", // "class T {", " Object foo(final @TypeUse Object a) {", " return null;", " }", "}") .doTest(TEXT_MATCH); } @Test public void varKeyword() { refactoringHelper .addInputLines( "Test.java", "import com.google.errorprone.annotations.Var;", "class T {", " void m() {", " @Var var x = 1;", " x = 2;", " }", "}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void recordAnnotation() { assumeTrue(RuntimeVersion.isAtLeast16()); refactoringHelper .addInputLines( "Test.java", "public record Test(String bar) {", " @SuppressWarnings(\"unused\")", " public Test {}", "}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void interspersedJavadoc_enum() { refactoringHelper .addInputLines( "Test.java", // "enum Test {", " @NonTypeUse", " /** Javadoc! */", " ONE;", "}") .addOutputLines( "Test.java", // "enum Test {", " /** Javadoc! */", " @NonTypeUse", " ONE;", "}") .doTest(TEXT_MATCH); } @Test public void interspersedJavadoc_variableNoModifiers() { refactoringHelper .addInputLines( "Test.java", // "class Test {", " @NonTypeUse", " /** Javadoc! */", " int x;", "}") .addOutputLines( "Test.java", // "class Test {", " /** Javadoc! */", " @NonTypeUse", " int x;", "}") .doTest(TEXT_MATCH); } @Test public void variable_genericType_modifiers() { refactoringHelper .addInputLines( "Test.java", "import java.util.List;", "class Test {", " @TypeUse private List<?> x;", " @EitherUse private List<?> y;", " @NonTypeUse private List<?> z;", "}") .addOutputLines( "Test.java", "import java.util.List;", "class Test {", " private @TypeUse List<?> x;", " private @EitherUse List<?> y;", " @NonTypeUse private List<?> z;", "}") .doTest(TEXT_MATCH); } }
17,872
28.348112
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StreamResourceLeakTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static java.lang.String.format; import static org.junit.Assume.assumeTrue; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; import org.junit.Test; import org.junit.runner.RunWith; /** {@link StreamResourceLeakTest}Test */ @RunWith(TestParameterInjector.class) public class StreamResourceLeakTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(StreamResourceLeak.class, getClass()); @Test public void positive( @TestParameter({ "Files.newDirectoryStream(p)", "Files.newDirectoryStream(p, /* glob= */ \"*\")", "Files.newDirectoryStream(p, /* filter= */ path -> true)", "Files.list(p)", "Files.walk(p, /* maxDepth= */ 0)", "Files.walk(p)", "Files.find(p, /* maxDepth= */ 0, (path, a) -> true)", "try (Stream<String> stream =" + " Files.lines(p).collect(Collectors.toList()).stream()) {\n" + " stream.collect(Collectors.joining(\", \"));\n" + "}", "Files.lines(p).collect(Collectors.joining(\", \"))", }) String buggySnippet) { testHelper .addSourceLines( "Test.java", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Collectors;", "import java.util.stream.Stream;", "class Test {", " void f(Path p) throws IOException {", " // BUG: Diagnostic contains: should be closed", format(" %s;", buggySnippet), " }", "}") .doTest(); } @Test public void negative() { testHelper .addSourceLines( "Test.java", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Collectors;", "import java.util.stream.Stream;", "class Test {", " String f(Path p) throws IOException {", " try (Stream<String> stream = Files.lines(p).filter(l -> !l.isEmpty())) {", " stream.collect(Collectors.joining(\", \"));", " }", " try (Stream<String> stream = Files.lines(p)) {", " return stream.collect(Collectors.joining(\", \"));", " }", " }", "}") .doTest(); } @Test public void fix() { BugCheckerRefactoringTestHelper.newInstance(StreamResourceLeak.class, getClass()) .addInputLines( "in/Test.java", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Collectors;", "class Test {", " String f(Path p) throws IOException {", " return Files.lines(p).collect(Collectors.joining(\", \"));", " }", "}") .addOutputLines( "out/Test.java", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Collectors;", "import java.util.stream.Stream;", "class Test {", " String f(Path p) throws IOException {", " try (Stream<String> stream = Files.lines(p)) {", " return stream.collect(Collectors.joining(\", \"));", " }", " }", "}") .doTest(); } @Test public void fixVariable() { BugCheckerRefactoringTestHelper.newInstance(StreamResourceLeak.class, getClass()) .addInputLines( "in/Test.java", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Collectors;", "class Test {", " void f(Path p) throws IOException {", " String s = Files.lines(p).collect(Collectors.joining(\", \"));", " }", "}") .addOutputLines( "out/Test.java", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Collectors;", "import java.util.stream.Stream;", "class Test {", " void f(Path p) throws IOException {", " String s;", " try (Stream<String> stream = Files.lines(p)) {", " s = stream.collect(Collectors.joining(\", \"));", " }", " }", "}") .doTest(); } @Test public void ternary() { testHelper .addSourceLines( "Test.java", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Collectors;", "import java.util.stream.Stream;", "class Test {", " String f(Path p) throws IOException {", " String r;", " // BUG: Diagnostic contains:", " try (Stream<String> stream = Files.lines(p).count() > 0 ? null : null) {", " r = stream.collect(Collectors.joining(\", \"));", " }", " try (Stream<String> stream = true ? null : Files.lines(p)) {", " r = stream.collect(Collectors.joining(\", \"));", " }", " try (Stream<String> stream = true ? Files.lines(p) : null) {", " r = stream.collect(Collectors.joining(\", \"));", " }", " return r;", " }", "}") .doTest(); } @Test public void returnFromMustBeClosedMethod() { testHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.MustBeClosed;", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Stream;", "class Test {", " @MustBeClosed", " Stream<String> f(Path p) throws IOException {", " return Files.lines(p);", " }", "}") .doTest(); } @Test public void returnFromMustBeClosedMethodWithChaining() { testHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.MustBeClosed;", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Stream;", "class Test {", " @MustBeClosed", " Stream<String> f(Path p) throws IOException {", " return Files.list(p).map(Path::toString); // OK due to @MustBeClosed", " }", " Stream<String> g(Path p) throws IOException {", " // BUG: Diagnostic contains: should be closed", " return Files.list(p).map(Path::toString);", " }", "}") .doTest(); } @Test public void moreRefactorings() { BugCheckerRefactoringTestHelper.newInstance(StreamResourceLeak.class, getClass()) .addInputLines( "in/Test.java", "import java.io.IOException;", "import java.nio.file.DirectoryStream;", "import java.nio.file.Files;", "import java.nio.file.Path;", "class Test {", " void f(Path p) throws IOException {", " DirectoryStream<Path> l = Files.newDirectoryStream(p);", " for (Path x : Files.newDirectoryStream(p)) {", " System.err.println(x);", " }", " System.err.println(l);", " System.err.println(Files.newDirectoryStream(p));", " }", "}") .addOutputLines( "out/Test.java", "import java.io.IOException;", "import java.nio.file.DirectoryStream;", "import java.nio.file.Files;", "import java.nio.file.Path;", "class Test {", " void f(Path p) throws IOException {", " try (DirectoryStream<Path> l = Files.newDirectoryStream(p)) {", " try (DirectoryStream<Path> stream = Files.newDirectoryStream(p)) {", " for (Path x : stream) {", " System.err.println(x);", " }", " }", " System.err.println(l);", " }", " try (DirectoryStream<Path> stream = Files.newDirectoryStream(p)) {", " System.err.println(stream);", " }", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void defaultMethod() { testHelper .addSourceLines( "Test.java", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.nio.file.DirectoryStream;", "interface I {", " default DirectoryStream<Path> f(Path path) throws IOException {", " // BUG: Diagnostic contains: should be closed", " return Files.newDirectoryStream(path);", " }", "}") .doTest(); } @Test public void record() { assumeTrue(RuntimeVersion.isAtLeast16()); testHelper .addSourceLines( "ExampleRecord.java", "package example;", "import java.io.IOException;", "import java.nio.file.Files;", "import java.nio.file.Path;", "import java.util.stream.Stream;", "record ExampleRecord(Path path) {", " public Stream<Path> list() throws IOException {", " // BUG: Diagnostic contains: should be closed", " return Files.list(path);", " }", "}") .doTest(); } }
11,272
35.364516
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MockNotUsedInProductionTest.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class MockNotUsedInProductionTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(MockNotUsedInProduction.class, getClass()); private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(MockNotUsedInProduction.class, getClass()); @Test public void neverUsed() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "class Test {", " public Object test() {", " // BUG: Diagnostic contains:", " Test test = mock(Test.class);", " when(test.test()).thenCallRealMethod();", " return null;", " }", "}") .doTest(); } @Test public void neverUsed_butInitializedSeparately() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "class Test {", " private Test test;", " public Object test() {", " // BUG: Diagnostic contains:", " test = mock(Test.class);", " when(test.test()).thenCallRealMethod();", " return null;", " }", "}") .doTest(); } @Test public void spyNeverUsed() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.spy;", "import static org.mockito.Mockito.verify;", "class Test {", " public Object test() {", " // BUG: Diagnostic contains:", " Test test = spy(new Test());", " verify(test).test();", " return null;", " }", "}") .doTest(); } @Test public void nonStaticVerify_countsAsUse() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.spy;", "class Test {", " public Object test() {", " Test test = spy(new Test());", " verify(test).test();", " return null;", " }", " Test verify (Test t) {", " return t;", " }", "}") .doTest(); } @Test public void passedToProduction() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "class Test {", " public Object test() {", " Test test = mock(Test.class);", " when(test.test()).thenCallRealMethod();", " return test.test();", " }", "}") .doTest(); } @Test public void possiblyBound() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import com.google.inject.testing.fieldbinder.Bind;", "import org.mockito.Mock;", "class Test {", " @Bind @Mock public Test test;", " public Object test() {", " when(test.test()).thenCallRealMethod();", " return null;", " }", "}") .doTest(); } @Test public void publicField() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import org.mockito.Mock;", "class Test {", " @Mock public Test test;", " public Object test() {", " when(test.test()).thenCallRealMethod();", " return null;", " }", "}") .doTest(); } @Test public void qualifiedWithThis_stillSeen() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import org.mockito.Mock;", "class Test {", " @Mock private Test test;", " public Test test() {", " return this.test;", " }", "}") .doTest(); } @Test public void privateField() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import org.mockito.Mock;", "class Test {", " // BUG: Diagnostic contains:", " @Mock private Test test;", " public Object test() {", " when(test.test()).thenCallRealMethod();", " return null;", " }", "}") .doTest(); } @Test public void injectMocks_noFinding() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import org.mockito.InjectMocks;", "import org.mockito.Mock;", "class Test {", " @Mock private Test test;", " @InjectMocks Test t;", " public Object test() {", " when(test.test()).thenCallRealMethod();", " return null;", " }", "}") .doTest(); } @Test public void suppressionWorks() { helper .addSourceLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import org.mockito.Mock;", "class Test {", " @SuppressWarnings(\"MockNotUsedInProduction\")", " @Mock private Test test;", " public Object test() {", " when(test.test()).thenCallRealMethod();", " return null;", " }", "}") .doTest(); } @Test public void refactoring() { refactoring .addInputLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import org.mockito.Mock;", "class Test {", " @Mock private Test test;", " public Object test() {", " when(test.test()).thenCallRealMethod();", " return null;", " }", "}") .addOutputLines( "Test.java", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import org.mockito.Mock;", "class Test {", " public Object test() {", " return null;", " }", "}") .doTest(); } @Test public void refactoringNested() { refactoring .addInputLines( "Test.java", "import static org.mockito.Mockito.doAnswer;", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import org.mockito.Mock;", "class Test {", " @Mock private Test test;", " public Object test() {", " doAnswer(a -> { when(test.test()).thenReturn(null); return null;" + " }).when(test).test();", " return null;", " }", "}") .addOutputLines( "Test.java", "import static org.mockito.Mockito.doAnswer;", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import org.mockito.Mock;", "class Test {", " public Object test() {", " return null;", " }", "}") .doTest(); } }
9,019
29.576271
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IncomparableTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link Incomparable}Test */ @RunWith(JUnit4.class) public class IncomparableTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(Incomparable.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import java.util.TreeMap;", "import java.util.TreeSet;", "import java.util.Set;", "import java.util.Collections;", "final class Test {", " void f() {", " // BUG: Diagnostic contains: Test", " new TreeMap<Test, String>();", " // BUG: Diagnostic contains: Test", " new TreeSet<Test>();", " // BUG: Diagnostic contains: Test", " Set<Test> xs = Collections.synchronizedSet(new TreeSet<>());", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.TreeMap;", "import java.util.TreeSet;", "import java.util.Set;", "import java.util.Collections;", "class Test {", " void f() {", " new TreeMap<String, Test>();", " new TreeSet<String>();", " Set<String> xs = Collections.synchronizedSet(new TreeSet<>());", " }", "}") .doTest(); } }
2,294
31.323944
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ProtectedMembersInFinalClassTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link ProtectedMembersInFinalClass} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class ProtectedMembersInFinalClassTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(ProtectedMembersInFinalClass.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ProtectedMembersInFinalClass.class, getClass()); @Test public void positiveCases() { testHelper .addInputLines( "in/Test.java", "final class Test {", " protected void methodOne() {}", " protected void methodTwo() {}", " protected String var1;", " protected int var2;", "}") .addOutputLines( "out/Test.java", "final class Test {", " void methodOne() {}", " void methodTwo() {}", " String var1;", " int var2;", "}") .doTest(); } @Test public void negativeCases() { compilationHelper .addSourceLines( "in/Base.java", // "class Base {", " protected void protectedMethod() {}", "}") .addSourceLines( "in/Test.java", "final class Test extends Base {", " public void publicMethod() {}", " void packageMethod() {}", " private void privateMethod() {}", " @Override protected void protectedMethod() {}", " public int publicField;", " int packageField;", " private int privateField;", "}") .doTest(); } @Test public void diagnosticStringWithMultipleMemberMatches() { compilationHelper .addSourceLines( "in/Test.java", "final class Test {", " // BUG: Diagnostic contains: Make members of final classes package-private:" + " methodOne, methodTwo, fieldOne, fieldTwo", " protected void methodOne() {}", " protected void methodTwo() {}", " public void publicMethod() {}", " private void privateMethod() {}", " void packageMethod() {}", " protected int fieldOne;", " protected long fieldTwo;", " public int publicField;", " int packageField;", " private int privateField;", "}") .doTest(); } @Test public void methodSuppression() { compilationHelper .addSourceLines( "in/Test.java", "final class Test {", " @SuppressWarnings(\"ProtectedMembersInFinalClass\")", " protected void methodOne() {}", "}") .doTest(); } @Test public void constructorFindingDescription() { compilationHelper .addSourceLines( "Test.java", "final class Test {", " // BUG: Diagnostic contains: Test", " protected Test() {}", "}") .doTest(); } }
4,036
30.787402
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/YodaConditionTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class YodaConditionTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(YodaCondition.class, getClass()); @Test public void primitive() { refactoring .addInputLines( "Test.java", "class Test {", " boolean yoda(int a) {", " return 4 == a;", " }", " boolean notYoda(int a) {", " return a == 4;", " }", "}") .addOutputLines( "Test.java", "class Test {", " boolean yoda(int a) {", " return a == 4;", " }", " boolean notYoda(int a) {", " return a == 4;", " }", "}") .doTest(); } @Test public void enums() { refactoring .addInputLines( "E.java", "enum E {", " A, B;", " boolean foo(E e) {", " return this == e;", " }", "}") .expectUnchanged() .addInputLines( "Test.java", "class Test {", " boolean yoda(E a) {", " return E.A == a;", " }", " boolean notYoda(E a) {", " return a == E.A;", " }", "}") .addOutputLines( "Test.java", "class Test {", " boolean yoda(E a) {", " return a == E.A;", " }", " boolean notYoda(E a) {", " return a == E.A;", " }", "}") .doTest(); } @Test public void nullIntolerantFix() { refactoring .addInputLines("E.java", "enum E {A, B}") .expectUnchanged() .addInputLines( "Test.java", "class Test {", " boolean yoda(E a) {", " return E.A.equals(a);", " }", "}") .addOutputLines( "Test.java", "class Test {", " boolean yoda(E a) {", " return a.equals(E.A);", " }", "}") .setFixChooser(FixChoosers.SECOND) .doTest(); } @Test public void nullTolerantFix() { refactoring .addInputLines("E.java", "enum E {A, B}") .expectUnchanged() .addInputLines( "Test.java", "class Test {", " boolean yoda(E a) {", " return E.A.equals(a);", " }", "}") .addOutputLines( "Test.java", "import java.util.Objects;", "class Test {", " boolean yoda(E a) {", " return Objects.equals(a, E.A);", " }", "}") .doTest(); } @Test public void provablyNonNull_nullIntolerantFix() { refactoring .addInputLines("E.java", "enum E {A, B}") .expectUnchanged() .addInputLines( "Test.java", "class Test {", " boolean yoda(E a) {", " if (a != null) {", " return E.A.equals(a);", " }", " return true;", " }", "}") .addOutputLines( "Test.java", "class Test {", " boolean yoda(E a) {", " if (a != null) {", " return a.equals(E.A);", " }", " return true;", " }", "}") .doTest(); } }
4,513
26.357576
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CannotMockMethodTest.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class CannotMockMethodTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(CannotMockMethod.class, getClass()); @Test public void whenCall_flagged() { compilationHelper .addSourceLines( "Test.java", "import static org.mockito.Mockito.when;", "class Test {", " final Integer foo() {", " return 1;", " }", " void test() {", " // BUG: Diagnostic contains:", " when(this.foo());", " }", "}") .doTest(); } @Test public void whenCall_forStaticMethod_flagged() { compilationHelper .addSourceLines( "Test.java", "import static org.mockito.Mockito.when;", "class Test {", " static Integer foo() {", " return 1;", " }", " void test() {", " // BUG: Diagnostic contains:", " when(foo());", " }", "}") .doTest(); } @Test public void verifyCall_flagged() { compilationHelper .addSourceLines( "Test.java", "import static org.mockito.Mockito.verify;", "class Test {", " final Integer foo() {", " return 1;", " }", " void test() {", " // BUG: Diagnostic contains:", " verify(this).foo();", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import static org.mockito.Mockito.when;", "class Test {", " Integer foo() {", " return 1;", " }", " void test() {", " when(this.foo());", " }", "}") .doTest(); } }
2,797
26.98
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ICCProfileGetInstanceTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ICCProfileGetInstanceTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(ICCProfileGetInstance.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "Test.java", "import java.awt.color.ICC_Profile;", "class Test {", " void f(String s) throws Exception {", " // BUG: Diagnostic contains:", " ICC_Profile.getInstance(s);", " }", "}") .doTest(); } @Test public void negative() { testHelper .addSourceLines( "Test.java", "import java.awt.color.ICC_Profile;", "class Test {", " void f(byte[] b) throws Exception {", " ICC_Profile.getInstance(b);", " }", "}") .doTest(); } }
1,718
28.637931
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/FloatingPointAssertionWithinEpsilonTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link FloatingPointAssertionWithinEpsilon} bug pattern. * * @author ghm@google.com (Graeme Morgan) */ @RunWith(JUnit4.class) public final class FloatingPointAssertionWithinEpsilonTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(FloatingPointAssertionWithinEpsilon.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceFile("FloatingPointAssertionWithinEpsilonPositiveCases.java") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceFile("FloatingPointAssertionWithinEpsilonNegativeCases.java") .doTest(); } @Test public void fixes() { BugCheckerRefactoringTestHelper.newInstance( FloatingPointAssertionWithinEpsilon.class, getClass()) .addInput("FloatingPointAssertionWithinEpsilonPositiveCases.java") .addOutput("FloatingPointAssertionWithinEpsilonPositiveCases_expected.java") .doTest(TestMode.AST_MATCH); } }
1,976
32.508475
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnit4ClassUsedInJUnit3Test.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author jdesprez@google.com (Julien Desprez) */ @RunWith(JUnit4.class) public class JUnit4ClassUsedInJUnit3Test { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(JUnit4ClassUsedInJUnit3.class, getClass()); @Test public void negative_regular_junit3() { compilationHelper .addSourceLines( "Foo.java", "import junit.framework.TestCase;", "public class Foo extends TestCase {", " public void testName1() { System.out.println(\"here\");}", " public void testName2() {}", "}") .doTest(); } @Test public void negative_assume_in_junit4() { compilationHelper .addSourceLines( "Foo.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.junit.Assume;", "import org.junit.Test;", "@RunWith(JUnit4.class)", "public class Foo {", " @Test", " public void testOne() {", " Assume.assumeTrue(true);", " }", "}") .doTest(); } @Test public void negative_annotation_in_junit4() { compilationHelper .addSourceLines( "Foo.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.junit.Rule;", "import org.junit.rules.TemporaryFolder;", "import org.junit.Test;", "import org.junit.Ignore;", "@RunWith(JUnit4.class)", "public class Foo {", " @Rule public TemporaryFolder folder= new TemporaryFolder();", " @Ignore", " @Test", " public void testOne() {}", " @Test public void testTwo() {}", "}") .doTest(); } @Test public void positive_assume_in_test() { compilationHelper .addSourceLines( "Foo.java", "import junit.framework.TestCase;", "import org.junit.Test;", "import org.junit.Assume;", "public class Foo extends TestCase {", " public void testName1() { System.out.println(\"here\");}", " public void testName2() {", " // BUG: Diagnostic contains: Assume", " Assume.assumeTrue(true);", " }", " public void testName3() {}", "}") .doTest(); } @Test public void positive_assume_in_setUp() { compilationHelper .addSourceLines( "Foo.java", "import junit.framework.TestCase;", "import org.junit.Test;", "import org.junit.Assume;", "public class Foo extends TestCase {", " @Override public void setUp() {", " // BUG: Diagnostic contains: Assume", " Assume.assumeTrue(true);", " }", " public void testName1() {}", "}") .doTest(); } @Test public void positive_assume_in_tear_down() { compilationHelper .addSourceLines( "Foo.java", "import junit.framework.TestCase;", "import org.junit.Test;", "import org.junit.Assume;", "public class Foo extends TestCase {", " @Override public void tearDown() {", " // BUG: Diagnostic contains: Assume", " Assume.assumeTrue(true);", " }", " public void testName1() {}", "}") .doTest(); } @Test public void positive_static_assume_in_test() { compilationHelper .addSourceLines( "Foo.java", "import junit.framework.TestCase;", "import org.junit.Test;", "import static org.junit.Assume.assumeTrue;", "public class Foo extends TestCase {", " public void testName1() { System.out.println(\"here\");}", " public void testName2() {", " // BUG: Diagnostic contains: Assume", " assumeTrue(true);", " }", " public void testName3() {}", "}") .doTest(); } @Test public void positive_ignore_on_test() { compilationHelper .addSourceLines( "Foo.java", "import junit.framework.TestCase;", "import org.junit.Ignore;", "public class Foo extends TestCase {", " public void testName1() {}", " // BUG: Diagnostic contains: @Ignore", " @Ignore", " public void testName2() {}", "}") .doTest(); } @Test public void positive_ignore_on_class() { compilationHelper .addSourceLines( "Foo.java", "import junit.framework.TestCase;", "import org.junit.Ignore;", "// BUG: Diagnostic contains: @Ignore", "@Ignore", "public class Foo extends TestCase {", " public void testName1() {}", " public void testName2() {}", "}") .doTest(); } @Test public void positive_rule_in_junit3() { compilationHelper .addSourceLines( "Foo.java", "import junit.framework.TestCase;", "import org.junit.Rule;", "import org.junit.rules.TemporaryFolder;", "public class Foo extends TestCase {", " // BUG: Diagnostic contains: @Rule", " @Rule public TemporaryFolder folder = new TemporaryFolder();", " public void testName1() {}", " public void testName2() {}", "}") .doTest(); } }
6,568
30.280952
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SameNameButDifferentTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link SameNameButDifferent}. */ @RunWith(JUnit4.class) public final class SameNameButDifferentTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(SameNameButDifferent.class, getClass()); private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(SameNameButDifferent.class, getClass()); @Test public void simpleNameClash() { helper .addSourceLines( "A.java", // "class A {", " class Supplier {}", "}") .addSourceLines( "B.java", "import java.util.function.Supplier;", "class B {", " // BUG: Diagnostic contains:", " Supplier<Integer> supplier = () -> 1;", " class C extends A {", " // BUG: Diagnostic contains:", " Supplier supplier2 = new Supplier();", " }", "}") .doTest(); } @Test public void simpleNameRefactoring() { refactoring .addInputLines( "A.java", // "package foo;", "class A {", " class Supplier {}", "}") .expectUnchanged() .addInputLines( "B.java", "package foo;", "import java.util.function.Supplier;", "class B {", " Supplier<Integer> supplier = () -> 1;", " class C extends A {", " Supplier supplier2 = new Supplier();", " Class<Supplier> clazz = Supplier.class;", " }", "}") .addOutputLines( "B.java", "package foo;", "import java.util.function.Supplier;", "class B {", " Supplier<Integer> supplier = () -> 1;", " class C extends A {", " A.Supplier supplier2 = new A.Supplier();", " Class<A.Supplier> clazz = A.Supplier.class;", " }", "}") .doTest(); } @Test public void nestedClassNameClash() { refactoring .addInputLines( "A.java", // "package foo;", "class A {", " static class B {", " static class C {}", " }", "}") .expectUnchanged() .addInputLines( "D.java", "package foo;", "class D {", " static class B {", " static class C {}", " }", "}") .expectUnchanged() .addInputLines( "E.java", "package foo;", "import foo.A.B;", "class E {", " B.C foo = new B.C();", " class C extends D {", " B.C bar = new B.C();", " }", "}") .addOutputLines( "E.java", "package foo;", "import foo.A.B;", "class E {", " A.B.C foo = new A.B.C();", " class C extends D {", " D.B.C bar = new D.B.C();", " }", "}") .doTest(); } @Test public void negativeAlreadyQualified() { helper .addSourceLines( "A.java", // "class A {", " class Supplier {}", "}") .addSourceLines( "B.java", "import java.util.function.Supplier;", "class B {", " Supplier<Integer> supplier = () -> 1;", " class C extends A {", " A.Supplier supplier2 = new A.Supplier();", " }", "}") .doTest(); } @Test public void neverShadowing() { helper .addSourceLines( "A.java", "class A {", " public void foo() {", " class B {}", " B b = new B();", " }", " public void bar() {", " class B {}", " B b = new B();", " }", "}") .doTest(); } @Test public void doesNotThrowConcurrentModification_whenFilteringNonShadowingTypeNames() { helper .addSourceLines( "A.java", "class A {", " public void foo() {", " class B {}", " B b = new B();", " }", " public void bar() {", " class B {}", " class C {}", " C c = new C();", " B b = new B();", " }", "}") .doTest(); } @Test public void referencesSelf() { helper .addSourceLines( "B.java", "import java.util.function.Supplier;", "class B {", " Supplier<Integer> supplier = () -> 1;", " class C {", " class Supplier {", " Supplier s = new Supplier();", " }", " }", "}") .doTest(); } }
5,930
27.109005
90
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RequiredModifiersCheckerTest.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import javax.tools.JavaFileObject; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link RequiredModifiersChecker}. * * @author sgoldfeder@google.com (Steven Goldfeder) */ @RunWith(JUnit4.class) public class RequiredModifiersCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(RequiredModifiersChecker.class, getClass()) .addSourceLines( "test/AbstractRequired.java", "package test;", "import static javax.lang.model.element.Modifier.ABSTRACT;", "import com.google.errorprone.annotations.RequiredModifiers;", "@RequiredModifiers(ABSTRACT)", "public @interface AbstractRequired {", "}") .addSourceLines( "test/PublicAndFinalRequired.java", "package test;", "import static javax.lang.model.element.Modifier.FINAL;", "import static javax.lang.model.element.Modifier.PUBLIC;", "import com.google.errorprone.annotations.RequiredModifiers;", "@RequiredModifiers({PUBLIC, FINAL})", "public @interface PublicAndFinalRequired {", "}"); JavaFileObject abstractRequired; JavaFileObject publicAndFinalRequired; @Test public void annotationWithRequiredModifiersMissingOnClassFails() { compilationHelper .addSourceLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.AbstractRequired;", "// BUG: Diagnostic contains: The annotation '@AbstractRequired' has specified that it" + " must be used together with the following modifiers: [abstract]", "@AbstractRequired public class RequiredModifiersTestCase {", "}") .doTest(); } @Test public void annotationWithRequiredModifiersMissingOnFieldFails1() { compilationHelper .addSourceLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.PublicAndFinalRequired;", "public class RequiredModifiersTestCase {", " // BUG: Diagnostic contains: The annotation '@PublicAndFinalRequired' has specified" + " that it must be used together with the following modifiers: [public, final]", " @PublicAndFinalRequired int n = 0;", "}") .doTest(); } @Test public void annotationWithRequiredModifiersMissingOnFieldFails2() { compilationHelper .addSourceLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.PublicAndFinalRequired;", "public class RequiredModifiersTestCase {", " // BUG: Diagnostic contains: The annotation '@PublicAndFinalRequired' has specified" + " that it must be used together with the following modifiers: [final]", " @PublicAndFinalRequired public int n = 0;", "}") .doTest(); } @Test public void annotationWithRequiredModifiersMissingOnFieldFails3() { compilationHelper .addSourceLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.PublicAndFinalRequired;", "public class RequiredModifiersTestCase {", " // BUG: Diagnostic contains: The annotation '@PublicAndFinalRequired' has specified" + " that it must be used together with the following modifiers: [public]", " @PublicAndFinalRequired final int n = 0;", "}") .doTest(); } @Test public void annotationWithRequiredModifiersMissingOnMethodFails1() { compilationHelper .addSourceLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.PublicAndFinalRequired;", "public class RequiredModifiersTestCase {", " // BUG: Diagnostic contains: The annotation '@PublicAndFinalRequired' has specified" + " that it must be used together with the following modifiers: [public, final]", " @PublicAndFinalRequired private void foo(){}", "}") .doTest(); } @Test public void annotationWithRequiredModifiersMissingOnMethodFails2() { compilationHelper .addSourceLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.PublicAndFinalRequired;", "public class RequiredModifiersTestCase {", " // BUG: Diagnostic contains: The annotation '@PublicAndFinalRequired' has specified" + " that it must be used together with the following modifiers: [final]", " @PublicAndFinalRequired public void foo(){}", "}") .doTest(); } @Test public void annotationWithRequiredModifiersMissingOnMethodFails3() { compilationHelper .addSourceLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.PublicAndFinalRequired;", "public class RequiredModifiersTestCase {", " // BUG: Diagnostic contains: The annotation '@PublicAndFinalRequired' has specified" + " that it must be used together with the following modifiers: [public]", " @PublicAndFinalRequired final void foo(){}", "}") .doTest(); } @Test public void hasRequiredModifiersSucceeds() { compilationHelper .addSourceLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.AbstractRequired;", "abstract class RequiredModifiersTestCase {}") .doTest(); } // Regression test for #313 @Test public void negativeNestedAnnotations() { compilationHelper .addSourceLines( "test/Test.java", "package test;", "@interface Foos {", " Foo[] value();", "}", "@interface Foo {", "}", "@Foos({@Foo, @Foo}) public class Test {", "}") .doTest(); } // Regression test for #313 @Test public void negativePackageAnnotation() { compilationHelper .addSourceLines( "testdata/Anno.java", "package testdata;", "import java.lang.annotation.Target;", "import java.lang.annotation.ElementType;", "@Target(ElementType.PACKAGE)", "public @interface Anno {", "}") .addSourceLines("testdata/package-info.java", "@Anno", "package testdata;") .doTest(); } @Test public void refactoring() { BugCheckerRefactoringTestHelper.newInstance(RequiredModifiersChecker.class, getClass()) .addInputLines( "test/AbstractRequired.java", "package test;", "import static javax.lang.model.element.Modifier.ABSTRACT;", "import com.google.errorprone.annotations.RequiredModifiers;", "@RequiredModifiers(ABSTRACT)", "public @interface AbstractRequired {", "}") .expectUnchanged() .addInputLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.AbstractRequired;", "@AbstractRequired class RequiredModifiersTestCase {", "}") .addOutputLines( "test/RequiredModifiersTestCase.java", "package test;", "import test.AbstractRequired;", "@AbstractRequired abstract class RequiredModifiersTestCase {", "}") .doTest(); } }
8,562
35.909483
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessarySetDefaultTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ClassToInstanceMap; import com.google.common.testing.ArbitraryInstances; import com.google.errorprone.BugCheckerRefactoringTestHelper; import java.lang.reflect.Field; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link UnnecessarySetDefault}Test */ @RunWith(JUnit4.class) public class UnnecessarySetDefaultTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(UnnecessarySetDefault.class, getClass()); @Test public void refactoring() { testHelper .addInputLines( "in/Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.common.testing.NullPointerTester;", "class Test {", " {", " NullPointerTester tester = new NullPointerTester();", " tester.setDefault(String.class, \"\");", " tester", " .setDefault(ImmutableList.class, ImmutableList.of(42))", " .setDefault(ImmutableList.class, ImmutableList.of())", " .setDefault(ImmutableList.class, ImmutableList.<String>of())", " .setDefault(ImmutableList.class, ImmutableList.of(42));", " }", "}") .addOutputLines( "out/Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.common.testing.NullPointerTester;", "class Test {", " {", " NullPointerTester tester = new NullPointerTester();", " tester", " .setDefault(ImmutableList.class, ImmutableList.of(42))", " .setDefault(ImmutableList.class, ImmutableList.of(42));", " }", "}") .doTest(); } @Test public void exhaustive() throws ReflectiveOperationException { Field f = ArbitraryInstances.class.getDeclaredField("DEFAULTS"); f.setAccessible(true); ClassToInstanceMap<?> actual = (ClassToInstanceMap<?>) f.get(null); assertThat(UnnecessarySetDefault.DEFAULTS.keySet()) .containsAnyIn( actual.keySet().stream().map(Class::getCanonicalName).collect(toImmutableList())); } }
3,088
37.6125
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BadShiftAmountTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author Bill Pugh (bill.pugh@gmail.com) */ @RunWith(JUnit4.class) public class BadShiftAmountTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(BadShiftAmount.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("BadShiftAmountPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("BadShiftAmountNegativeCases.java").doTest(); } }
1,291
29.046512
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InitializeInlineTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link InitializeInline}. */ @RunWith(JUnit4.class) public final class InitializeInlineTest { private final BugCheckerRefactoringTestHelper compilationHelper = BugCheckerRefactoringTestHelper.newInstance(InitializeInline.class, getClass()); @Test public void simple() { compilationHelper .addInputLines( "Test.java", "class Test {", " void test() {", " int a;", " a = 1;", " final int b;", " b = 1;", " }", "}") .addOutputLines( "Test.java", "class Test {", " void test() {", " int a = 1;", " final int b = 1;", " }", "}") .doTest(); } @Test public void multipleAssignment_noMatch() { compilationHelper .addInputLines( "Test.java", "class Test {", " void test() {", " int a;", " a = 1;", " a = 2;", " }", "}") .expectUnchanged() .doTest(); } @Test public void multipleAssignment_withinBlock() { compilationHelper .addInputLines( "Test.java", "class Test {", " int test() {", " int a;", " if (true) {", " a = 1;", " return a;", " }", " a = 2;", " return a;", " }", "}") .expectUnchanged() .doTest(); } @Test public void assignedWithinTry_noMatch() { compilationHelper .addInputLines( "Test.java", "class Test {", " int test() {", " int c;", " try {", " c = 1;", " } catch (Exception e) {", " throw e;", " }", " return c;", " }", "}") .expectUnchanged() .doTest(); } @Test public void unstylishBlocks() { compilationHelper .addInputLines( "Test.java", "class Test {", " int test() {", " int c;", " if (hashCode() == 0) c = 1;", " else c = 2;", " return c;", " }", "}") .expectUnchanged() .doTest(); } }
3,293
24.937008
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/PreferredInterfaceTypeTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link PreferredInterfaceType}. */ @RunWith(JUnit4.class) public final class PreferredInterfaceTypeTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(PreferredInterfaceType.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(PreferredInterfaceType.class, getClass()); @Test public void assigned() { refactoringHelper .addInputLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " private static final Iterable<Integer> FOO = new ArrayList<>();", " public static final Iterable<Integer> BAR = new ArrayList<>();", " public static final Iterable<Integer> RAW = new ArrayList<>();", "}") .addOutputLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " private static final List<Integer> FOO = new ArrayList<>();", " public static final List<Integer> BAR = new ArrayList<>();", " public static final List<Integer> RAW = new ArrayList<>();", "}") .doTest(); } @Test public void assignedMultipleTypesCompatibleWithSuper() { testHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.Collection;", "import java.util.HashSet;", "class Test {", " void test() {", " Collection<Integer> foo = new ArrayList<>();", " foo = new HashSet<>();", " }", "}") .doTest(); } @Test public void referringToCollectionAsIterable_noFinding() { testHelper .addSourceLines( "Test.java", "import java.util.Collection;", "import java.util.HashSet;", "class Test {", " Collection<Integer> test() {", " Iterable<Integer> foo = test();", " return null;", " }", "}") .doTest(); } @Test public void alreadyTightenedType() { testHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " void test() {", " List<Integer> foo = new ArrayList<>();", " }", "}") .doTest(); } @Test public void parameters_notFlagged() { testHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " void test(Iterable<Object> xs) {", " xs = new ArrayList<>();", " }", "}") .doTest(); } @Test public void nonPrivateNonFinalFields_notFlagged() { testHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " Iterable<Object> xs;", " Test(List<Object> xs) {", " this.xs = xs;", " }", "}") .doTest(); } @Test public void nonFinalButPrivateFields() { testHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " // BUG: Diagnostic contains:", " private Iterable<Object> xs;", " void test(List<Object> xs) {", " this.xs = xs;", " }", "}") .doTest(); } @Test public void nonFinalButFieldInPrivateClass() { testHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " private static class Inner {", " // BUG: Diagnostic contains:", " Iterable<Object> xs;", " void test(List<Object> xs) {", " this.xs = xs;", " }", " }", "}") .doTest(); } @Test public void immutables() { refactoringHelper .addInputLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " void test() {", " List<Integer> foo = ImmutableList.of(1);", " }", "}") .addOutputLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " void test() {", " ImmutableList<Integer> foo = ImmutableList.of(1);", " }", "}") .doTest(); } @Test public void immutableMap() { refactoringHelper .addInputLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "import java.util.Map;", "class Test {", " void test() {", " Map<Integer, Integer> foo = ImmutableMap.of(1, 1);", " }", "}") .addOutputLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "import java.util.Map;", "class Test {", " void test() {", " ImmutableMap<Integer, Integer> foo = ImmutableMap.of(1, 1);", " }", "}") .doTest(); } @Test public void constructor_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", // "class Test {", " Test() { }", "}") .doTest(); } @Test public void returnTypeVoid_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", // "class Test {", " void foo() { }", "}") .doTest(); } @Test public void nonFinalNonPrivateNonStaticMethodInNonFinalClass_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " List<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void providesAnnotatedMethod_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import dagger.Provides;", "import java.util.List;", "class Test {", " @Provides", " static List<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void producesAnnotatedMethod_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import dagger.producers.Produces;", "import java.util.List;", "class Test {", " @Produces", " static List<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void nonFinalNonPrivateNonStaticMethodInFinalClass() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "final class Test {", " // BUG: Diagnostic contains: immutable type", " List<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void finalMethodInNonFinalClass() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " // BUG: Diagnostic contains: final ImmutableList<String> foo()", " final List<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void privateMethodInNonFinalClass() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " // BUG: Diagnostic contains: private ImmutableList<String> foo()", " private List<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void staticMethodInNonFinalClass() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " // BUG: Diagnostic contains: static ImmutableList<String> foo()", " static List<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void returnTypeImmutableList_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " final ImmutableList<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void returnTypeImmutableCollection_suggestsTighterType() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableCollection;", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " // BUG: Diagnostic contains: convey more information", " final ImmutableCollection<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void returnTypeList_singleReturnStatementImmutableList_suggestsImmutableList() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " // BUG: Diagnostic contains: final ImmutableList<String> foo()", " final List<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void returnTypeList_singleReturnStatementArrayList_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " final List<String> foo() {", " return new ArrayList<>();", " }", "}") .doTest(); } @Test public void returnTypeList_singleReturnStatementList_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " final List<String> foo() {", " return new ArrayList<>();", " }", "}") .doTest(); } @Test public void returnTypeList_multipleReturnStatementsImmutableList_suggestsImmutableList() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " // BUG: Diagnostic contains: ImmutableList<String> foo()", " final List<String> foo() {", " if (true) {", " return ImmutableList.of();", " } else {", " return ImmutableList.of();", " }", " }", "}") .doTest(); } @Test public void returnTypeList_multipleReturnStatementsArrayListImmutableList_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " final List<String> foo() {", " if (true) {", " return ImmutableList.of();", " } else {", " return new ArrayList<>();", " }", " }", "}") .doTest(); } @Test public void returnTypeList_multipleReturnStatementsImmutableSetImmutableList_suggestsImmutableCollection() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.common.collect.ImmutableSet;", "import java.util.Collection;", "class Test {", " // BUG: Diagnostic contains: ImmutableCollection<String> foo()", " final Collection<String> foo() {", " if (true) {", " return ImmutableList.of();", " } else {", " return ImmutableSet.of();", " }", " }", "}") .doTest(); } @Test public void returnTypeList_multipleReturnStatementsImmutableSetImmutableMap_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.common.collect.ImmutableMap;", "class Test {", " final Object foo() {", " if (true) {", " return ImmutableList.of();", " } else {", " return ImmutableMap.of();", " }", " }", "}") .doTest(); } @Test public void returnTypeList_multipleReturnStatementsImmutableMapImmutableBiMap_suggestsImmutableMap() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableBiMap;", "import com.google.common.collect.ImmutableMap;", "import java.util.Map;", "class Test {", " // BUG: Diagnostic contains: final ImmutableMap<String, String> foo()", " final Map<String, String> foo() {", " if (true) {", " return ImmutableBiMap.of();", " } else {", " return ImmutableMap.of();", " }", " }", "}") .doTest(); } @Test public void returnTypeList_insideAnonymousNested_suggestsImmutableList() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.inject.Provider;", "import java.util.List;", "class Test {", " private static final int getFooLength() {", " final Provider<List<String>> fooProvider = ", " new Provider<List<String>>() {", " @Override", " // BUG: Diagnostic contains: ImmutableList<String> get", " public List<String> get() {", " return ImmutableList.of(\"foo\", \"bar\");", " }", " };", " List<String> foo = fooProvider.get();", " return foo.size();", " }", "}") .doTest(); } @Test public void returnTypeList_anonymousLambda_suggestsNothing() { testHelper .addSourceLines( "ApplyInterface.java", "import java.util.function.Function;", "import java.util.List;", "public interface ApplyInterface {", " int applyAndGetSize(Function<String, List<String>> fun);", "}") .addSourceLines( "ApplyImpl.java", "import com.google.common.collect.ImmutableList;", "import java.util.function.Function;", "import java.util.List;", "public class ApplyImpl implements ApplyInterface {", " public int applyAndGetSize(Function<String, List<String>> fun) {", " List<String> result = fun.apply(\"foo,bar\");", " return result.size();", " }", "}") .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.function.Function;", "import java.util.List;", "class Test {", " private static final ApplyInterface APPLY = new ApplyImpl();", " private int doApply() {", " int result = APPLY.applyAndGetSize(str -> {", " ImmutableList<String> res = ImmutableList.of(str, str);", " return res;", " });", " return result;", " }", "}") .doTest(); } @Test public void overridingMethod_specialNotice() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.inject.Provider;", "import java.util.List;", "class Test {", " private static final int getFooLength() {", " final Provider<List<String>> fooProvider = ", " new Provider<List<String>>() {", " @Override", " // BUG: Diagnostic contains: even when overriding a method", " public List<String> get() {", " return ImmutableList.of(\"foo\", \"bar\");", " }", " };", " List<String> foo = fooProvider.get();", " return foo.size();", " }", "}") .doTest(); } @Test public void iterable_givenMoreTypeInformationAvailable_refactored() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " final ImmutableList<String> foo() {", " return ImmutableList.of();", " }", "}") .doTest(); } @Test public void immutableMap_notReplacedWithBiMap() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableBiMap;", "import com.google.common.collect.ImmutableMap;", "class Test {", " final ImmutableMap<String, String> foo() {", " return ImmutableBiMap.of();", " }", "}") .doTest(); } @Test public void diagnosticMessage_whenReplacingWithNonImmutableType() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ArrayListMultimap;", "import com.google.common.collect.HashMultimap;", "import com.google.common.collect.Multimap;", "import com.google.common.collect.ImmutableListMultimap;", "import com.google.common.collect.ImmutableMultimap;", "import com.google.common.collect.ImmutableSetMultimap;", "class Test {", " // BUG: Diagnostic contains: convey more information", " final Multimap<?, ?> foo() {", " return ArrayListMultimap.create();", " }", " // BUG: Diagnostic contains: convey more information", " final Multimap<?, ?> bar() {", " return HashMultimap.create();", " }", " // BUG: Diagnostic contains: convey more information", " final ImmutableMultimap<?, ?> baz() {", " return ImmutableListMultimap.of();", " }", " // BUG: Diagnostic contains: convey more information", " final ImmutableMultimap<?, ?> quux() {", " return ImmutableSetMultimap.of();", " }", "}") .doTest(); } @Test public void staticFinalIterableInitializedInDeclarationWithImmutableSetOf() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "class Test {", " // BUG: Diagnostic contains: static final ImmutableSet<String> FOO =", " static final Iterable<String> FOO = ImmutableSet.of();", "}") .doTest(); } @Test public void bind() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import com.google.inject.testing.fieldbinder.Bind;", "import java.util.List;", "class Test {", " @Bind ", " private static final List<String> LABELS = ImmutableList.of(\"MiniCluster\");", "}") .doTest(); } @Test public void staticFinalMapInitializedInDeclarationWithImmutableBiMapOf() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableBiMap;", "import java.util.Map;", "class Test {", " // BUG: Diagnostic contains: static final ImmutableMap<String, String> FOO =", " static final Map<String, String> FOO = ImmutableBiMap.of();", "}") .doTest(); } @Test public void staticFinalSetInitializedInDeclarationWithImmutableSetOf() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "import java.util.Set;", "class Test {", " // BUG: Diagnostic contains: static final ImmutableSet<String> FOO =", " static final Set<String> FOO = ImmutableSet.of();", "}") .doTest(); } @Test public void staticFinalRawSetInitializedInDeclarationWithImmutableSetOf() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "import java.util.Set;", "class Test {", " // BUG: Diagnostic contains: static final ImmutableSet FOO =", " static final Set FOO = ImmutableSet.of();", "}") .doTest(); } @Test public void staticFinalSetInitializedInDeclarationWithImmutableSetBuilder() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "import java.util.Set;", "class Test {", " // BUG: Diagnostic contains: static final ImmutableSet<String> FOO =", " static final Set<String> FOO = ImmutableSet.<String>builder().build();", "}") .doTest(); } @Test public void staticFinalListInitializedInDeclarationWithImmutableListOf() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "import java.util.List;", "class Test {", " // BUG: Diagnostic contains: static final ImmutableList<String> FOO =", " static final List<String> FOO = ImmutableList.of();", "}") .doTest(); } @Test public void staticFinalMapInitializedInDeclarationWithImmutableMapOf() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableMap;", "import java.util.Map;", "class Test {", " // BUG: Diagnostic contains: static final ImmutableMap<Integer, String> FOO =", " static final Map<Integer, String> FOO = ImmutableMap.of();", "}") .doTest(); } @Test public void staticFinalImmutableSetInitializedInDeclarationWithImmutableSet_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "class Test {", " static final ImmutableSet<String> FOO = ImmutableSet.of();", "}") .doTest(); } @Test public void staticFinalSetInitializedInStaticBlock() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "class Test {", " private static final ImmutableSet<String> FOO;", " static {", " FOO = ImmutableSet.of();", " }", "}") .doTest(); } @Test public void nonStatic() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "class Test {", " final ImmutableSet<String> NON_STATIC = ImmutableSet.of();", "}") .doTest(); } @Test public void nonFinal() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "import java.util.Set;", "class Test {", " static Set<String> NON_FINAL = ImmutableSet.of();", "}") .doTest(); } @Test public void nonCapitalCase_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableSet;", "import java.util.Set;", "class Test {", " static final ImmutableSet<String> nonCapitalCase = ImmutableSet.of();", "}") .doTest(); } @Test public void mutable_doesNotSuggestFix() { testHelper .addSourceLines( "Test.java", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " static Iterable<String> mutable = new ArrayList<>();", "}") .doTest(); } @Test public void replacementNotSubtypeOfDeclaredType_noFinding() { testHelper .addSourceLines( "Test.java", "import java.util.Deque;", "import java.util.LinkedList;", "class Test {", " private final Deque<String> foos = new LinkedList<>();", "}") .doTest(); } @Test public void charSequences() { testHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: String", " private final CharSequence a = \"foo\";", "}") .doTest(); } @Test public void obeysKeep() { refactoringHelper .addInputLines( "Test.java", "import com.google.errorprone.annotations.Keep;", "import java.util.ArrayList;", "class Test {", " @Keep private static final Iterable<Integer> FOO = new ArrayList<>();", "}") .expectUnchanged() .doTest(); } }
28,680
30.345355
102
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RethrowReflectiveOperationExceptionAsLinkageErrorTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link RethrowReflectiveOperationExceptionAsLinkageError}Test */ @RunWith(JUnit4.class) public class RethrowReflectiveOperationExceptionAsLinkageErrorTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance( RethrowReflectiveOperationExceptionAsLinkageError.class, getClass()); @Test public void positive() { testHelper .addSourceFile("RethrowReflectiveOperationExceptionAsLinkageErrorPositiveCases.java") .doTest(); } @Test public void negative() { testHelper .addSourceFile("RethrowReflectiveOperationExceptionAsLinkageErrorNegativeCases.java") .doTest(); } }
1,466
31.6
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SelfAssignmentTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class SelfAssignmentTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(SelfAssignment.class, getClass()); @Test public void positiveCases1() { compilationHelper.addSourceFile("SelfAssignmentPositiveCases1.java").doTest(); } @Test public void positiveCases2() { compilationHelper.addSourceFile("SelfAssignmentPositiveCases2.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("SelfAssignmentNegativeCases.java").doTest(); } }
1,429
28.791667
82
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NullableVoidTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link NullableVoid}Test */ @RunWith(JUnit4.class) public class NullableVoidTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(NullableVoid.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "class Test {", " // BUG: Diagnostic contains:", " // void-returning methods should not be annotated with @Nullable", " @Nullable void f() {}", "}") .doTest(); } @Test public void negativeNotAnnotated() { compilationHelper .addSourceLines("Test.java", "class Test {", " public void f() {}", "}") .doTest(); } @Test public void negativeBoxedVoid() { compilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "class Test {", " @Nullable Void f() { return null; }", "}") .doTest(); } // regression test for #418 @Test public void typeParameter() { compilationHelper .addSourceLines( "Nullable.java", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Retention;", "import java.lang.annotation.RetentionPolicy;", "import java.lang.annotation.Target;", "@Retention(RetentionPolicy.RUNTIME)", "@Target(ElementType.TYPE_USE)", "public @interface Nullable {}") .addSourceLines( "Test.java", // "class Test {", " <@Nullable T> void f(T t) {}", "}") .doTest(); } }
2,546
28.964706
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ProtoStringFieldReferenceEqualityTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ProtoStringFieldReferenceEquality}Test */ @RunWith(JUnit4.class) public class ProtoStringFieldReferenceEqualityTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ProtoStringFieldReferenceEquality.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "com/google/protobuf/GeneratedMessage.java", "package com.google.protobuf;", "public class GeneratedMessage {}") .addSourceLines( "Proto.java", "public abstract class Proto extends com.google.protobuf.GeneratedMessage {", " public abstract String getMessage();", "}") .addSourceLines( "Test.java", "class Test {", " boolean g(Proto proto) {", " boolean r = false;", " // BUG: Diagnostic contains: proto.getMessage().equals(\"\")", " r |= proto.getMessage() == \"\";", " // BUG: Diagnostic contains: \"\".equals(proto.getMessage())", " r |= \"\" == proto.getMessage();", " // BUG: Diagnostic contains: !proto.getMessage().equals(\"\")", " r |= proto.getMessage() != \"\";", " return r;", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "com/google/protobuf/GeneratedMessage.java", "package com.google.protobuf;", "public class GeneratedMessage {}") .addSourceLines( "Proto.java", "public abstract class Proto extends com.google.protobuf.GeneratedMessage {", " public abstract int getId();", " public abstract String getMessage();", "}") .addSourceLines( "Test.java", "class Test {", " boolean g(Proto proto) {", " boolean r = false;", " r |= proto.getId() == 0;", " r |= proto.getMessage() == null;", " return r;", " }", "}") .doTest(); } }
2,998
33.872093
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DeduplicateConstantsTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link DeduplicateConstants}Test */ @RunWith(JUnit4.class) public class DeduplicateConstantsTest { @Test public void positive() { BugCheckerRefactoringTestHelper.newInstance(DeduplicateConstants.class, getClass()) .addInputLines( "Test.java", "class Test {", " static final String C = \"hello world\";", " void f() {", " System.err.println(\"hello world\");", " System.err.println(\"hello world\");", " }", "}") .addOutputLines( "Test.java", "class Test {", " static final String C = \"hello world\";", " void f() {", " System.err.println(C);", " System.err.println(C);", " }", "}") .doTest(); } @Test public void effectivelyFinal() { BugCheckerRefactoringTestHelper.newInstance(DeduplicateConstants.class, getClass()) .addInputLines( "Test.java", "class Test {", " void f() {", " String C = \"hello world\";", " System.err.println(\"hello world\");", " System.err.println(\"hello world\");", " }", "}") .addOutputLines( "Test.java", "class Test {", " void f() {", " String C = \"hello world\";", " System.err.println(C);", " System.err.println(C);", " }", "}") .doTest(); } @Test public void negativeRecursiveInitializers() { BugCheckerRefactoringTestHelper.newInstance(DeduplicateConstants.class, getClass()) .addInputLines( "Test.java", "class Test {", " static final String C = \"hello\";", " class One {", " static final String C = \"hello\";", " }", " class Two {", " static final String C = \"hello\";", " }", "}") .expectUnchanged() .doTest(); } @Test public void negativeOnlyOneUse() { BugCheckerRefactoringTestHelper.newInstance(DeduplicateConstants.class, getClass()) .addInputLines( "Test.java", "class Test {", " static final String C = \"hello world\";", " void f() {", " System.err.println(\"hello world\");", " }", "}") .expectUnchanged() .doTest(); } @Test public void negativeTooShort() { BugCheckerRefactoringTestHelper.newInstance(DeduplicateConstants.class, getClass()) .addInputLines( "Test.java", "class Test {", " static final String C = \".\";", " void f() {", " System.err.println(\".\");", " System.err.println(\".\");", " System.err.println(\".\");", " }", "}") .expectUnchanged() .doTest(); } }
3,873
29.746032
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InlineTrivialConstantTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class InlineTrivialConstantTest { @Test public void positive() { BugCheckerRefactoringTestHelper.newInstance(InlineTrivialConstant.class, getClass()) .addInputLines( "Test.java", "class Test {", " private static final String EMPTY_STRING = \"\";", " void f() {", " System.err.println(EMPTY_STRING);", " }", "}") .addOutputLines( "Test.java", "class Test {", " void f() {", " System.err.println(\"\");", " }", "}") .doTest(); } @Test public void negative() { CompilationTestHelper.newInstance(InlineTrivialConstant.class, getClass()) .addSourceLines( "Test.java", "class Test {", " static class NonPrivate {", " static final String EMPTY_STRING = \"\";", " }", " static class NonStatic {", " private final String EMPTY_STRING = \"\";", " }", " static class NonFinal {", " private static String EMPTY_STRING = \"\";", " }", " static class NonString {", " private static final Object EMPTY_STRING = \"\";", " }", " static class WrongName {", " private static final String LAUNCH_CODES = \"\";", " }", " static class WrongValue {", " private static final String EMPTY_STRING = \"hello\";", " }", "}") .doTest(); } }
2,509
32.026316
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TestsNotRunWithinEnclosedTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link JUnit4TestsNotRunWithinEnclosed}. */ @RunWith(JUnit4.class) public final class JUnit4TestsNotRunWithinEnclosedTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(JUnit4TestsNotRunWithinEnclosed.class, getClass()); private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance( JUnit4TestsNotRunWithinEnclosed.class, getClass()); @Test public void nonEnclosedRunner_testPresumedToRun() { helper .addSourceLines( "FooTest.java", "import org.junit.Test;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public final class FooTest {", " @Test public void test() {}", "}") .doTest(); } @Test public void enclosingRunner_doesNotRunEnclosedTests() { helper .addSourceLines( "FooTest.java", "import org.junit.Test;", "import org.junit.experimental.runners.Enclosed;", "import org.junit.runner.RunWith;", "@RunWith(Enclosed.class)", "public final class FooTest {", " // BUG: Diagnostic contains:", " @Test public void test() {}", "}") .doTest(); } @Test public void refactoring_changesToUseJunitRunner() { refactoring .addInputLines( "FooTest.java", "import org.junit.Test;", "import org.junit.experimental.runners.Enclosed;", "import org.junit.runner.RunWith;", "@RunWith(Enclosed.class)", "public final class FooTest {", " @Test public void test() {}", "}") .addOutputLines( "FooTest.java", "import org.junit.Test;", "import org.junit.experimental.runners.Enclosed;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public final class FooTest {", " @Test public void test() {}", "}") .doTest(); } @Test public void enclosingRunner_butWithClassExtended_doesRunTests() { helper .addSourceLines( "FooTest.java", "import org.junit.experimental.runners.Enclosed;", "import org.junit.Test;", "import org.junit.runner.RunWith;", "@RunWith(Enclosed.class)", "public class FooTest {", " @Test public void test() {}", " public class FooInnerTest extends FooTest {}", "}") .doTest(); } @Test public void enclosingRunner_withInnerClasses_runsTests() { helper .addSourceLines( "FooTest.java", "import org.junit.experimental.runners.Enclosed;", "import org.junit.Test;", "import org.junit.runner.RunWith;", "@RunWith(Enclosed.class)", "public class FooTest {", " public static class BarTest {", " @Test public void test() {}", " }", "}") .doTest(); } }
4,112
32.169355
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ModifyingCollectionWithItselfTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author scottjohnson@google.com (Scott Johnson) */ @RunWith(JUnit4.class) public class ModifyingCollectionWithItselfTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ModifyingCollectionWithItself.class, getClass()); @Test public void positiveCases1() { compilationHelper.addSourceFile("ModifyingCollectionWithItselfPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("ModifyingCollectionWithItselfNegativeCases.java").doTest(); } }
1,361
30.674419
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnusedNestedClassTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static java.util.Arrays.asList; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link UnusedNestedClass} bug pattern. */ @RunWith(JUnit4.class) public class UnusedNestedClassTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnusedNestedClass.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", // "class A {", " // BUG: Diagnostic contains:", " private class B {}", "}") .doTest(); } @Test public void exemptedByUnusedPrefix() { compilationHelper .addSourceLines( "Test.java", // "class A {", " private class UnusedClass {}", "}") .doTest(); } @Test public void nonPrivateNestedClass_noWarning() { compilationHelper .addSourceLines( "Test.java", // "class A {", " class B {}", "}") .doTest(); } @Test public void anonymousClass_noFinding() { compilationHelper .addSourceLines( "Test.java", // "import java.util.function.Function;", "import java.util.stream.Stream;", "class A {", " private Stream<String> map(Stream<Object> xs) {", " return xs.map(new Function<Object, String>() {", " @Override", " public String apply(Object o) {", " return o.toString();", " }", " });", " }", "}") .doTest(); } @Test public void anonymousClass_asAStatement_unused() { compilationHelper .addSourceLines( "Test.java", // "import java.util.function.Function;", "import java.util.stream.Stream;", "class A {", " void test() {", // TODO(ghm): This should probably report an error, but maybe it's not within scope // of this check? " new Function<Object, String>() {", " @Override", " public String apply(Object o) {", " return o.toString();", " }", " };", " }", "}") .doTest(); } @Test public void localClass_used_noFinding() { compilationHelper .addSourceLines( "Test.java", // "import java.util.function.Function;", "import java.util.stream.Stream;", "class A {", " private Stream<String> map(Stream<Object> xs) {", " class Mapper implements Function<Object, String> {", " @Override", " public String apply(Object o) {", " return o.toString();", " }", " }", " return xs.map(new Mapper());", " }", "}") .doTest(); } @Test public void localClass_unused_finding() { compilationHelper .addSourceLines( "Test.java", // "import java.util.function.Function;", "import java.util.stream.Stream;", "class A {", " void test() {", " // BUG: Diagnostic contains:", " class Mapper implements Function<Object, String> {", " @Override", " public String apply(Object o) {", " return o.toString();", " }", " }", " }", "}") .doTest(); } @Test public void usedWithinSelf_warning() { compilationHelper .addSourceLines( "Test.java", "class A {", " // BUG: Diagnostic contains:", " private static class B {", " private static final B b = new B();", " }", "}") .doTest(); } @Test public void usedOutsideSelf_noWarning() { compilationHelper .addSourceLines( "Test.java", "class A {", " private static final B b = new B();", " private static class B {}", "}") .doTest(); } @Test public void usedOutsideSelf_oddQualification_noWarning() { compilationHelper .addSourceLines( "Test.java", "class A {", " public static final Object b = new A.B();", " private static class B {}", "}") .doTest(); } @Test public void suppression() { compilationHelper .addSourceLines( "Test.java", "class A {", " @SuppressWarnings(\"unused\")", " private class B {}", "}") .doTest(); } @Test public void usedReflectively_suppressed() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Keep;", "class A {", " @Keep", " private class B {}", "}") .doTest(); } @Test public void refactoring() { BugCheckerRefactoringTestHelper.newInstance(UnusedNestedClass.class, getClass()) .addInputLines( "Test.java", // "class A {", " /** Foo. */", " private class B {}", "}") .addOutputLines( "Test.java", // "class A {", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void moduleInfo() { compilationHelper .setArgs(asList("-source", "9", "-target", "9")) .addSourceLines( "module-info.java", // "module foo {", " requires java.base;", "}") .doTest(); } }
6,777
26.893004
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryTypeArgumentTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link UnnecessaryTypeArgument}Test */ @RunWith(JUnit4.class) public class UnnecessaryTypeArgumentTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnnecessaryTypeArgument.class, getClass()); @Test public void positiveCall() { compilationHelper .addSourceLines( "Test.java", "package foo.bar;", "class Test {", " void f() {}", " void m() {", " // BUG: Diagnostic contains: this.f()", " this.<String>f();", " }", "}") .doTest(); } @Test public void positiveThis() { compilationHelper .addSourceLines( "Test.java", "package foo.bar;", "class Test {", " static class C {", " public <T> C() {", " // BUG: Diagnostic contains: /*START*/this(42)", " /*START*/<String>this(42);", " }", " public C(int i) {", " }", " }", "}") .doTest(); } @Test public void positiveSuper() { compilationHelper .addSourceLines( "Test.java", "package foo.bar;", "class Test {", " static class B {", " public B() {", " }", " }", " static class C extends B {", " public <T> C() {", " // BUG: Diagnostic contains: /*START*/super()", " /*START*/<String>super();", " }", " }", "}") .doTest(); } @Test public void positiveInstantiation() { compilationHelper .addSourceLines( "Test.java", "package foo.bar;", "class Test {", " static class C {", " public C() {}", " }", " void m() {", " // BUG: Diagnostic contains: new C()", " new <String, Integer>C();", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "package foo.bar;", "class Test {", " <T> void f() {}", " void m() {", " this.<String>f();", " }", "}") .doTest(); } @Test public void negativeGenericSuper() { compilationHelper .addSourceLines( "Super.java", "public class Super {", " public <T> T f(T x) { return x; }", "}") .addSourceLines( "Sub.java", "@SuppressWarnings(\"unchecked\")", "public class Sub extends Super {", " public Object f(Object x) { return x; }", "}") .addSourceLines( "Test.java", "public class Test {", " void m(Sub s) {", " s.<String>f(null);", " }", "}") .doTest(); } @Test public void whitespaceFix() { compilationHelper .addSourceLines( "Test.java", "package foo.bar;", "class Test {", " void f() {}", " void m() {", " // BUG: Diagnostic contains: this.f()", " this.< /* */ String /* */ >f();", " }", "}") .doTest(); } }
4,284
26.292994
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/URLEqualsHashCodeTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link URLEqualsHashCode} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class URLEqualsHashCodeTest { CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(URLEqualsHashCode.class, getClass()); } @Test public void positiveCase() { compilationHelper.addSourceFile("URLEqualsHashCodePositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("URLEqualsHashCodeNegativeCases.java").doTest(); } }
1,434
28.285714
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnsafeFinalizationTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link UnsafeFinalization}Test */ @RunWith(JUnit4.class) public class UnsafeFinalizationTest { private final CompilationTestHelper compilationTestHelper = CompilationTestHelper.newInstance(UnsafeFinalization.class, getClass()); @Test public void positive() { compilationTestHelper .addSourceLines( "MyAwesomeGame.java", "class MyAwesomeGame {", " private long nativeResourcePtr;", " private static native long doNativeInit();", " private static native void cleanUpNativeResources(long nativeResourcePtr);", " private static native void playAwesomeGame(long nativeResourcePtr);", " public MyAwesomeGame() {", " nativeResourcePtr = doNativeInit();", " }", " @SuppressWarnings(\"removal\")", " @Override", " protected void finalize() throws Throwable {", " cleanUpNativeResources(nativeResourcePtr);", " nativeResourcePtr = 0;", " super.finalize();", " }", " public void run() {", " // BUG: Diagnostic contains:", " playAwesomeGame(nativeResourcePtr);", " }", "}") .doTest(); } @Test public void negative_instance() { compilationTestHelper .addSourceLines( "MyAwesomeGame.java", "class MyAwesomeGame {", " private static long nativeResourcePtr;", " private native void playAwesomeGame(long nativeResourcePtr);", " @SuppressWarnings(\"removal\")", " @Override protected void finalize() {}", " public void run() {", " playAwesomeGame(nativeResourcePtr);", " }", "}") .doTest(); } @Test public void negative_this() { compilationTestHelper .addSourceLines( "NativeStuff.java", "class NativeStuff {", " static native void doNative(long ctx, NativeResource instance);", "}") .addSourceLines( "NativeResource.java", "class NativeResource {", " private static long ctx;", " @SuppressWarnings(\"removal\")", " @Override protected void finalize() {}", " public void run() {", " NativeStuff.doNative(ctx, this);", " }", "}") .doTest(); } @Test public void negative_nonIntOrLong() { compilationTestHelper .addSourceLines( "MyAwesomeGame.java", "class MyAwesomeGame {", " private static String nativeResourcePtr;", " private static native void playAwesomeGame(String nativeResourcePtr);", " @SuppressWarnings(\"removal\")", " @Override protected void finalize() {}", " public static void run() {", " playAwesomeGame(nativeResourcePtr);", " }", "}") .doTest(); } @Test public void negative_nonNative() { compilationTestHelper .addSourceLines( "MyAwesomeGame.java", "class MyAwesomeGame {", " private static long nativeResourcePtr;", " private static void playAwesomeGame(long nativeResourcePtr) {}", " @SuppressWarnings(\"removal\")", " @Override protected void finalize() {}", " public static void run() {", " playAwesomeGame(nativeResourcePtr);", " }", "}") .doTest(); } @Test public void negative_noInstanceState() { compilationTestHelper .addSourceLines( "MyAwesomeGame.java", "class MyAwesomeGame {", " private long nativeResourcePtr;", " private static native long doNativeInit();", " private static native void cleanUpNativeResources(long nativeResourcePtr);", " private static native void playAwesomeGame();", " public MyAwesomeGame() {", " nativeResourcePtr = doNativeInit();", " }", " @SuppressWarnings(\"removal\")", " @Override", " protected void finalize() throws Throwable {", " cleanUpNativeResources(nativeResourcePtr);", " nativeResourcePtr = 0;", " super.finalize();", " }", " public void run() {", " playAwesomeGame();", " }", "}") .doTest(); } @Test public void negativeFence() { compilationTestHelper .addSourceLines( "MyAwesomeGame.java", "import java.lang.ref.Reference;", "class MyAwesomeGame {", " private long nativeResourcePtr;", " private static native long doNativeInit();", " private static native void cleanUpNativeResources(long nativeResourcePtr);", " private static native void playAwesomeGame(long nativeResourcePtr);", " public MyAwesomeGame() {", " nativeResourcePtr = doNativeInit();", " }", " @SuppressWarnings(\"removal\")", " @Override", " protected void finalize() throws Throwable {", " cleanUpNativeResources(nativeResourcePtr);", " nativeResourcePtr = 0;", " super.finalize();", " }", " public void run() {", " try {", " playAwesomeGame(nativeResourcePtr);", " } finally {", " Reference.reachabilityFence(this);", " }", " }", "}") .doTest(); } @Test public void negativeInterface() { compilationTestHelper .addSourceLines( "I.java", "interface I {", " int duration = 1;", " default void f() throws Exception {", " // a native static method", " Thread.sleep(duration);", " }", "}") .doTest(); } }
7,005
33.17561
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LabelledBreakTargetTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link LabelledBreakTarget}Test */ @RunWith(JUnit4.class) public class LabelledBreakTargetTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(LabelledBreakTarget.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f() {", " // BUG: Diagnostic contains:", " FOO:", " if (true) {", " break FOO;", " }", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f(Iterable<?> xs) {", " ONE:", " while (true) {", " break ONE;", " }", " TWO:", " do {", " break TWO;", " } while (true);", " THREE:", " for (var x : xs) {", " break THREE;", " }", " FOUR:", " for (int i = 0; i < 10; i++) {", " break FOUR;", " }", " }", "}") .doTest(); } }
2,126
27.36
79
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SelfEqualsTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link SelfEquals} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class SelfEqualsTest { CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(SelfEquals.class, getClass()); } @Test public void positiveCase() { compilationHelper.addSourceFile("SelfEqualsPositiveCase.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("SelfEqualsNegativeCases.java").doTest(); } @Test public void positiveFix() { compilationHelper .addSourceLines( "Test.java", "class Test {", " <T> boolean f() {", " T t = null;", " int y = 0;", " // BUG: Diagnostic contains:", " return t.equals(t);", " }", "}") .doTest(); } @Test public void positiveCase_guava() { compilationHelper.addSourceFile("SelfEqualsGuavaPositiveCase.java").doTest(); } @Test public void negativeCase_guava() { compilationHelper.addSourceFile("SelfEqualsGuavaNegativeCases.java").doTest(); } @Test public void enclosingStatement() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.base.Objects;", "class Test {", " Object a = new Object();", " // BUG: Diagnostic contains:", " boolean b = Objects.equal(a, a);", "}") .doTest(); } }
2,422
26.224719
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/CannotMockFinalClassTest.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@code CannotMockFinalClass}. * * @author Louis Wasserman */ @RunWith(JUnit4.class) public class CannotMockFinalClassTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(CannotMockFinalClass.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("CannotMockFinalClassPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("CannotMockFinalClassNegativeCases.java").doTest(); } @Test public void negativeCase2() { compilationHelper.addSourceFile("CannotMockFinalClassNegativeCases2.java").doTest(); } }
1,478
29.183673
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AlreadyCheckedTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link AlreadyChecked}. */ @RunWith(JUnit4.class) public final class AlreadyCheckedTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(AlreadyChecked.class, getClass()); @Test public void elseChecksSameVariable() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: false", " } else if (a) {}", " }", "}") .doTest(); } @Test public void thisAndThat() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b) {", " if (a && b) {", " } else if (a) {", " } else if (b) {}", " }", "}") .doTest(); } @Test public void guardBlock() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " return;", " }", " // BUG: Diagnostic contains: false", " if (a) {}", " }", "}") .doTest(); } @Test public void guardBlock_returnFromElse() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (!a) {", " } else {", " return;", " }", " // BUG: Diagnostic contains: false", " if (a) {}", " }", "}") .doTest(); } @Test public void withinLambda() { helper .addSourceLines( "Test.java", "import java.util.stream.Stream;", "class Test {", " public Stream<String> test(Stream<String> xs, String x) {", " if (x.isEmpty()) {", " return Stream.empty();", " }", " return xs.filter(", " // BUG: Diagnostic contains: x.isEmpty()", " y -> x.isEmpty() || y.equals(x));", " }", "}") .doTest(); } @Test public void checkedInDifferentMethods() { helper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " private final ImmutableList<Integer> foos = null;", " public boolean a() {", " if (foos.isEmpty()) {", " return true;", " }", " return false;", " }", " public boolean b() {", " return foos.isEmpty();", " }", "}") .doTest(); } @Test public void checkedInLambdaAndAfter() { helper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " private final ImmutableList<Integer> foos = null;", " public boolean a() {", " ImmutableList.of().stream().anyMatch(x -> true);", " if (foos.isEmpty()) {", " return true;", " }", " // BUG: Diagnostic contains:", " return foos.isEmpty();", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " if (a) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedThrice() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " if (a) {}", " // BUG: Diagnostic contains: true", " if (a) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_negated() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " if (!a) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_atTopLevel() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {}", " if (a) {}", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_asPartOfAnd() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b, boolean c) {", " if (a && b) {", " // BUG: Diagnostic contains: true", " if (a && c) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_butOuterIfNotSimple() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b, boolean c) {", " if ((a && b) || b) {", " if (a && c) {}", " }", " }", "}") .doTest(); } @Test public void complexExpression() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b, boolean c) {", " if (!a || (b && c)) {", " } else if (b) {}", " }", "}") .doTest(); } @Test public void notFinal_noFinding() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " a = true;", " if (a) {", " } else if (a) {}", " }", "}") .doTest(); } @Test public void ternaryWithinIf() { helper .addSourceLines( "Test.java", "class Test {", " public int test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " return a ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void equalsCheckedTwice() { helper .addSourceLines( "Test.java", "class Test {", " public int test(String a) {", " if (a.equals(\"a\")) {", " // BUG: Diagnostic contains: true", " return a.equals(\"a\") ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void equalsCheckedTwice_comparedToDifferentConstant() { helper .addSourceLines( "Test.java", "class Test {", " public int test(String a) {", " if (a.equals(\"b\")) {", " return a.equals(\"a\") ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void comparedUsingBinaryEquals() { helper .addSourceLines( "Test.java", "class Test {", " public int test(int a, int b) {", " if (a == 1) {", " if (a == b) {", " return 3;", " }", " // BUG: Diagnostic contains:", " return a != 1 ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void checkedTwiceWithinTernary() { helper .addSourceLines( "Test.java", "class Test {", " public int test(int a) {", " // BUG: Diagnostic contains:", " return a == 1 ? (a == 1 ? 1 : 2) : 2;", " }", "}") .doTest(); } @Test public void durationsComparedUsingFactoryMethods() { helper .addSourceLines( "Test.java", "import java.time.Duration;", "class Test {", " public void test(Duration a, Duration b) {", " if (a.equals(Duration.ofSeconds(1))) {", " if (a.equals(Duration.ofSeconds(2))) {}", " // BUG: Diagnostic contains:", " if (a.equals(Duration.ofSeconds(1))) {}", " }", " }", "}") .doTest(); } @Test public void durationsComparedUsingFactoryMethods_withDifferentImport() { helper .addSourceLines( "Test.java", "import static java.time.Duration.ofSeconds;", "import java.time.Duration;", "class Test {", " public void test(Duration a, Duration b) {", " if (a.equals(Duration.ofSeconds(1))) {", " if (a.equals(Duration.ofSeconds(2))) {}", " // BUG: Diagnostic contains:", " if (a.equals(ofSeconds(1))) {}", " // BUG: Diagnostic contains:", " if (a.equals(java.time.Duration.ofSeconds(1))) {}", " }", " }", "}") .doTest(); } @Test public void autoValues() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " public void test(Foo a, Foo b) {", " if (a.bar().equals(\"foo\") && a.bar().equals(b.bar())) {", " // BUG: Diagnostic contains:", " if (a.bar().equals(\"foo\")) {}", " // BUG: Diagnostic contains:", " if (a.bar().equals(b.bar())) {}", " }", " }", " @AutoValue abstract static class Foo {", " abstract String bar();", " }", "}") .doTest(); } @Test public void autoValue_withEnum() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.Immutable;", "class Test {", " public void test(Foo a, Foo b) {", " if (a.bar().equals(E.A)) {", " // BUG: Diagnostic contains:", " if (a.bar().equals(E.A)) {}", " }", " }", " @AutoValue abstract static class Foo {", " abstract E bar();", " }", " @Immutable", " private enum E {", " A", " }", "}") .doTest(); } @Test public void fieldCheckedTwice() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " private final String a = \"foo\";", " public void test(String a) {", " if (this.a.equals(a)) {", " // BUG: Diagnostic contains:", " if (this.a.equals(a)) {}", " }", " }", "}") .doTest(); } @Test public void knownQuantityPassedToMethod() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " void test(boolean a) {", " if (a) {", " set(a);", " }", " }", " void set(boolean a) {}", "}") .doTest(); } @Test public void equalsCalledTwiceOnMutableType_noFinding() { helper .addSourceLines( "Test.java", "import java.util.List;", "class Test {", " private final List<String> xs = null;", " public boolean e(List<String> ys) {", " if (xs.equals(ys)) {", " return true;", " }", " return xs.equals(ys);", " }", "}") .doTest(); } @Test public void i3914() { helper .addSourceLines( "Test.java", "import java.util.List;", "class Test {", " void test(boolean a, boolean b) {", " if (a && b)", " return;", " if (a) {", " } else if (b) {", " }", " }", "}") .doTest(); } }
14,142
26.198077
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnit3FloatingPointComparisonWithoutDeltaTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link JUnit3FloatingPointComparisonWithoutDelta}. * * @author mwacker@google.com (Mike Wacker) */ @RunWith(JUnit4.class) public class JUnit3FloatingPointComparisonWithoutDeltaTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance( JUnit3FloatingPointComparisonWithoutDelta.class, getClass()); @Test public void match_twoPrimitiveDoubles() { checkAssertEquals("1.0, 1.0", true); } @Test public void match_primitiveAndReferenceDouble() { checkAssertEquals("1.0, (Double) 1.0", true); } @Test public void match_referenceAndPrimitiveDouble() { checkAssertEquals("(Double) 1.0, 1.0", true); } @Test public void noMatch_twoReferenceDoubles() { checkAssertEquals("(Double) 1.0, (Double) 1.0", false); } @Test public void match_twoPrimitiveDoublesWithMessage() { checkAssertEquals("\"message\", 1.0, 1.0", true); } @Test public void noMatch_deltaArgumentUsed() { checkAssertEquals("1.0, 1.0, 0.0", false); } @Test public void noMatch_twoPrimitiveInts() { checkAssertEquals("1, 1", false); } @Test public void noMatch_twoStrings() { checkAssertEquals("\"abc\", \"abc\"", false); } @Test public void noMatch_primitiveDoubleAndString() { checkAssertEquals("1.0, \"abc\"", false); } @Test public void match_twoPrimitiveFloats() { checkAssertEquals("1.0f, 1.0f", true); } @Test public void match_referenceAndPrimitiveFloat() { checkAssertEquals("(Float) 1.0f, 1.0f", true); } @Test public void noMatch_twoReferenceFloats() { checkAssertEquals("(Float) 1.0f, (Float) 1.0f", false); } @Test public void match_primitiveFloatAndPrimitiveDouble() { checkAssertEquals("1.0f, 1.0", true); } @Test public void match_primitiveFloatAndReferenceDouble() { checkAssertEquals("1.0f, (Double) 1.0", true); } @Test public void match_primitiveIntAndPrimitiveDouble() { checkAssertEquals("1, 1.0", true); } @Test public void match_primitiveDoubleAndReferenceInteger() { checkAssertEquals("1.0, (Integer) 1", true); } @Test public void match_primitiveCharAndPrimitiveDouble() { checkAssertEquals("'a', 1.0", true); } @Test public void noMatch_notAssertEquals() { checkTest(" assertSame(1.0, 1.0);", false); } @Test public void noMatch_notTestCase() { compilationHelper .addSourceLines( "SampleClass.java", "public class SampleClass {", " public void assertEquals(double d1, double d2) {}", " public void f() {", " assertEquals(1.0, 1.0);", " }", "}") .doTest(); } private void checkAssertEquals(String assertEqualsArgumentsText, boolean matchExpected) { String assertEqualsLine = String.format(" assertEquals(%s);", assertEqualsArgumentsText); checkTest(assertEqualsLine, matchExpected); } private void checkTest(String methodInvocationLine, boolean matchExpected) { String diagnosticLine = matchExpected ? " // BUG: Diagnostic contains:" : ""; compilationHelper .addSourceLines( "SampleTest.java", "import junit.framework.TestCase;", "public class SampleTest extends TestCase {", " public void testComparison() {", diagnosticLine, methodInvocationLine, " }", "}") .doTest(); } }
4,290
25.81875
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnit4ClassAnnotationNonStaticTest.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; /** Unit test of {@link JUnit4ClassAnnotationNonStatic} */ @RunWith(JUnit4.class) public class JUnit4ClassAnnotationNonStaticTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(JUnit4ClassAnnotationNonStatic.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.junit.BeforeClass;", "import org.junit.AfterClass;", "@RunWith(JUnit4.class)", "public class Test {", " @BeforeClass", " // BUG: Diagnostic contains: BeforeClass can only be applied to static methods.", " public void shouldDoSomething() {}", "", " @AfterClass", " // BUG: Diagnostic contains: AfterClass can only be applied to static methods.", " public void shouldDoSomethingElse() {}", "", " @AfterClass @BeforeClass", " // BUG: Diagnostic contains: AfterClass and BeforeClass can only be applied to", " public void shouldDoSomethingElseBlah() {}", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.junit.BeforeClass;", "import org.junit.AfterClass;", "@RunWith(JUnit4.class)", "public class Test {", " @BeforeClass", " public static void shouldDoSomething() {}", "", " @AfterClass", " public static void shouldDoSomethingElse() {}", "}") .doTest(); } }
2,680
33.818182
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IterableAndIteratorTest.java
/* Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author jsjeon@google.com (Jinseong Jeon) */ @RunWith(JUnit4.class) public class IterableAndIteratorTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(IterableAndIterator.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("IterableAndIteratorPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("IterableAndIteratorNegativeCases.java").doTest(); } }
1,309
30.95122
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ThrowsUncheckedExceptionTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author yulissa@google.com (Yulissa Arroyo-Paredes) */ @RunWith(JUnit4.class) public final class ThrowsUncheckedExceptionTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ThrowsUncheckedException.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("ThrowsUncheckedExceptionPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("ThrowsUncheckedExceptionNegativeCases.java").doTest(); } @Test public void deleteAll() { BugCheckerRefactoringTestHelper.newInstance(ThrowsUncheckedException.class, getClass()) .addInputLines( "in/Test.java", "import java.io.IOError;", "interface Test {", " void f() throws IOError, RuntimeException;", "}") .addOutputLines( "out/Test.java", // "import java.io.IOError;", "interface Test {", " void f();", "}") .doTest(TEXT_MATCH); } @Test public void deleteLeft() { BugCheckerRefactoringTestHelper.newInstance(ThrowsUncheckedException.class, getClass()) .addInputLines( "in/Test.java", "import java.io.IOError;", "import java.io.IOException;", "interface Test {", " void f() throws IOError, RuntimeException, IOException;", "}") .addOutputLines( "out/Test.java", "import java.io.IOError;", "import java.io.IOException;", "interface Test {", " void f() throws IOException;", "}") .doTest(); } @Test public void deleteRight() { BugCheckerRefactoringTestHelper.newInstance(ThrowsUncheckedException.class, getClass()) .addInputLines( "in/Test.java", "import java.io.IOError;", "import java.io.IOException;", "interface Test {", " void f() throws IOException, IOError, RuntimeException;", "}") .addOutputLines( "out/Test.java", "import java.io.IOError;", "import java.io.IOException;", "interface Test {", " void f() throws IOException;", "}") .doTest(); } @Test public void preserveOrder() { BugCheckerRefactoringTestHelper.newInstance(ThrowsUncheckedException.class, getClass()) .addInputLines( "in/Test.java", "import java.io.IOException;", "interface Test {", " void f() throws ReflectiveOperationException, IOException, RuntimeException;", "}") .addOutputLines( "out/Test.java", "import java.io.IOException;", "interface Test {", " void f() throws ReflectiveOperationException, IOException;", "}") .doTest(); } }
3,930
31.758333
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DeprecatedVariableTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link DeprecatedVariable}Test */ @RunWith(JUnit4.class) public class DeprecatedVariableTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(DeprecatedVariable.class, getClass()); @Test public void refactor() { testHelper .addInputLines( "Test.java", "class Test {", " @Deprecated int x;", " void f(@Deprecated int x) {", " @Deprecated int y;", " }", "}") .addOutputLines( "Test.java", "class Test {", // " @Deprecated int x;", " void f(int x) {", " int y;", " }", "}") .doTest(); } }
1,574
29.288462
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RedundantOverrideTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link RedundantOverride}. */ @RunWith(JUnit4.class) public final class RedundantOverrideTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(RedundantOverride.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "Test.java", "class Test extends foo.Bar {", " // BUG: Diagnostic contains:", " @Override public boolean frob(Object o) {", " return super.frob(o);", " }", "}") .addSourceLines( "foo/Bar.java", "package foo;", "public class Bar {", " public boolean frob(Object o) {", " return false;", " }", "}") .doTest(); } @Test public void addingJavadoc() { testHelper .addSourceLines( "Test.java", "class Test extends foo.Bar {", " /** Adding javadoc. */", " @Override public boolean frob(Object o) {", " return super.frob(o);", " }", "}") .addSourceLines( "foo/Bar.java", "package foo;", "public class Bar {", " public boolean frob(Object o) {", " return false;", " }", "}") .doTest(); } @Test public void addingComments() { testHelper .addSourceLines( "Test.java", "class Test extends foo.Bar {", " @Override public boolean frob(Object o) {", " // TODO..", " return super.frob(o);", " }", "}") .addSourceLines( "foo/Bar.java", "package foo;", "public class Bar {", " public boolean frob(Object o) {", " return false;", " }", "}") .doTest(); } @Test public void considersParameterOrder() { testHelper .addSourceLines( "A.java", // "class A {", " public void swap(int a, int b) {}", "}") .addSourceLines( "B.java", "class B extends A {", " @Override public void swap(int a, int b) {", " super.swap(b, a);", " }", "}") .doTest(); } @Test public void wideningVisibilityNoMatch() { testHelper .addSourceLines( "A.java", // "class A {", " void swap(int a, int b) {}", "}") .addSourceLines( "B.java", "class B extends A {", " @Override public void swap(int a, int b) {", " super.swap(a, b);", " }", "}") .doTest(); } @Test public void addingAnnotations() { testHelper .addSourceLines( "A.java", // "class A {", " Object swap(int a, int b) {", " return null;", " }", "}") .addSourceLines( "B.java", "import javax.annotation.Nullable;", "class B extends A {", " @Nullable", " @Override public Object swap(int a, int b) {", " return super.swap(a, b);", " }", "}") .doTest(); } @Test public void sameAnnotation() { testHelper .addSourceLines( "A.java", // "import javax.annotation.Nullable;", "class A {", " @Nullable Object swap(int a, int b) {", " return null;", " }", "}") .addSourceLines( "B.java", "import javax.annotation.Nullable;", "class B extends A {", " @Nullable", " // BUG: Diagnostic contains:", " @Override Object swap(int a, int b) {", " return super.swap(a, b);", " }", "}") .doTest(); } @Test public void removesAnnotation() { testHelper .addSourceLines( "A.java", // "import javax.annotation.Nullable;", "class A {", " @Nullable Object swap(int a, int b) {", " return null;", " }", "}") .addSourceLines( "B.java", "import javax.annotation.Nullable;", "class B extends A {", " @Override Object swap(int a, int b) {", " return super.swap(a, b);", " }", "}") .doTest(); } @Test public void addsAnnotation() { testHelper .addSourceLines( "A.java", // "class A {", " Object swap(int a, int b) {", " return null;", " }", "}") .addSourceLines( "B.java", "import javax.annotation.Nullable;", "class B extends A {", " @Nullable", " @Override Object swap(int a, int b) {", " return super.swap(a, b);", " }", "}") .doTest(); } @Test public void protectedOverrideInDifferentPackage() { testHelper .addSourceLines( "A.java", // "package foo;", "public class A {", " protected void swap() {}", "}") .addSourceLines( "B.java", "package bar;", "public class B extends foo.A {", " @Override protected void swap() {", " super.swap();", " }", "}") .doTest(); } @Test public void protectedOverrideInSamePackage() { testHelper .addSourceLines( "A.java", // "package foo;", "class A {", " protected void swap() {}", "}") .addSourceLines( "B.java", "package foo;", "class B extends A {", " // BUG: Diagnostic contains:", " @Override protected void swap() {", " super.swap();", " }", "}") .doTest(); } @Test public void paramAnnotationAddedInOverride() { testHelper .addSourceLines( "DemoAnnotation.java", // "package foo;", "@interface DemoAnnotation {}") .addSourceLines( "A.java", // "package foo;", "class A {", " protected void swap(int a) {}", "}") .addSourceLines( "B.java", "package foo;", "class B extends A {", " @Override", " protected void swap(@DemoAnnotation int a) {", " super.swap(a);", " }", "}") .doTest(); } @Test public void paramAnnotationOmittedInOverride() { testHelper .addSourceLines( "DemoAnnotation.java", // "package foo;", "@interface DemoAnnotation {}") .addSourceLines( "A.java", // "package foo;", "class A {", " protected void swap(@DemoAnnotation int a) {}", "}") .addSourceLines( "B.java", "package foo;", "class B extends A {", " @Override", " protected void swap(int a) {", " super.swap(a);", " }", "}") .doTest(); } }
8,442
25.974441
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TestNotRunTest.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class JUnit4TestNotRunTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(JUnit4TestNotRun.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(JUnit4TestNotRun.class, getClass()); @Test public void positiveCase1() { compilationHelper.addSourceFile("JUnit4TestNotRunPositiveCase1.java").doTest(); } @Test public void positiveCase2() { compilationHelper.addSourceFile("JUnit4TestNotRunPositiveCase2.java").doTest(); } @Test public void containsVerifyAsIdentifier_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import static org.mockito.Mockito.verify;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " verify(null);", " }", "}") .doTest(); } @Test public void containsQualifiedVerify_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.mockito.Mockito;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " Mockito.verify(null);", " }", "}") .doTest(); } @Test public void containsAssertAsIdentifier_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import static com.google.common.truth.Truth.assertThat;", "import java.util.Collections;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " assertThat(2).isEqualTo(2);", " }", " // BUG: Diagnostic contains: @Test", " public void shouldDoTwoThings() {", " Collections.sort(Collections.<Integer>emptyList());", " assertThat(3).isEqualTo(3);", " }", "}") .doTest(); } @Test public void containsQualifiedAssert_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import com.google.common.truth.Truth;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " Truth.assertThat(1).isEqualTo(1);", " }", "}") .doTest(); } @Test public void containsCheckAsIdentifier_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import static com.google.common.base.Preconditions.checkState;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " checkState(false);", " }", "}") .doTest(); } @Test public void containsQualifiedCheck_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.base.Preconditions;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " Preconditions.checkState(false);", " }", "}") .doTest(); } @Test public void containsFailAsIdentifier_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import static org.junit.Assert.fail;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " fail();", " }", "}") .doTest(); } @Test public void containsQualifiedFail_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import org.junit.Assert;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " Assert.fail();", " }", "}") .doTest(); } @Test public void containsExpectAsIdentifier_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import static org.junit.Assert.assertThrows;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " assertThrows(null, null);", " }", "}") .doTest(); } @Test public void containsQualifiedExpect_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import org.junit.Assert;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", " // BUG: Diagnostic contains: @Test", " public void shouldDoSomething() {", " Assert.assertThrows(null, null);", " }", "}") .doTest(); } @Test public void noTestKeyword_notATest() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import java.util.Collections;", "@RunWith(JUnit4.class)", "public class Test {", " public void shouldDoSomething() {", " Collections.sort(Collections.<Integer>emptyList());", " }", "}") .doTest(); } @Test public void staticMethodWithTestKeyword_notATest() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import java.util.Collections;", "@RunWith(JUnit4.class)", "public class Test {", " private static void assertDoesSomething() {}", " public static void shouldDoSomething() {", " assertDoesSomething();", " }", "}") .doTest(); } @Test public void hasOtherAnnotation_notATest() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", " @Deprecated", " public void shouldDoSomething() {", " verify();", " }", " private void verify() {}", "}") .doTest(); } @Test public void hasOtherAnnotationAndNamedTest_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import java.util.Collections;", "@RunWith(JUnit4.class)", "public class Test {", " @Deprecated", " // BUG: Diagnostic contains: @Test", " public void testShouldDoSomething() {", " Collections.sort(Collections.<Integer>emptyList());", " }", " private void verify() {}", "}") .doTest(); } @Test public void shouldNotDetectMethodsOnAbstractClass() { compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public abstract class Test {", " public void testDoSomething() {}", "}") .doTest(); } @Test public void fix() { refactoringHelper .addInputLines( "in/TestStuff.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestStuff {", " public void testDoSomething() {}", "}") .addOutputLines( "out/TestStuff.java", "import org.junit.Test;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestStuff {", " @Test", " public void testDoSomething() {}", "}") .setFixChooser(FixChoosers.FIRST) .doTest(); } @Test public void ignoreFix() { refactoringHelper .addInputLines( "in/TestStuff.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestStuff {", " public void testDoSomething() {}", "}") .addOutputLines( "out/TestStuff.java", "import org.junit.Ignore;", "import org.junit.Test;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestStuff {", " @Test @Ignore public void testDoSomething() {}", "}") .setFixChooser(FixChoosers.SECOND) .doTest(); } @Test public void makePrivateFix() { refactoringHelper .addInputLines( "in/TestStuff.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestStuff {", " public void testDoSomething() {}", "}") .addOutputLines( "out/TestStuff.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestStuff {", " private void testDoSomething() {}", "}") .setFixChooser(FixChoosers.THIRD) .doTest(); } @Test public void ignoreFixComesFirstWhenTestNamedDisabled() { refactoringHelper .addInputLines( "in/TestStuff.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestStuff {", " public void disabledTestDoSomething() {", " verify();", " }", " void verify() {}", "}") .addOutputLines( "out/TestStuff.java", "import org.junit.Ignore;", "import org.junit.Test;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestStuff {", " @Test @Ignore public void disabledTestDoSomething() {", " verify();", " }", " void verify() {}", "}") .setFixChooser(FixChoosers.FIRST) .doTest(); } @Test public void helperMethodCalledElsewhere() { compilationHelper .addSourceLines( "TestStuff.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.junit.Test;", "@RunWith(JUnit4.class)", "public class TestStuff {", " public void shouldDoSomething() {", " verify();", " }", " @Test", " public void testDoesSomething() {", " shouldDoSomething();", " }", " void verify() {}", "}") .doTest(); } @Test public void helperMethodCallFoundInNestedInvocation() { compilationHelper .addSourceLines( "TestStuff.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import org.junit.Test;", "import java.util.function.Consumer;", "@RunWith(JUnit4.class)", "public class TestStuff {", " public void shouldDoSomething() {", " verify();", " }", " @Test", " public void testDoesSomething() {", " doSomething(u -> shouldDoSomething());", " }", " void doSomething(Consumer f) {}", " void verify() {}", "}") .doTest(); } @Test public void runWithNotRequired() { compilationHelper .addSourceLines( "TestStuff.java", "import org.junit.Test;", "public class TestStuff {", " // BUG: Diagnostic contains: @Test", " public void testDoesSomething() {}", " @Test", " public void foo() {}", "}") .doTest(); } @Test public void suppression() { compilationHelper .addSourceLines( "TestStuff.java", "import org.junit.Test;", "public class TestStuff {", " @SuppressWarnings(\"JUnit4TestNotRun\")", " public void testDoesSomething() {}", " @Test", " public void foo() {}", "}") .doTest(); } @Test public void negativeCase1() { compilationHelper.addSourceFile("JUnit4TestNotRunNegativeCase1.java").doTest(); } @Test public void negativeCase2() { compilationHelper.addSourceFile("JUnit4TestNotRunNegativeCase2.java").doTest(); } @Test public void negativeCase3() { compilationHelper.addSourceFile("JUnit4TestNotRunNegativeCase3.java").doTest(); } @Test public void negativeCase4() { compilationHelper.addSourceFile("JUnit4TestNotRunNegativeCase4.java").doTest(); } @Test public void negativeCase5() { compilationHelper .addSourceFile("JUnit4TestNotRunBaseClass.java") .addSourceFile("JUnit4TestNotRunNegativeCase5.java") .doTest(); } @Test public void junit3TestWithIgnore() { compilationHelper .addSourceLines( "TestStuff.java", "import org.junit.Ignore;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestStuff {", " @Ignore", " public void testMethod() {}", "}") .doTest(); } @Test public void junit4Theory_isTestAnnotation() { compilationHelper .addSourceLines( "TestTheories.java", "import org.junit.runner.RunWith;", "import org.junit.experimental.theories.Theories;", "import org.junit.experimental.theories.Theory;", "@RunWith(Theories.class)", "public class TestTheories {", " @Theory public void testMyTheory() {}", "}") .doTest(); } @Test public void methodsWithParameters_areStillTests() { compilationHelper .addSourceLines( "TestTheories.java", "import static org.junit.Assert.fail;", "import org.junit.runner.RunWith;", "import org.junit.experimental.theories.Theories;", "import org.junit.experimental.theories.FromDataPoints;", "@RunWith(Theories.class)", "public class TestTheories {", " // BUG: Diagnostic contains:", " public void testMyTheory(@FromDataPoints(\"foo\") Object foo) {", " fail();", " }", "}") .doTest(); } @Test public void annotationOnSuperMethod() { compilationHelper .addSourceLines( "TestSuper.java", "import org.junit.Test;", "public class TestSuper {", " @Test public void testToOverride() {}", "}") .addSourceLines( "TestSub.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class TestSub extends TestSuper {", " @Override public void testToOverride() {}", "}") .doTest(); } }
18,740
30.287145
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TestParametersNotInitializedTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link TestParametersNotInitialized}. */ @RunWith(JUnit4.class) public final class TestParametersNotInitializedTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(TestParametersNotInitialized.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(TestParametersNotInitialized.class, getClass()); @Test public void positive() { refactoringHelper .addInputLines( "Test.java", "import com.google.testing.junit.testparameterinjector.TestParameter;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", " @TestParameter public boolean foo;", "}") .addOutputLines( "Test.java", "import com.google.testing.junit.testparameterinjector.TestParameter;", "import com.google.testing.junit.testparameterinjector.TestParameterInjector;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(TestParameterInjector.class)", "public class Test {", " @TestParameter public boolean foo;", "}") .doTest(); } @Test public void onlyFlagsJunit4Runner() { refactoringHelper .addInputLines( "MyRunner.java", "import org.junit.runners.BlockJUnit4ClassRunner;", "import org.junit.runners.model.InitializationError;", "public final class MyRunner extends BlockJUnit4ClassRunner {", " public MyRunner(Class<?> testClass) throws InitializationError {", " super(testClass);", " }", "}") .expectUnchanged() .addInputLines( "Test.java", "import com.google.testing.junit.testparameterinjector.TestParameter;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(MyRunner.class)", "public class Test {", " @TestParameter public boolean foo;", "}") .expectUnchanged() .doTest(); } @Test public void alreadyParameterized_noFinding() { helper .addSourceLines( "Test.java", "import com.google.testing.junit.testparameterinjector.TestParameter;", "import com.google.testing.junit.testparameterinjector.TestParameterInjector;", "import org.junit.runner.RunWith;", "@RunWith(TestParameterInjector.class)", "public class Test {", " @TestParameter public boolean foo;", "}") .doTest(); } @Test public void noParameters_noFinding() { helper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class Test {", "}") .doTest(); } }
4,004
34.758929
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TypeToStringTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link TypeToString}. */ @RunWith(JUnit4.class) public class TypeToStringTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(TypeToString.class, getClass()); @Test public void noMatch() { testHelper .addSourceLines( "ExampleChecker.java", "import com.google.errorprone.BugPattern;", "import com.google.errorprone.BugPattern.SeverityLevel;", "import com.google.errorprone.VisitorState;", "import com.google.errorprone.bugpatterns.BugChecker;", "import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;", "import com.google.errorprone.matchers.Description;", "import com.sun.source.tree.ClassTree;", "import com.sun.tools.javac.code.Types;", "@BugPattern(name = \"Example\", summary = \"\", severity = SeverityLevel.ERROR)", "public class ExampleChecker extends BugChecker implements ClassTreeMatcher {", " @Override public Description matchClass(ClassTree t, VisitorState s) {", " return Description.NO_MATCH;", " }", "}") .addModules("jdk.compiler/com.sun.tools.javac.code") .doTest(); } @Test public void matchInABugChecker() { testHelper .addSourceLines( "ExampleChecker.java", "import com.google.errorprone.BugPattern;", "import com.google.errorprone.BugPattern.SeverityLevel;", "import com.google.errorprone.VisitorState;", "import com.google.errorprone.bugpatterns.BugChecker;", "import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;", "import com.google.errorprone.fixes.SuggestedFix;", "import com.google.errorprone.matchers.Description;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.ClassTree;", "import com.sun.tools.javac.tree.TreeMaker;", "import com.sun.tools.javac.code.Type;", "import com.sun.tools.javac.code.Types;", "import com.sun.tools.javac.tree.JCTree;", "import com.sun.tools.javac.tree.JCTree.JCClassDecl;", "@BugPattern(name = \"Example\", summary = \"\", severity = SeverityLevel.ERROR)", "public class ExampleChecker extends BugChecker implements ClassTreeMatcher {", " @Override", " public Description matchClass(ClassTree tree, VisitorState state) {", " Type type = ((JCTree) tree).type;", " if (type.toString().contains(\"matcha\")) {", " return describeMatch(tree);", " }", " // BUG: Diagnostic contains: TypeToString", " if (type.toString().equals(\"match\")) {", " return describeMatch(tree);", " }", " if (new InnerClass().matchaMatcher(type)) {", " return describeMatch(tree);", " }", " return Description.NO_MATCH;", " }", "", " class InnerClass {", " boolean matchaMatcher(Type type) {", " // BUG: Diagnostic contains: TypeToString", " return type.toString().equals(\"match\");", " }", " }", "}") .addModules( "jdk.compiler/com.sun.tools.javac.code", "jdk.compiler/com.sun.tools.javac.tree", "jdk.compiler/com.sun.tools.javac.util") .doTest(); } }
4,441
41.711538
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LiteProtoToStringTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link LiteProtoToString} bugpattern. * * @author ghm@google.com (Graeme Morgan) */ @RunWith(JUnit4.class) public final class LiteProtoToStringTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(LiteProtoToString.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import com.google.protobuf.GeneratedMessageLite;", "class Test {", " private String test(GeneratedMessageLite message) {", " // BUG: Diagnostic contains:", " return message.toString();", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import com.google.protobuf.GeneratedMessageLite;", "class Test {", " private void test(GeneratedMessageLite message) {", " atVerbose(message.toString());", " }", " public void atVerbose(String s) {}", "}") .doTest(); } @Test public void unknownFieldSet_noMatch() { compilationHelper .addSourceLines( "Test.java", "import com.google.protobuf.UnknownFieldSet;", "class Test {", " private String test(UnknownFieldSet message) {", " return message.toString();", " }", "}") .doTest(); } @Test public void enums() { compilationHelper .addSourceLines( "Test.java", "import com.google.protobuf.Internal.EnumLite;", "import com.google.protobuf.ProtocolMessageEnum;", "class Test {", " private String test(EnumLite e) {", " // BUG: Diagnostic contains:", " return e.toString();", " }", " private String testImplicit(EnumLite e) {", " // BUG: Diagnostic contains:", " return \"\" + e;", " }", " private String test2(ProtocolMessageEnum e) {", " return e.toString();", " }", " private String test3(ProtocolMessageEnum e) {", " return e.getValueDescriptor().toString();", " }", "}") .doTest(); } @Test public void nestedLogStatement() { compilationHelper .addSourceLines( "Test.java", "import com.google.protobuf.GeneratedMessageLite;", "class Test {", " private void test(GeneratedMessageLite message) {", " atVerbose().log(message.toString());", " }", " public Test atVerbose() {", " return this;", " }", " public Test log(String s) {", " return this;", " }", "}") .doTest(); } @Test public void androidLogAtInfoOrFiner_noWarning() { compilationHelper .addSourceLines( "Test.java", "import com.google.protobuf.GeneratedMessageLite;", "class Test {", " static class Log {", " static void i(String s) {}", " static void d(String s) {}", " static void v(String s) {}", " }", " private void test(GeneratedMessageLite message) {", " Log.i(message.toString());", " Log.d(message.toString());", " Log.v(message.toString());", " }", "}") .doTest(); } @Test public void androidLogAtWarning_error() { compilationHelper .addSourceLines( "Test.java", "import com.google.protobuf.GeneratedMessageLite;", "class Test {", " static class Log {", " static void w(String s) {}", " }", " private void test(GeneratedMessageLite message) {", " // BUG: Diagnostic contains:", " Log.w(message.toString());", " }", "}") .doTest(); } @Test public void customFormatMethod() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.protobuf.GeneratedMessageLite;", "class Test {", " private void test(GeneratedMessageLite message) {", " // BUG: Diagnostic contains:", " format(null, \"%s\", message);", " format(message, \"%s\", 1);", " }", " @FormatMethod", " String format(Object tag, String format, Object... args) {", " return String.format(format, args);", " }", "}") .doTest(); } }
5,748
30.244565
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TruthGetOrDefaultTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link TruthGetOrDefault} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class TruthGetOrDefaultTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(TruthGetOrDefault.class, getClass()); private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(TruthGetOrDefault.class, getClass()); @Test public void positiveCases() { compilationHelper .addSourceLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import java.util.HashMap;", "import java.util.Map;", "class Test {", " void test() {", " Map<String, Integer> map = new HashMap<>();", " // BUG: Diagnostic contains: TruthGetOrDefault", " assertThat(map.getOrDefault(\"key\", 0)).isEqualTo(0);", " Integer expectedVal = 0;", " // BUG: Diagnostic contains: TruthGetOrDefault", " assertThat(map.getOrDefault(\"key\", expectedVal)).isEqualTo(expectedVal);", " Map<String, Long> longMap = new HashMap<>();", " // BUG: Diagnostic contains: TruthGetOrDefault", " assertThat(longMap.getOrDefault(\"key\", 0L)).isEqualTo(5L);", " }", "}") .doTest(); } @Test public void negativeCases() { compilationHelper .addSourceLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import java.util.HashMap;", "import java.util.Map;", "class Test {", " void test() {", " Map<String, Integer> map = new HashMap<>();", " Integer expectedVal = 10;", " assertThat(map.getOrDefault(\"key\", 0)).isEqualTo(expectedVal);", " assertThat(map.getOrDefault(\"key\", Integer.valueOf(0)))", " .isEqualTo(Integer.valueOf(1));", " }", "}") .doTest(); } @Test public void fixGeneration() { testHelper .addInputLines( "in/Test.java", "import static com.google.common.truth.Truth.assertThat;", "import java.util.HashMap;", "import java.util.Map;", "class Test {", " void test() {", " Map<String, Integer> map = new HashMap<>();", " assertThat(map.getOrDefault(\"key\", 0)).isEqualTo(1);", " Map<String, Long> longMap = new HashMap<>();", " assertThat(longMap.getOrDefault(\"key\", 0L)).isEqualTo(0L);", " assertThat(longMap.getOrDefault(\"key\", 0L)).isEqualTo(0);", " }", "}") .addOutputLines( "out/Test.java", "import static com.google.common.truth.Truth.assertThat;", "import java.util.HashMap;", "import java.util.Map;", "class Test {", " void test() {", " Map<String, Integer> map = new HashMap<>();", " assertThat(map).containsEntry(\"key\", 1);", " Map<String, Long> longMap = new HashMap<>();", " assertThat(longMap).doesNotContainKey(\"key\");", " assertThat(longMap.getOrDefault(\"key\", 0L)).isEqualTo(0);", " }", "}") .doTest(); } }
4,396
37.234783
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EqualsGetClassTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link EqualsGetClass} bugpattern. * * @author ghm@google.com (Graeme Morgan) */ @RunWith(JUnit4.class) public final class EqualsGetClassTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(EqualsGetClass.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(EqualsGetClass.class, getClass()); @Test public void fixes_inline() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " return o != null && o.getClass().equals(getClass()) && a == ((Test) o).a;", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " return o instanceof Test && a == ((Test) o).a;", " }", "}") .doTest(); } @Test public void fixes_extraParens() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " return (o != null) && (o.getClass() == getClass()) && a == ((Test) o).a;", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " return (o instanceof Test) && a == ((Test) o).a;", " }", "}") .doTest(); } @Test public void separateNullCheck() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (o == null) { return false; }", " if (o.getClass() != getClass()) { return false; }", " return ((Test) o).a == a;", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (!(o instanceof Test)) { return false; }", " return ((Test) o).a == a;", " }", "}") .doTest(); } @Test public void separateNullCheck_withElse() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (o == null) {", " return false;", " } else {", " if (o.getClass() != getClass()) { return false; }", " return ((Test) o).a == a;", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (!(o instanceof Test)) { return false; }", " return ((Test) o).a == a;", " }", "}") .doTest(); } @Test public void separateNullCheck_noParens() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (o == null)", " return false;", " else", " return o.getClass() == getClass() && ((Test) o).a == a;", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " return o instanceof Test && ((Test) o).a == a;", " }", "}") .doTest(); } @Test public void unnecessaryCast() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (o == null || !o.getClass().equals(((Object) this).getClass())) {", " return false;", " }", " return ((Test) o).a == a;", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (!(o instanceof Test)) { return false; }", " return ((Test) o).a == a;", " }", "}") .doTest(); } @Test public void positive_unfixable() { helper .addSourceLines( "Test.java", "import com.google.common.base.Objects;", "class Test {", " private int a;", " // BUG: Diagnostic matches: NO_FIX", " @Override public boolean equals(Object o) {", " if (o == null) { return false; }", " if (!Objects.equal(o.getClass(), getClass())) { return false; }", " return ((Test) o).a == a;", " }", "}") .expectErrorMessage("NO_FIX", fix -> !fix.contains("instanceof Test")) .doTest(); } @Test public void negative_final() { helper .addSourceLines( "Test.java", "final class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (o == null) { return false; }", " if (o.getClass() != getClass()) { return false; }", " return ((Test) o).a == a;", " }", "}") .doTest(); } @Test public void negative_anonymous() { helper .addSourceLines( "Test.java", "final class Test {", " Object foo = new Object() {", " @Override public boolean equals(Object o) {", " if (o == null) { return false; }", " return o.getClass() == getClass();", " }", " };", "}") .doTest(); } @Test public void negative_notOnParameter() { helper .addSourceLines( "Test.java", "class Test {", " private Object a;", " @Override public boolean equals(Object o) {", " if (o == null) { return false; }", " if (!(o instanceof Test)) { return false; }", " return ((Test) o).a.getClass() == a.getClass();", " }", "}") .doTest(); } }
7,824
29.928854
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ProtocolBufferOrdinalTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link ProtocolBufferOrdinal}. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class ProtocolBufferOrdinalTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ProtocolBufferOrdinal.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("ProtocolBufferOrdinalPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("ProtocolBufferOrdinalNegativeCases.java").doTest(); } }
1,371
29.488889
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TruthSelfEqualsTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link TruthSelfEquals} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class TruthSelfEqualsTest { CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(TruthSelfEquals.class, getClass()); } @Test public void positiveCase() { compilationHelper.addSourceFile("TruthSelfEqualsPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("TruthSelfEqualsNegativeCases.java").doTest(); } // regression test for b/32107126 @Test public void customReceiver() { compilationHelper .addSourceLines( "Test.java", "import static com.google.common.truth.Truth.assertThat;", "import com.google.common.truth.IntegerSubject;", "import java.util.Arrays;", "abstract class Test {", " abstract IntegerSubject f(int i);", " abstract IntegerSubject g();", " void test(int x) {", " f(x).isEqualTo(x);", " g().isEqualTo(x);", " }", "}") .doTest(); } }
2,051
28.73913
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AssertFalseTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author sebastian.h.monte@gmail.com (Sebastian Monte) */ @RunWith(JUnit4.class) public class AssertFalseTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(AssertFalse.class, getClass()); @Test public void negativeCase() { compilationHelper.addSourceFile("AssertFalseNegativeCases.java").doTest(); } @Test public void positiveCase() { compilationHelper.addSourceFile("AssertFalsePositiveCases.java").doTest(); } }
1,293
29.093023
78
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MissingBracesTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link MissingBraces}Test */ @RunWith(JUnit4.class) public class MissingBracesTest { @Test public void positive() { BugCheckerRefactoringTestHelper.newInstance(MissingBraces.class, getClass()) .addInputLines( "Test.java", "import java.util.List;", "class Test {", " void f(boolean x, List<Integer> is) {", " if (x) throw new AssertionError();", " else x = !x;", " while (x) g();", " do g(); while (x);", " for ( ; x; ) g();", " for (int i : is) g();", " }", " void g() {}", "}") .addOutputLines( "Test.java", "import java.util.List;", "class Test {", " void f(boolean x, List<Integer> is) {", " if (x) { throw new AssertionError(); }", " else { x = !x; }", " while (x) { g(); }", " do { g(); } while (x);", " for ( ; x; ) { g(); }", " for (int i : is) { g(); }", " }", " void g() {}", "}") .doTest(); } @Test public void negative() { CompilationTestHelper.newInstance(MissingBraces.class, getClass()) .addSourceLines( "Test.java", "class Test {", " void f(boolean x) {", " if (x) { g(); }", " else { g(); }", " while (x) { g(); }", " do { g(); } while (x);", " for (;;) { g(); }", " }", " void g() {}", "}") .doTest(); } }
2,549
30.875
80
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InvalidTimeZoneIDTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author awturner@google.com (Andy Turner) */ @RunWith(JUnit4.class) public class InvalidTimeZoneIDTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InvalidTimeZoneID.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceLines( "a/A.java", "package a;", "import java.util.TimeZone;", "class A {", " private static final String TIMEZONE_ID = \"unknown\";", " public static void test() {", " // BUG: Diagnostic contains:", " TimeZone.getTimeZone(\"\");", " // BUG: Diagnostic contains:", " TimeZone.getTimeZone(\"unknown\");", " // BUG: Diagnostic contains:", " TimeZone.getTimeZone(TIMEZONE_ID);", " // BUG: Diagnostic contains:", " TimeZone.getTimeZone(\"America/Los_Angele\");", " // BUG: Diagnostic contains:", " TimeZone.getTimeZone(\"KST\");", " }", " public static void invalidCustomIDs() {", " // BUG: Diagnostic contains:", " TimeZone.getTimeZone(\"UTC+0\");", " // BUG: Diagnostic contains:", " TimeZone.getTimeZone(\"GMT+24\");", " // BUG: Diagnostic contains:", " TimeZone.getTimeZone(\"GMT1\");", " // BUG: Diagnostic contains:", " TimeZone.getTimeZone(\"GMT/0\");", " }", " public static void underscoreSuggestion() {", " // BUG: Diagnostic contains: America/Los_Angeles", " TimeZone.getTimeZone(\"America/Los Angeles\");", " }", "}") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceLines( "a/A.java", "package a;", "import java.util.TimeZone;", "class A {", " private static final String TIMEZONE_ID = \"America/New_York\";", " public static void ianaIDs() {", " TimeZone.getTimeZone(\"America/Los_Angeles\");", " TimeZone.getTimeZone(TIMEZONE_ID);", " TimeZone.getTimeZone(\"Europe/London\");", " }", " public static void customIDs() {", " // Custom IDs", " TimeZone.getTimeZone(\"GMT+0\");", " TimeZone.getTimeZone(\"GMT+00\");", " TimeZone.getTimeZone(\"GMT+00:00\");", " }", " public static void threeLetterIDs() {", " TimeZone.getTimeZone(\"GMT\");", " TimeZone.getTimeZone(\"UTC\");", " // Some 3-letter IDs are deprecated, but are still recognized.", " TimeZone.getTimeZone(\"PST\");", " }", "}") .doTest(); } }
3,768
35.95098
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/VarCheckerTest.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 java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author cushon@google.com (Liam Miller-Cushon) */ @RunWith(JUnit4.class) public class VarCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(VarChecker.class, getClass()); // fields are ignored @Test public void nonFinalField() { compilationHelper .addSourceLines("Test.java", "class Test {", " public int x = 42;", "}") .doTest(); } @Test public void finalField() { compilationHelper .addSourceLines( "Test.java", // TODO(b/21633565): force line break "class Test {", " public final int x = 42;", "}") .doTest(); } @Test public void positiveParam() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: public void x(@Var int y) {", " public void x(int y) {", " y++;", " }", "}") .doTest(); } @Test public void negativeParam() { compilationHelper .addSourceLines( "Test.java", // TODO(b/21633565): force line break "class Test {", " public void x(int y) {", " }", "}") .doTest(); } @Test public void positiveLocal() { compilationHelper .addSourceLines( "Test.java", "class Test {", " public void x() {", " // BUG: Diagnostic contains: @Var int y = 0;", " int y = 0;", " y++;", " }", "}") .doTest(); } @Test public void negativeLocal() { compilationHelper .addSourceLines( "Test.java", // TODO(b/21633565): force line break "class Test {", " public void x() {", " int y = 0;", " }", "}") .doTest(); } @Test public void finalLocal7() { compilationHelper .addSourceLines( "Test.java", // TODO(b/21633565): force line break "class Test {", " public void x() {", " final int y = 0;", " }", "}") .setArgs(Arrays.asList("-source", "7", "-target", "7")) .doTest(); } @Test public void finalLocal8() { compilationHelper .addSourceLines( "Test.java", "class Test {", " public void x() {", " // BUG: Diagnostic contains: /*START*/ int y = 0;", " /*START*/ final int y = 0;", " }", "}") .setArgs(Arrays.asList("-source", "8", "-target", "8")) .doTest(); } @Test public void forLoop() { compilationHelper .addSourceLines( "Test.java", "class Test {", " {", " for (int i = 0; i < 10; i++) {", " }", " }", "}") .doTest(); } @Test public void enhancedFor() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f (Iterable<String> xs) {", " for (String x : xs) {", " }", " }", "}") .doTest(); } @Test public void unnecessaryFinalNativeMethod() { compilationHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: native void f(int y);", " native void f(final int y);", "}") .doTest(); } @Test public void nativeMethod() { compilationHelper .addSourceLines( "Test.java", // TODO(b/21633565): force line break "class Test {", " native void f(int y);", "}") .doTest(); } @Test public void abstractMethod() { compilationHelper .addSourceLines( "Test.java", // TODO(b/21633565): force line break "abstract class Test {", " abstract void f(int y);", "}") .doTest(); } @Test public void interfaceMethod() { compilationHelper .addSourceLines( "Test.java", // TODO(b/21633565): force line break "interface Test {", " void f(int y);", "}") .doTest(); } @Test public void varField() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Var;", "class Test {", " @Var public int x = 42;", "}") .doTest(); } @Test public void varParam() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Var;", "class Test {", " public void x(@Var int y) {", " y++;", " }", "}") .doTest(); } @Test public void varLocal() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Var;", "class Test {", " public void x() {", " @Var int y = 0;", " y++;", " }", "}") .doTest(); } @Test public void varCatch() { compilationHelper .addSourceLines( "Test.java", "class Test {", " public void x() {", " try {", " // BUG: Diagnostic contains: missing @Var", " } catch (Exception e) {", " e = null;", " }", " }", "}") .doTest(); } @Test public void finalCatch() { compilationHelper .addSourceLines( "Test.java", "class Test {", " public void x() {", " try {", " // BUG: Diagnostic contains: Unnecessary 'final' modifier.", " } catch (final Exception e) {", " }", " }", "}") .doTest(); } @Test public void finalTWR() { compilationHelper .addSourceLines( "Test.java", "import java.io.InputStream;", "class Test {", " public void x() {", " // BUG: Diagnostic contains: Unnecessary 'final' modifier.", " try (final InputStream is = null) {", " } catch (Exception e) {", " }", " }", "}") .doTest(); } @Test public void nonFinalTWR() { compilationHelper .addSourceLines( "Test.java", "import java.io.InputStream;", "class Test {", " public void x() {", " try (InputStream is = null) {", " } catch (Exception e) {", " }", " }", "}") .doTest(); } @Test public void receiverParameter() { compilationHelper .addSourceLines( "Test.java", "class Test {", " public void f(Test this, int x) {", " this.toString();", " }", "}") .doTest(); } @Test public void suppressedByGeneratedAnnotation() { compilationHelper .addSourceLines( "Test.java", "import javax.annotation.processing.Generated;", "@Generated(\"generator\") class Test {", " public void x() {", " final int y = 0;", " }", "}") .doTest(); } @Test public void suppressedBySuppressWarningsAnnotation() { compilationHelper .addSourceLines( "Test.java", "@SuppressWarnings(\"Var\") class Test {", " public void x() {", " final int y = 0;", " }", "}") .doTest(); } @Test public void notSuppressedByUnrelatedSuppressWarningsAnnotation() { compilationHelper .addSourceLines( "Test.java", "@SuppressWarnings(\"Foo\") class Test {", " public void x() {", " // BUG: Diagnostic contains: Unnecessary 'final' modifier.", " final int y = 0;", " }", "}") .doTest(); } @Test public void effectivelyFinal() { compilationHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.Var;", "class Test {", " int f(", " // BUG: Diagnostic contains: @Var variable is never modified", " @Var int x,", " @Var int y) {", " y++;", " return x + y;", " }", "}") .doTest(); } }
9,863
23.972152
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static org.junit.Assume.assumeTrue; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link StatementSwitchToExpressionSwitch}. */ @RunWith(JUnit4.class) public final class StatementSwitchToExpressionSwitchTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(StatementSwitchToExpressionSwitch.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance( StatementSwitchToExpressionSwitch.class, getClass()); @Test public void switchByEnum_removesRedundantBreak_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {OBVERSE, REVERSE};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case OBVERSE:", " // Explanatory comment", " System.out.println(\"the front is called the\");", " // Middle comment", " System.out.println(\"obverse\");", " // Break comment", " break;", " // End comment", " case REVERSE:", " System.out.println(\"reverse\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {OBVERSE, REVERSE};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case OBVERSE /* left comment */ /* and there is more: */ // to end of line", " :", " // Explanatory comment", " System.out.println(\"the front is called the\");", " // Middle comment", " System.out.println(\"obverse\");", " // Break comment", " break;", " // End comment", " case REVERSE:", " System.out.println(\"reverse\");", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {OBVERSE, REVERSE};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case OBVERSE -> { /* left comment */", " /* and there is more: */", " // to end of line", " // Explanatory comment", " System.out.println(\"the front is called the\");", " // Middle comment", " System.out.println(\"obverse\");", " // Break comment", " }", " case REVERSE -> System.out.println(\"reverse\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnumWithCompletionAnalsis_removesRedundantBreak_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {OBVERSE, REVERSE};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case OBVERSE:", " // Explanatory comment", " System.out.println(\"this block cannot complete normally\");", " {", " throw new NullPointerException();", " }", " case REVERSE:", " System.out.println(\"reverse\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {OBVERSE, REVERSE};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case OBVERSE:", " // Explanatory comment", " System.out.println(\"this block cannot complete normally\");", " {", " throw new NullPointerException();", " }", " case REVERSE:", " System.out.println(\"reverse\");", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {OBVERSE, REVERSE};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case OBVERSE -> {", " // Explanatory comment", " System.out.println(\"this block cannot complete normally\");", " {", " throw new NullPointerException();", " }", " }", " case REVERSE -> ", " System.out.println(\"reverse\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnumCard_combinesCaseComments_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " // Empty block comment 1", " // Fall through", " case SPADE:", " // Empty block comment 2", " case CLUB: ", " // Start of block comment 1", " System.out.println(\"what's not a heart is \");", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART:", " System.out.println(\"heart2\");", " break;", " case /* sparkly */ DIAMOND:", " // Empty block comment 1", " // Fall through", " case SPADE:", " // Empty block comment 2", " case CLUB: ", " // Start of block comment 1", " System.out.println(\"what's not a heart is \");", " System.out.println(\"everything else\");", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART -> System.out.println(\"heart2\");", " case DIAMOND, SPADE, CLUB -> { /* sparkly */", " // Empty block comment 1", " // Empty block comment 2", " // Start of block comment 1", " System.out.println(\"what's not a heart is \");", " System.out.println(\"everything else\");", " }", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnumCard2_removesRedundantBreaks_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " // Pre break comment", " break;", " // Post break comment", " case DIAMOND:", " // Diamond break comment", " break;", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " // Pre break comment", " break;", " // Post break comment", " case DIAMOND:", " // Diamond break comment", " break;", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART -> {", " System.out.println(\"heart\");", " // Pre break comment", " }", " case DIAMOND -> {", " // Diamond break comment", " break;", " }", " case SPADE, CLUB -> System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnumCard_onlyExpressionsAndThrowAreBraceless_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " for(;;) {", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " continue;", " case SPADE:", " return;", " case CLUB:", " throw new AssertionError();", " }", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " for(;;) {", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " continue;", " case SPADE:", " return;", " case CLUB:", " throw new AssertionError();", " }", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " for(;;) {", " switch(side) {", " case HEART ->", " System.out.println(\"heart\");", " case DIAMOND -> {", " continue;", " }", " case SPADE -> {", " return;", " }", " case CLUB -> throw new AssertionError();", " }", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchFallsThruToDefault_noError() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " break;", " case SPADE:", " default:", " System.out.println(\"spade or club\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchFallsThruFromDefault_noError() { // Placing default in the middle of the switch is not recommended, but is valid Java assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " System.out.println(\"diamond\");", " default:", " System.out.println(\"club\");", " break;", " case SPADE:", " System.out.println(\"spade\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchWithDefaultInMiddle_error() { // Placing default in the middle of the switch is not recommended, but is valid Java assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " System.out.println(\"diamond\");", " return;", " default:", " System.out.println(\"club\");", " break;", " case SPADE:", " System.out.println(\"spade\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); // This check does not attempt to re-order cases, for example to move the default to the end, as // this scope is delegated to other tests e.g. SwitchDefault refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " System.out.println(\"diamond\");", " return;", " default /* comment: */:", " System.out.println(\"club\");", " break;", " case SPADE:", " System.out.println(\"spade\");", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART -> System.out.println(\"heart\");", " case DIAMOND -> {", " System.out.println(\"diamond\");", " return;", " }", " default -> { /* comment: */", " System.out.println(\"club\");", " }", " case SPADE -> System.out.println(\"spade\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchWithLabelledBreak_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " outer:", " for(;;) {", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"will return\");", " return;", " case DIAMOND:", " break outer;", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " outer:", " for(;;) {", " switch(side) {", " case HEART:", " System.out.println(\"will return\");", " return;", " case DIAMOND:", " break outer;", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " outer:", " for(;;) {", " switch(side) {", " case HEART -> { ", " System.out.println(\"will return\");", " return;", " }", " case DIAMOND -> {break outer;}", " case SPADE, CLUB -> System.out.println(\"everything else\");", " }", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnum_statementSwitchWithMultipleExpressions_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"will return\");", " return;", " case DIAMOND:", " case SPADE, CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"will return\");", " return;", " case DIAMOND:", " case SPADE, CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART -> {", " System.out.println(\"will return\");", " return;", " }", " case DIAMOND, SPADE, CLUB ->", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnumCardWithThrow_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"will return\");", " return;", " case DIAMOND:", " break;", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchInSwitch_error() { // Only the outer "switch" should generate a finding assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " switch(side) {", " case HEART: ", " case SPADE: ", " System.out.println(\"non-default\");", " break;", " default: ", " System.out.println(\"do nothing\");", " }", " break; ", " case DIAMOND:", " break;", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnumCardWithReturnNested1_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " { System.out.println(\"nested1\"); break; }", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " { System.out.println(\"nested1\"); break; }", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART-> System.out.println(\"heart\");", " case DIAMOND -> {{ System.out.println(\"nested1\"); break; }}", " case SPADE, CLUB -> System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnumCardWithReturnNested2_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " case DIAMOND:", " { System.out.println(\"nested2a\"); ", " {System.out.println(\"nested2b\"); break; } ", " }", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnumWithConditionalControl_noError() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " if(true) {", " break;", " }", " case DIAMOND:", " break;", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnumWithLambda_noError() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", " import java.util.function.Function;", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", // "Last" statement in the HEART block is a return, but we don't want to conclude that // the block has definite control flow based on that " Function<Integer,Integer> x = (i) -> {while(true) {break;} return i;};", " case DIAMOND:", " break;", " case SPADE:", " case CLUB:", " System.out.println(\"everything else\");", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void singleCaseConvertible_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " System.out.println(\"heart\");", " break;", " }", " }", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void emptyExpressionSwitchCases_noMatch() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " void foo(int value) { ", " switch (value) {", " case 0 -> {}", " default -> {}", " }", " }", "}") .doTest(); } @Test public void nonEmptyExpressionSwitchCases_noMatch() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " void foo(int value) { ", " switch (value) {", " case 0 -> System.out.println(\"zero\");", " default -> {System.out.println(\"non-zero\");}", " }", " }", "}") .doTest(); } @Test public void dynamicWithThrowableDuringInitializationFromMethod_noMatch() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " Throwable foo = bar(); ", " public Test(int foo) {", " } ", " ", " private static Throwable bar() { ", " return new NullPointerException(\"initialized with return value\"); ", " } ", "}") .setArgs( ImmutableList.of("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")) .doTest(); } @Test public void switchByEnum_exampleInDocumentation_error() { // This code appears as an example in the documentation (added surrounding class) assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS};", " public Test() {}", " private void foo(Suit suit) {", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(suit) {", " case HEARTS:", " System.out.println(\"Red hearts\");", " break;", " case DIAMONDS:", " System.out.println(\"Red diamonds\");", " break;", " case SPADES:", " // Fall through", " case CLUBS:", " bar();", " System.out.println(\"Black suit\");", " }", " }", " private void bar() {}", "}") .setArgs("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion") .doTest(); refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS};", " public Test() {}", " private void foo(Suit suit) {", " switch(suit) {", " case HEARTS:", " System.out.println(\"Red hearts\");", " break;", " case DIAMONDS:", " System.out.println(\"Red diamonds\");", " break;", " case SPADES:", " // Fall through", " case CLUBS:", " bar();", " System.out.println(\"Black suit\");", " }", " }", " private void bar() {}", "}") .addOutputLines( "Test.java", "class Test {", " enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS};", " public Test() {}", " private void foo(Suit suit) {", " switch(suit) {", " case HEARTS ->", " System.out.println(\"Red hearts\");", " case DIAMONDS ->", " System.out.println(\"Red diamonds\");", " case SPADES, CLUBS -> {", " bar();", " System.out.println(\"Black suit\");", " }", " }", " }", " private void bar() {}", "}") .setArgs("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion") .doTest(); } /********************************** * * Return switch test cases * **********************************/ @Test public void switchByEnum_returnSwitch_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " switch(side) {", " case HEART:", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " return switch(side) {", " case HEART, DIAMOND -> invoke();", " case SPADE -> throw new RuntimeException();", " default -> throw new NullPointerException();", " };", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_returnSwitchWithShouldNeverHappen_error() { assumeTrue(RuntimeVersion.isAtLeast14()); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " switch(side) {", " case HEART:", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " // This should never happen", " int z = invoke();", " z++;", " throw new RuntimeException(\"Switch was not exhaustive at runtime \" + z);", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " return switch(side) {", " case HEART, DIAMOND -> invoke();", " case SPADE -> throw new RuntimeException();", " case CLUB -> throw new NullPointerException();", " };", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_switchInReturnSwitchWithShouldNeverHappen_error() { assumeTrue(RuntimeVersion.isAtLeast14()); // No error because the inner switch is the only fixable one helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " switch(side) {", " case HEART:", " System.out.println(\"hi\");", " switch(side) {", " case HEART:", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " // This should never happen", " int z = invoke();", " z++;", " throw new RuntimeException(\"Switch was not exhaustive at runtime \" + z);", " ", " default: ", " System.out.println(\"default\");", " return 0;", " }", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_exhaustiveWithDefault_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " String z = \"dkfj\";", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(z) {", " case \"\":", " case \"DIAMOND\":", " // Custom comment", " case \"SPADE\":", " return invoke();", " default:", " return 2;", " }", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " String z = \"dkfj\";", " switch(z) {", " case \"\":", " case \"DIAMOND\":", " // Custom comment", " case \"SPADE\":", " return invoke();", " default:", " return 2;", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " String z = \"dkfj\";", " return switch(z) {", " case \"\", \"DIAMOND\", \"SPADE\" ->", " // Custom comment", " invoke();", " default -> 2;", " };", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_defaultFallThru_noError() { // No error because default doesn't return anything within its block assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " switch(side) {", " case HEART:", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " default:", " // Fall through", " }", " return -2;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_alwaysThrows_noError() { // Every case throws, thus no type for return switch assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " switch(side) {", " case HEART:", " case DIAMOND:", " throw new NullPointerException();", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_returnSwitchWithShouldNeverHappen_errorAndRemoveShouldNeverHappen() { // The switch has a case for each enum and "should never happen" error handling assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " System.out.println(\"don't delete 0\");", " if (invoke() > 0) {", " System.out.println(\"don't delete 1\");", " // Preceding comment", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " // Fall through", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " // Custom comment - should never happen", " int z = invoke(/* block comment 0 */);", " {z++;}", " throw new RuntimeException(\"Switch was not exhaustive at runtime \" + z);", " }", " System.out.println(\"don't delete 2\");", " return 0;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " System.out.println(\"don't delete 0\");", " if (invoke() > 0) {", " System.out.println(\"don't delete 1\");", " // Preceding comment", " switch(side) {", " case HEART /* lhs comment */: // rhs comment", " // Fall through", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " // Custom comment - should never happen", " int z = invoke(/* block comment 0 */);", " {z++;}", " throw new RuntimeException(\"Switch was not exhaustive at runtime \" + z);", " }", " System.out.println(\"don't delete 2\");", " return 0;", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " System.out.println(\"don't delete 0\");", " if (invoke() > 0) {", " System.out.println(\"don't delete 1\");", " // Preceding comment", " return switch(side) {", " case HEART, DIAMOND -> ", " /* lhs comment */", " // rhs comment", " invoke();", " case SPADE -> throw new RuntimeException();", " case CLUB -> throw new NullPointerException();", " };", " // Custom comment - should never happen", " }", " System.out.println(\"don't delete 2\");", " return 0;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_returnSwitchNoFollowingStatementsInBlock_errorAndNoRemoval() { // The switch is exhaustive but doesn't have any statements immediately following it in the // lowest ancestor statement block assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " System.out.println(\"don't delete 0\");", " if (invoke() > 0) {", " System.out.println(\"don't delete 1\");", " // Preceding comment", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART /* lhs comment */: // rhs comment", " // Fall through", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " }", " // Custom comment - should never happen because invoke returns 123", " int z = invoke(/* block comment 0 */);", " {z++;}", " throw new RuntimeException(\"Invoke <= 0 at runtime \");", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " System.out.println(\"don't delete 0\");", " if (invoke() > 0) {", " System.out.println(\"don't delete 1\");", " // Preceding comment", " switch(side) {", " case HEART /* lhs comment */: // rhs comment", " // Fall through", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " }", " // Custom comment - should never happen because invoke returns 123", " int z = invoke(/* block comment 0 */);", " {z++;}", " throw new RuntimeException(\"Invoke <= 0 at runtime \");", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " System.out.println(\"don't delete 0\");", " if (invoke() > 0) {", " System.out.println(\"don't delete 1\");", " // Preceding comment", " return switch(side) {", " case HEART, DIAMOND -> ", " /* lhs comment */", " // rhs comment", " invoke();", " case SPADE -> throw new RuntimeException();", " case CLUB -> throw new NullPointerException();", " };", " }", " // Custom comment - should never happen because invoke returns 123", " int z = invoke(/* block comment 0 */);", " {z++;}", " throw new RuntimeException(\"Invoke <= 0 at runtime \");", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_returnSwitchWithShouldNeverHappenInLambda_errorAndRemoveShouldNeverHappen() { // Conversion to return switch within a lambda assumeTrue(RuntimeVersion.isAtLeast14()); refactoringHelper .addInputLines( "Test.java", "import java.util.function.Supplier;", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " Supplier<Integer> lambda = () -> {", " // Preceding comment", " switch(side) {", " case HEART :", " // Fall through", " case DIAMOND:", " return invoke();", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " // Custom comment - should never happen", " int z = invoke(/* block comment 0 */);", " z++;", " throw new RuntimeException(\"Switch was not exhaustive at runtime \" + z);", " };", " System.out.println(\"don't delete 2\");", " return lambda.get();", " }", "}") .addOutputLines( "Test.java", "import java.util.function.Supplier;", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int invoke() {", " return 123;", " }", " public int foo(Side side) { ", " Supplier<Integer> lambda = () -> {", " // Preceding comment", " return switch(side) {", " case HEART, DIAMOND -> invoke();", " case SPADE -> throw new RuntimeException();", " case CLUB -> throw new NullPointerException();", " };", " // Custom comment - should never happen", " };", " System.out.println(\"don't delete 2\");", " return lambda.get();", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_returnSwitchVoid_noError() { // A void cannot be converted to a return switch assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public void foo(Side side) { ", " switch(side) {", " case HEART:", " // Fall through", " case DIAMOND:", " return;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_returnLabelledContinue_noError() { // Control jumps outside the switch for HEART assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " before:", " for(;;) {", " switch(side) {", " case HEART:", " continue before;", " case DIAMOND:", " return 3;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " }", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_returnUnlabelledContinue_noError() { // Control jumps outside the switch for HEART assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " before:", " for(;;) {", " switch(side) {", " case HEART:", " continue;", " case DIAMOND:", " return 3;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " }", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_returnLabelledBreak_noError() { // Control jumps outside the switch for HEART assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " before:", " for(;;) {", " switch(side) {", " case HEART:", " break before;", " case DIAMOND:", " return 3;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " }", " return 0;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } @Test public void switchByEnum_returnYield_noError() { // Does not attempt to convert "yield" expressions assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " return switch(side) {", " case HEART:", " yield 2;", " case DIAMOND:", " yield 3;", " case SPADE:", " // Fall through", " default:", " throw new NullPointerException();", " };", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion")) .doTest(); } /********************************** * * Assignment switch test cases * **********************************/ @Test public void switchByEnum_assignmentSwitchToLocalHasDefault_error() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " case DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); // Check correct generated code refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " switch(side) {", " case HEART:", " case DIAMOND:", " x = ((x+1) * (x*x)) << 1;", " break;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " return x;", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " x = switch(side) {", " case HEART, DIAMOND ->", " ((x+1) * (x*x)) << 1;", " case SPADE ->", " throw new RuntimeException();", " default ->", " throw new NullPointerException();", " };", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_assignmentSwitchMixedReferences_error() { // Must deduce that "x" and "this.x" refer to same thing assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x;", " public Test(int foo) {", " x = -1;", " }", " ", " public int foo(Side side) { ", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case /* LHS comment */ HEART:", " // Inline comment", " x <<= 2;", " break;", " case DIAMOND:", " this.x <<= (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); // Check correct generated code. // Note that suggested fix uses the style of the first case (in source order). refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x;", " public Test(int foo) {", " x = -1;", " }", " ", " public int foo(Side side) { ", " switch(side) {", " case /* LHS comment */ HEART:", " // Inline comment", " this.x <<= 2;", " break;", " case DIAMOND:", " x <<= (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " return x;", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x;", " public Test(int foo) {", " x = -1;", " }", " ", " public int foo(Side side) { ", " this.x <<= switch(side) {", " case HEART -> /* LHS comment */", " // Inline comment", " 2;", " case DIAMOND -> (((x+1) * (x*x)) << 1);", " case SPADE -> throw new RuntimeException();", " default -> throw new NullPointerException();", " };", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_assignmentSwitchMixedReferences_noError() { // Must deduce that "x" and "this.y" refer to different things assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x, y;", " public Test(int foo) {", " x = -1;", " y = -1;", " }", " ", " public int foo(Side side) { ", " switch(side) {", " case HEART:", " x = 2;", " break;", " case DIAMOND:", " this.y = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_assignmentSwitchTwoAssignments_noError() { // Can't convert multiple assignments, even if redundant assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x;", " public Test(int foo) {", " x = -1;", " }", " ", " public int foo(Side side) { ", " switch(side) {", " case HEART:", " x = 2;", " x = 3;", " break;", " case DIAMOND:", " this.x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_assignmentSwitchMixedKinds_noError() { // Different assignment types ("=" versus "+="). The check does not attempt to alter the // assignments to make the assignment types match (e.g. does not change to "x = x + 2") assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x;", " public Test(int foo) {", " x = -1;", " }", " ", " public int foo(Side side) { ", " switch(side) {", " case HEART:", " x += 2;", " break;", " case DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " default:", " throw new NullPointerException();", " }", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_assignmentLabelledContinue_noError() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x;", " public Test(int foo) {", " x = -1;", " }", " ", " public int foo(Side side) { ", " before:", " for(;;) {", " switch(side) {", " case HEART:", " x = 2;", " break;", " case DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " continue before;", " default:", " throw new NullPointerException();", " }", " break;", " }", " after:", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_assignmentLabelledBreak_noError() { // Can't convert because of "break before" assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x;", " public Test(int foo) {", " x = -1;", " }", " ", " public int foo(Side side) { ", " before:", " for(;;) {", " switch(side) {", " case HEART:", " x = 2;", " break;", " case DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " break before;", " default:", " throw new NullPointerException();", " }", " break;", " }", " after:", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_assignmentLabelledBreak2_noError() { // Can't convert because of "break before" as the second statement in its block assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x;", " public Test(int foo) {", " x = -1;", " }", " ", " public int foo(Side side) { ", " before:", " for(;;) {", " switch(side) {", " case HEART:", " x = 2;", " break;", " case DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " x = 3;", " break before;", " default:", " throw new NullPointerException();", " }", " break;", " }", " after:", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_assignmentUnlabelledContinue_noError() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " int x;", " public Test(int foo) {", " x = -1;", " }", " ", " public int foo(Side side) { ", " before:", " for(;;) {", " switch(side) {", " case HEART:", " x = 2;", " break;", " case DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " continue;", " default:", " throw new NullPointerException();", " }", " break;", " }", " after:", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_assignmentYield_noError() { // Does not attempt to convert "yield" expressions assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = switch(side) {", " case HEART:", " yield 2;", " case DIAMOND:", " yield 3;", " case SPADE:", " // Fall through", " default:", " throw new NullPointerException();", " };", " x <<= 1;", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_exhaustiveAssignmentSwitch_error() { // Transformation can change error handling. Here, if the enum is not exhaustive at runtime // (say there is a new JOKER suit), then nothing would happen. But the transformed source, // would throw. assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " // Heart comment", " // Fall through", " case DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " switch(side) {", " case HEART:", " // Heart comment", " // Fall through", " case DIAMOND:", " x = (((x+1) * (x*x)) << 2);", " break;", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " return x;", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " x = switch(side) {", " case HEART, DIAMOND -> ", " // Heart comment", " (((x+1) * (x*x)) << 2);", " case SPADE -> throw new RuntimeException();", " case CLUB -> throw new NullPointerException();", " };", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_exhaustiveCompoundAssignmentSwitch_error() { // Verify compound assignments (here, +=) assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART:", " case DIAMOND:", " x += (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " switch(side) {", " case HEART:", " case DIAMOND:", " x += (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " return x;", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " x += switch(side) {", " case HEART, DIAMOND -> (((x+1) * (x*x)) << 1);", " case SPADE -> throw new RuntimeException();", " case CLUB -> throw new NullPointerException();", " };", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_compoundAssignmentExampleInDocumentation_error() { // This code appears as an example in the documentation (added surrounding class) assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS};", " int score = 0;", " public Test() {}", " private void updateScore(Suit suit) {", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(suit) {", " case HEARTS:", " // Fall thru", " case DIAMONDS:", " score += -1;", " break;", " case SPADES:", " score += 2;", " break;", " case CLUBS:", " score += 3;", " break;", " }", " }", "}") .setArgs("-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion") .doTest(); refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS};", " int score = 0;", " public Test() {}", " private void updateScore(Suit suit) {", " switch(suit) {", " case HEARTS:", " // Fall thru", " case DIAMONDS:", " score += -1;", " break;", " case SPADES:", " score += 2;", " break;", " case CLUBS:", " score += 3;", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS};", " int score = 0;", " public Test() {}", " private void updateScore(Suit suit) {", " score += switch(suit) {", " case HEARTS, DIAMONDS -> -1;", " case SPADES -> 2;", " case CLUBS -> 3;", " };", " }", "}") .setArgs("-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion") .doTest(); } @Test public void switchByEnum_exhaustiveAssignmentSwitchCaseList_error() { // Statement switch has cases with multiple values assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " // BUG: Diagnostic contains: [StatementSwitchToExpressionSwitch]", " switch(side) {", " case HEART, DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE, CLUB:", " throw new NullPointerException();", " }", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); refactoringHelper .addInputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " switch(side) {", " case HEART, DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE, CLUB:", " throw new NullPointerException();", " }", " return x;", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " x = switch(side) {", " case HEART, DIAMOND -> (((x+1) * (x*x)) << 1);", " case SPADE, CLUB -> throw new NullPointerException();", " };", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } @Test public void switchByEnum_nonExhaustiveAssignmentSwitch_noError() { // No HEART case assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( "Test.java", "class Test {", " enum Side {HEART, SPADE, DIAMOND, CLUB};", " public Test(int foo) {", " }", " ", " public int foo(Side side) { ", " int x = 0;", " switch(side) {", " case DIAMOND:", " x = (((x+1) * (x*x)) << 1);", " break;", " case SPADE:", " throw new RuntimeException();", " case CLUB:", " throw new NullPointerException();", " }", " return x;", " }", "}") .setArgs( ImmutableList.of( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion")) .doTest(); } }
96,632
33.760072
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/XorPowerTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link XorPower}Test */ @RunWith(JUnit4.class) public class XorPowerTest { @Test public void positive() { BugCheckerRefactoringTestHelper.newInstance(XorPower.class, getClass()) .addInputLines( "Test.java", "class Test {", " static final int X = 2 ^ 16;", " static final int Y = 2 ^ 32;", " static final int Z = 2 ^ 31;", " static final int P = 10 ^ 6;", "}") .addOutputLines( "Test.java", "class Test {", " static final int X = 1 << 16;", " static final int Y = 2 ^ 32;", " static final int Z = 1 << 31;", " static final int P = 1000000;", "}") .doTest(); } @Test public void negative() { CompilationTestHelper.newInstance(XorPower.class, getClass()) .addSourceLines( "Test.java", "class Test {", " static final int X = 2 ^ 0x16;", " // BUG: Diagnostic contains:", " static final int Y = 2 ^ 32;", "}") .doTest(); } }
1,992
30.634921
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AssertionFailureIgnoredTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link AssertionFailureIgnored}Test */ @RunWith(JUnit4.class) public class AssertionFailureIgnoredTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(AssertionFailureIgnored.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "Test.java", // "import org.junit.Assert;", "class Test {", " void f() {", " try {", " // BUG: Diagnostic contains:", " Assert.fail();", " } catch (Throwable t) {", " }", " try {", " // BUG: Diagnostic contains:", " Assert.fail();", " } catch (AssertionError t) {", " }", " try {", " if (true) throw new NoSuchFieldException();", " if (true) throw new NoSuchMethodException();", " // BUG: Diagnostic contains:", " Assert.fail();", " } catch (NoSuchFieldException | NoSuchMethodException | AssertionError t) {", " }", " AssertionError e = null;", " try {", " // BUG: Diagnostic contains:", " Assert.fail();", " } catch (AssertionError t) {", " throw e;", " }", " try {", " // BUG: Diagnostic contains:", " Assert.fail();", " } catch (AssertionError t) {", " throw new AssertionError(e);", " }", " }", "}") .doTest(); } @Test public void negative() { testHelper .addSourceLines( "Test.java", // "import org.junit.Assert;", "import java.io.IOException;", "class Test {", " void f() {", " try {", " if (true) throw new IOException();", " Assert.fail();", " } catch (IOException t) {", " }", " try {", " Assert.fail();", " } catch (Exception t) {", " }", " try {", " if (true) throw new NoSuchFieldException();", " if (true) throw new NoSuchMethodException();", " Assert.fail();", " } catch (NoSuchFieldException | NoSuchMethodException t) {", " }", " try {", " } catch (Throwable t) {", " Assert.fail();", " }", " try {", " Assert.fail();", " } catch (AssertionError t) {", " throw t;", " }", " try {", " Assert.fail();", " } catch (AssertionError t) {", " throw new AssertionError(t);", " }", " }", "}") .doTest(); } @Test public void refactoring() { BugCheckerRefactoringTestHelper.newInstance(AssertionFailureIgnored.class, getClass()) .addInputLines( "in/Test.java", // "import org.junit.Assert;", "import java.io.IOException;", "import static com.google.common.truth.Truth.assertThat;", "class Test {", " void f() {", " try {", " System.err.println();", " Assert.fail();", " } catch (AssertionError t) {", " assertThat(t).isInstanceOf(AssertionError.class);", " }", " try {", " System.err.println();", " Assert.fail();", " } catch (AssertionError e) {", " }", " try {", " if (true) throw new IOException();", " Assert.fail();", " } catch (AssertionError e) {", " } catch (Exception e) {", " }", " try {", " if (true) throw new NoSuchFieldException();", " if (true) throw new NoSuchMethodException();", " Assert.fail();", " } catch (AssertionError | NoSuchFieldException | NoSuchMethodException e) {", " }", " }", "}") .addOutputLines( "out/Test.java", // "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.assertThrows;", "import java.io.IOException;", "import org.junit.Assert;", "class Test {", " void f() {", " AssertionError t = assertThrows(AssertionError.class, () -> ", " System.err.println());", " assertThat(t).isInstanceOf(AssertionError.class);", " assertThrows(AssertionError.class, () -> ", " System.err.println());", " try {", " if (true) throw new IOException();", " Assert.fail();", " } catch (AssertionError e) {", " } catch (Exception e) {", " }", " try {", " if (true) throw new NoSuchFieldException();", " if (true) throw new NoSuchMethodException();", " Assert.fail();", " } catch (AssertionError | NoSuchFieldException | NoSuchMethodException e) {", " }", " }", "}") .doTest(); } @Test public void refactoringStatements() { BugCheckerRefactoringTestHelper.newInstance(AssertionFailureIgnored.class, getClass()) .addInputLines( "in/Test.java", // "import org.junit.Assert;", "import java.io.IOException;", "import static com.google.common.truth.Truth.assertThat;", "class Test {", " void f() {", " try {", " System.err.println();", " System.err.println();", " Assert.fail();", " } catch (AssertionError t) {", " assertThat(t).isInstanceOf(AssertionError.class);", " }", " try {", " System.err.println();", " System.err.println();", " Assert.fail();", " } catch (AssertionError e) {", " }", " try {", " if (true) throw new AssertionError();", " Assert.fail();", " } catch (AssertionError e) {", " }", " }", "}") .addOutputLines( "out/Test.java", // "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.assertThrows;", "import java.io.IOException;", "import org.junit.Assert;", "class Test {", " void f() {", " AssertionError t = assertThrows(AssertionError.class, () -> {", " System.err.println();", " System.err.println();", " });", " assertThat(t).isInstanceOf(AssertionError.class);", " assertThrows(AssertionError.class, () -> {", " System.err.println();", " System.err.println();", " });", " assertThrows(AssertionError.class, () -> {", " if (true) throw new AssertionError();", " });", " }", "}") .doTest(); } @Test public void union() { testHelper .addSourceLines( "Test.java", // "import org.junit.Assert;", "import java.io.IOError;", "class Test {", " void f() {", " try {", " if (true) throw new NullPointerException();", " Assert.fail();", " } catch (NullPointerException | IOError t) {", " }", " }", "}") .doTest(); } }
9,131
34.533074
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallSuggesterTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests the {@link DoNotCallSuggester}. */ @RunWith(JUnit4.class) public class DoNotCallSuggesterTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(DoNotCallSuggester.class, getClass()); @Test public void finalClass_publicFinalMethod() { testHelper .addSourceLines( "Test.java", "final class Test {", " // BUG: Diagnostic contains: Always throws java.lang.RuntimeException", " public final void foo() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_withInlineComments_type1() { testHelper .addSourceLines( "Test.java", "final class Test {", " // BUG: Diagnostic contains: Always throws java.lang.RuntimeException", " public final void foo() {", " // inline comments get stripped and don't matter", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_withInlineComments_type2() { testHelper .addSourceLines( "Test.java", "final class Test {", " // BUG: Diagnostic contains: Always throws java.lang.RuntimeException", " public final void foo() {", " /* inline comments get stripped and don't matter */", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicNonFinalMethod() { testHelper .addSourceLines( "Test.java", "final class Test {", " // BUG: Diagnostic contains: Always throws java.lang.RuntimeException", " public void foo() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void nonFinalClass_publicFinalMethod() { testHelper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: Always throws java.lang.RuntimeException", " public final void foo() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void nonFinalClass_publicNonFinalMethod() { // no suggestion since the method is overrideable testHelper .addSourceLines( "Test.java", "class Test {", " public void foo() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_throwsAVariable() { testHelper .addSourceLines( "Test.java", "import java.io.IOException;", "final class Test {", " private IOException ioe = new IOException();", " // BUG: Diagnostic contains: Always throws java.io.IOException", " public final void foo() throws IOException {", " throw ioe;", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_throwsAnotherMethod() { testHelper .addSourceLines( "Test.java", "import java.io.IOException;", "final class Test {", " // BUG: Diagnostic contains: Always throws java.io.IOException", " public final void foo() throws IOException {", " throw up();", " }", " private IOException up() {", " return new IOException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_withoutImplementingParentInterface() { testHelper .addSourceLines( "Test.java", "final class Test {", " // BUG: Diagnostic contains: Always throws java.lang.RuntimeException", " public final String get() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_overriddenMethod() { testHelper .addSourceLines( "Test.java", "import java.util.function.Supplier;", "final class Test implements Supplier<String> {", " @Override", " public final String get() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_effectivelyOverriddenMethod() { testHelper .addSourceLines( "Test.java", "import java.util.function.Supplier;", "final class Test implements Supplier<String> {", " public final String get() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_methodStartsWithProvide() { testHelper .addSourceLines( "Test.java", "final class Test {", " public final String provideString() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_methodStartsWithProduce() { testHelper .addSourceLines( "Test.java", "final class Test {", " public final String produceString() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_methodStartsWithThrows() { testHelper .addSourceLines( "Test.java", "final class Test {", " public final void throwsRuntimeException() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicFinalMethod_extendsAbstractModule() { testHelper .addSourceLines( "AbstractModule.java", "package com.google.inject;", "public abstract class AbstractModule {", "}") .addSourceLines( "Test.java", "final class Test extends com.google.inject.AbstractModule {", " public final String extractString() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void finalClass_publicMethod_methodReturnsException() { testHelper .addSourceLines( "Test.java", "final class Test {", " public RuntimeException foo() {", " throw new RuntimeException();", " }", "}") .doTest(); } @Test public void insideAnonymousClass() { testHelper .addSourceLines( "Test.java", "final class Test {", " public final void foo() {", " Object obj = new Object() {", " public void foo() {", " throw new RuntimeException();", " }", " };", " }", "}") .doTest(); } @Test public void abstractClass() { testHelper .addSourceLines( "Test.java", // "abstract class Test {", " abstract void test();", "}") .doTest(); } @Test public void annotatedMethod() { testHelper .addSourceLines( "StarlarkMethod.java", "package net.starlark.java.annot;", "public @interface StarlarkMethod {", "}") .addSourceLines( "Test.java", "import net.starlark.java.annot.StarlarkMethod;", "final class Test {", " @StarlarkMethod", " public static void foo() {", " throw new RuntimeException();", " }", "}") .doTest(); } }
9,017
27.903846
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InvalidPatternSyntaxTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author mdempsky@google.com (Matthew Dempsky) */ @RunWith(JUnit4.class) public class InvalidPatternSyntaxTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InvalidPatternSyntax.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("InvalidPatternSyntaxPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("InvalidPatternSyntaxNegativeCases.java").doTest(); } }
1,321
29.744186
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MixedArrayDimensionsTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link MixedArrayDimensions}Test */ @RunWith(JUnit4.class) public class MixedArrayDimensionsTest { @Test public void positiveVariable() { BugCheckerRefactoringTestHelper.newInstance(MixedArrayDimensions.class, getClass()) .addInputLines( "in/Test.java", "abstract class Test {", " int a [] = null;", " int [] b [][];", " int [][] c [] = null;", " int [][] d [][];", "}") .addOutputLines( "out/Test.java", "abstract class Test {", " int[] a = null;", " int [][][] b ;", " int [][][] c = null;", " int [][][][] d ;", "}") .doTest(TEXT_MATCH); } @Test public void positiveMethod() { BugCheckerRefactoringTestHelper.newInstance(MixedArrayDimensions.class, getClass()) .addInputLines( "in/Test.java", "abstract class Test {", " int f() [] { return null; }", " abstract int[] g() [];", " int[] h() [][] { return null; }", " abstract int[][] i() [][];", "}") .addOutputLines( "out/Test.java", "abstract class Test {", " int[] f() { return null; }", " abstract int[][] g() ;", " int[][][] h() { return null; }", " abstract int[][][][] i() ;", "}") .doTest(TEXT_MATCH); } @Test public void negative() { CompilationTestHelper.newInstance(MixedArrayDimensions.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " int[] f() { return null; }", " abstract int[][] g();", " int[][][] h() { return null; }", " abstract int[][][][] i();", " int [] a = null;", " void f(boolean[]... xs) {}", "}") .doTest(); } @Test public void negativeInSimpleCharStream() { CompilationTestHelper.newInstance(MixedArrayDimensions.class, getClass()) .addSourceLines( "SimpleCharStream.java", // "final class SimpleCharStream {", " void test() {", " int a[];", " }", "}") .doTest(); } @Test public void comment() { CompilationTestHelper.newInstance(MixedArrayDimensions.class, getClass()) .addSourceLines( "Test.java", // "abstract class Test {", " int /*@Nullable*/ [] x;", "}") .doTest(); } }
3,582
30.156522
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ComparisonContractViolatedTest.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 lowasser@google.com (Louis Wasserman) */ @RunWith(JUnit4.class) public class ComparisonContractViolatedTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ComparisonContractViolated.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("ComparisonContractViolatedPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("ComparisonContractViolatedNegativeCases.java").doTest(); } }
1,344
31.02381
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MemberNameTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link MemberName}. */ @RunWith(JUnit4.class) public class MemberNameTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(MemberName.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(MemberName.class, getClass()); @Test public void nameWithUnderscores() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private int foo_bar;", " int get() {", " return foo_bar;", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int fooBar;", " int get() {", " return fooBar;", " }", "}") .doTest(); } @Test public void staticFields() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private static int Foo;", " private static int FooBar;", " private static int Bar_Foo;", "}") .addOutputLines( "Test.java", "class Test {", " private static int foo;", " private static int fooBar;", " private static int barFoo;", "}") .doTest(); } @Test public void nameWithUnderscores_mixedCasing() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private int foo_barBaz;", " int get() {", " return foo_barBaz;", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int fooBarBaz;", " int get() {", " return fooBarBaz;", " }", "}") .doTest(); } @Test public void localVariable_renamed() { refactoringHelper .addInputLines( "Test.java", "class Test {", " int get() {", " int foo_bar = 1;", " return foo_bar;", " }", "}") .addOutputLines( "Test.java", "class Test {", " int get() {", " int fooBar = 1;", " return fooBar;", " }", "}") .doTest(); } @Test public void resourceVariable_renamed() { refactoringHelper .addInputLines( "Test.java", "import java.io.ByteArrayOutputStream;", "import java.io.IOException;", "class Test {", " void run() throws IOException {", " try (var output_stream = new ByteArrayOutputStream()) {}", " }", "}") .addOutputLines( "Test.java", "import java.io.ByteArrayOutputStream;", "import java.io.IOException;", "class Test {", " void run() throws IOException {", " try (var outputStream = new ByteArrayOutputStream()) {}", " }", "}") .doTest(); } @Test public void exceptionParameter_renamed() { refactoringHelper .addInputLines( "Test.java", "class Test {", " void run() {", " try {", " run();", " } catch (StackOverflowError stack_overflow) {", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " void run() {", " try {", " run();", " } catch (StackOverflowError stackOverflow) {", " }", " }", "}") .doTest(); } @Test public void nameWithUnderscores_public_notRenamed() { refactoringHelper .addInputLines( "Test.java", "class Test {", " public int foo_bar;", " int get() {", " return foo_bar;", " }", "}") .expectUnchanged() .doTest(); } @Test public void nameWithLeadingUppercase() { helper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains:", " private int Foo;", " int get() {", " return Foo;", " }", "}") .doTest(); } @Test public void upperCamelCaseAndNotStatic_noFinding() { helper .addSourceLines( "Test.java", // "class Test {", " private int FOO;", "}") .doTest(); } @Test public void upperCamelCaseAndStatic_noFinding() { helper .addSourceLines( "Test.java", // "class Test {", " private static final int FOO_BAR = 1;", "}") .doTest(); } @Test public void methodNamedParametersFor_noFinding() { helper .addSourceLines( "Test.java", // "class Test {", " public void parametersForMyFavouriteTest_whichHasUnderscores() {}", "}") .doTest(); } @Test public void methodAnnotatedWithAnnotationContainingTest_exempted() { helper .addSourceLines( "Test.java", // "class Test {", " @IAmATest", " public void possibly_a_test_name() {}", " private @interface IAmATest {}", "}") .doTest(); } @Test public void ignoreTestMissingTestAnnotation_exempted() { helper .addSourceLines( "Test.java", // "import org.junit.Ignore;", "class Test {", " @Ignore", " public void possibly_a_test_name() {}", "}") .doTest(); } @Test public void superMethodAnnotatedWithAnnotationContainingTest_exempted() { helper .addSourceLines( "Test.java", // "class Test {", " @IAmATest", " public void possibly_a_test_name() {}", " private @interface IAmATest {}", "}") .addSourceLines( "Test2.java", "class Test2 extends Test {", " @Override", " public void possibly_a_test_name() {}", "}") .doTest(); } @Test public void nativeMethod_ignored() { helper .addSourceLines( "Test.java", // "class Test {", " public native void possibly_a_test_name();", "}") .doTest(); } @Test public void methodAnnotatedWithExemptedMethod_noMatch() { helper .addSourceLines( "Property.java", // "package com.pholser.junit.quickcheck;", "public @interface Property {}") .addSourceLines( "Test.java", // "class Test {", " @com.pholser.junit.quickcheck.Property", " public void possibly_a_test_name() {}", "}") .doTest(); } @Test public void methodWithUnderscores_overriddenFromSupertype_noFinding() { helper .addSourceLines( "Base.java", "abstract class Base {", " @SuppressWarnings(\"MemberName\")", // We only care about the subtype in this test. " abstract int get_some();", "}") .addSourceLines( "Test.java", "class Test extends Base {", " @Override", " public int get_some() {", " return 0;", " }", "}") .doTest(); } @Test public void methodWithUnderscores_notOverriddenFromGeneratedSupertype_bug() { helper .addSourceLines( "Base.java", "import javax.annotation.Generated;", "@Generated(\"Hands\")", "abstract class Base {}") .addSourceLines( "Test.java", "class Test extends Base {", " // BUG: Diagnostic contains:", " public int get_more() {", " return 0;", " }", "}") .doTest(); } @Test public void nonConformantOverride_nameMatchesSuper_ignored() { helper .addSourceLines( "Base.java", "interface Base {", " // BUG: Diagnostic contains:", " void foo(int a_b);", "}") .addSourceLines( "Test.java", // "class Test implements Base {", " public void foo(int a_b) {}", "}") .doTest(); } @Test public void nonConformantOverride_nameDoesNotMatchSuper_flagged() { helper .addSourceLines( "Base.java", "interface Base {", " // BUG: Diagnostic contains:", " void foo(int a_b);", "}") .addSourceLines( "Test.java", "class Test implements Base {", " // BUG: Diagnostic contains:", " public void foo(int a_b_c) {}", "}") .doTest(); } @Test public void initialismsInMethodNames_partOfCamelCase() { helper .addSourceLines( "Test.java", "interface Test {", " // BUG: Diagnostic contains: getRpcPolicy", " int getRPCPolicy();", " // BUG: Diagnostic contains: getRpc", " int getRPC();", "}") .doTest(); } @Test public void initialismsInVariableNames_partOfCamelCase() { helper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: getRpcPolicy", " int getRPCPolicy;", " // BUG: Diagnostic contains: getRpc", " int getRPC;", "}") .doTest(); } @Test public void initialismsInVariableNames_magicNamesExempt() { helper .addSourceLines( "Test.java", // "class Test {", " private static final long serialVersionUID = 0;", "}") .doTest(); } @Test public void lambdaExpressionParameterInsideOverridingMethod() { helper .addSourceLines( "Test.java", "import java.util.function.Function;", "class Test {", " @Override", " public String toString() {", " // BUG: Diagnostic contains: fooBar", " Function<String, String> f = foo_bar -> foo_bar;", " return f.apply(\"foo\");", " }", "}") .doTest(); } }
11,725
26.018433
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DoNotUseRuleChainTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link DoNotUseRuleChain} */ @RunWith(JUnit4.class) public class DoNotUseRuleChainTest { private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(DoNotUseRuleChain.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(DoNotUseRuleChain.class, getClass()); @Test public void negativeEmptyFile() { compilationHelper.addSourceLines("EmptyFile.java", "// Empty file").doTest(); } @Test public void negativeRuleChainNoInitializer() { compilationHelper .addSourceLines( "RuleChainNoInitializer.java", "package rulechainnoinitializer;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class RuleChainNoInitializer {", "@Rule", "public RuleChain notInitializedRule;", "}") .doTest(); } @Test public void negativeEmptyRuleChain() { compilationHelper .addSourceLines( "EmptyRuleChain.java", "package emptyrulechain;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class EmptyRuleChain {", "@Rule", "public final RuleChain emptyRuleChain = RuleChain.emptyRuleChain();", customRuleClasses(), "}") .doTest(); } @Test public void negativeNullRuleChain() { compilationHelper .addSourceLines( "NullRuleChain.java", "package nullrulechain;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class NullRuleChain {", "@Rule", "public final RuleChain nullRuleChain = null;", customRuleClasses(), "}") .doTest(); } @Test public void negativeLocalVariable() { compilationHelper .addSourceLines( "LocalVariable.java", "package localvariable;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class LocalVariable {", "public void doNothing() {", "RuleChain ruleChain = RuleChain.outerRule(new Rule2()).around(new Rule3());", "}", customRuleClasses(), "}") .doTest(); } @Test public void negativeSingleRules() { compilationHelper .addSourceLines( "SingleRule.java", "package singlerule;", "import org.junit.Rule;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class SingleRule {", "@Rule", "public final Rule1 ruleOne = new Rule1(null, null);", customRuleClasses(), "}") .doTest(); } @Test public void negativeOrderedRules() { compilationHelper .addSourceLines( "OrderedRules.java", "package orderedrules;", "import org.junit.Rule;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class OrderedRules {", "@Rule(order = 0)", "public final Rule1 ruleOne = new Rule1(\"unused\", new Rule2());", "@Rule(order = 1)", "public final Rule2 ruleTwo = new Rule2();", "@Rule(order = 2)", "public final Rule3 ruleThree = new Rule3();", customRuleClasses(), "}") .doTest(); } @Test public void negativeOrderedRulesClassRules() { compilationHelper .addSourceLines( "OrderedRulesClassRules.java", "package orderedrulesclassRules;", "import org.junit.Rule;", "import org.junit.ClassRule;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class OrderedRulesClassRules {", "@Rule(order = 0)", "public final Rule1 ruleOne = new Rule1(\"unused\", new Rule2());", "@Rule(order = 1)", "public final Rule2 ruleTwo = new Rule2();", "@ClassRule(order = 0)", "public static final Rule4 ruleFour = new Rule4();", customRuleClasses(), "}") .doTest(); } @Test public void negativeChainedRulesChain() { compilationHelper .addSourceLines( "OrderedRuleChain.java", "package orderedrulechain;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class OrderedRuleChain {", "@Rule(order = 0)", "public final RuleChain orderedRuleChain = RuleChain.outerRule(new Rule3())", ".around(RuleChain.outerRule(new Rule2()).around(new Rule3()));", customRuleClasses(), "}") .doTest(); } @Test public void negativeMultipleRuleChains() { compilationHelper .addSourceLines( "MultipleRuleChains.java", "package multiplerulechains;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class MultipleRuleChains {", "public final Rule5<Rule2> varRule52 = new Rule5();", "@Rule", "public final RuleChain ruleChain = RuleChain.outerRule(", "new Rule1(\"unused\", new Rule2()))", ".around(new Rule2()).around(new Rule5());", "@Rule", "public final RuleChain ruleChain2 = RuleChain.outerRule(new Rule3()).around(", "varRule52);", customRuleClasses(), "}") .doTest(); } @Test public void refactoringOrderedRulesChain() { refactoringHelper .addInputLines( "OrderedRuleChain.java", "package orderedrulechain;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class OrderedRuleChain {", "@Rule(order = 0)", "// BUG: Diagnostic contains: Do not use RuleChain", "public final RuleChain orderedRuleChain = RuleChain.outerRule(new Rule3())", ".around(new Rule2());", customRuleClasses(), "}") .addOutputLines( "OrderedRuleChain.java", "package orderedrulechain;", "import org.junit.Rule;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class OrderedRuleChain {", "@Rule(order = 0)", "public final Rule3 testRuleRule3 = new Rule3();", "@Rule(order = 1)", "public final Rule2 testRuleRule2 = new Rule2();", customRuleClasses(), "}") .doTest(); } @Test public void refactoringUnorderedRuleChainWithNewObjects() { refactoringHelper .addInputLines( "UnorderedRuleChainWithNewObjects.java", "package orderedrulechainwithnewobjects;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithNewObjects {", "@Rule", "// BUG: Diagnostic contains: Do not use RuleChain", "public final RuleChain ruleChain = RuleChain.outerRule(", "new Rule1(\"really big string so that the new falls into another line\"", ", new Rule2()))", ".around(new Rule2()).around(new Rule5()).around((base, description) ->", "new Statement() {", "@Override", "public void evaluate() throws Throwable {", "// Do nothing", "}", "});", customRuleClasses(), "}") .addOutputLines( "UnorderedRuleChainWithNewObjects.java", "package orderedrulechainwithnewobjects;", "import org.junit.Rule;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithNewObjects {", "@Rule(order = 0)", "public final Rule1 testRuleRule1 =", "new Rule1(\"really big string so that the new falls into another line\"", ", new Rule2());", "@Rule(order = 1)", "public final Rule2 testRuleRule2 = new Rule2();", "@Rule(order = 2)", "public final Rule5 testRuleRule5 = new Rule5();", "@Rule(order = 3)", "public final TestRule testRuleTestRule = (base, description) ->", "new Statement() {", "@Override", "public void evaluate() throws Throwable {", "// Do nothing", "}", "};", customRuleClasses(), "}") .doTest(); } @Test public void refactoringUnorderedRuleChainWithExistingObjects() { refactoringHelper .addInputLines( "UnorderedRuleChainWithExistingObjects.java", "package orderedrulechainwithexistingobjects;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithExistingObjects {", "public final Rule1 varRule1 = new Rule1(\"unused\", new Rule2());", "public final Rule2 varRule2 = new Rule2();", "@Rule", "// BUG: Diagnostic contains: Do not use RuleChain", "public final RuleChain ruleChain = RuleChain.outerRule(varRule1).around(varRule2);", customRuleClasses(), "}") .addOutputLines( "UnorderedRuleChainWithExistingObjects.java", "package orderedrulechainwithexistingobjects;", "import org.junit.Rule;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithExistingObjects {", "public final Rule1 varRule1 = new Rule1(\"unused\", new Rule2());", "public final Rule2 varRule2 = new Rule2();", "@Rule(order = 0)", "public final Rule1 testRuleRule1 = varRule1;", "@Rule(order = 1)", "public final Rule2 testRuleRule2 = varRule2;", customRuleClasses(), "}") .doTest(); } @Test public void refactoringUnorderedRuleChainWithGenericClass() { refactoringHelper .addInputLines( "UnorderedRuleChainWithGenericClass.java", "package orderedrulechainwithgenericclass;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithGenericClass {", "public final Rule5<Rule2> varRule52 = new Rule5();", "public final Rule6<Rule3, Rule2> varRule532 = new Rule6();", "@Rule", "// BUG: Diagnostic contains: Do not use RuleChain", "public final RuleChain ruleChain = RuleChain.outerRule(varRule52).around(varRule532);", customRuleClasses(), "}") .addOutputLines( "UnorderedRuleChainWithGenericClass.java", "package orderedrulechainwithgenericclass;", "import org.junit.Rule;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithGenericClass {", "public final Rule5<Rule2> varRule52 = new Rule5();", "public final Rule6<Rule3, Rule2> varRule532 = new Rule6();", "@Rule(order = 0)", "public final Rule5<Rule2> testRuleRule5Rule2 = varRule52;", "@Rule(order = 1)", "public final Rule6<Rule3, Rule2> testRuleRule6Rule3Rule2 = varRule532;", customRuleClasses(), "}") .doTest(); } @Test public void refactoringUnorderedTwoRuleChainWithClassRule() { refactoringHelper .addInputLines( "UnorderedRuleChainWithClassRule.java", "package orderedrulechainwithclassrule;", "import org.junit.ClassRule;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithClassRule {", "@Rule", "// BUG: Diagnostic contains: Do not use RuleChain", "public final RuleChain ruleChain = RuleChain.outerRule(", "new Rule2()).around(new Rule3());", "@ClassRule", "// BUG: Diagnostic contains: Do not use RuleChain", "public static final RuleChain classRuleChain = RuleChain.outerRule(new Rule4());", customRuleClasses(), "}") .addOutputLines( "UnorderedRuleChainWithClassRule.java", "package orderedrulechainwithclassrule;", "import org.junit.ClassRule;", "import org.junit.Rule;", "import org.junit.rules.TestRule;", "import org.junit.runner.Description;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithClassRule {", "@Rule(order = 0)", "public final Rule2 testRuleRule2 = new Rule2();", "@Rule(order = 1)", "public final Rule3 testRuleRule3 = new Rule3();", "@ClassRule(order = 0)", "public static final Rule4 testRuleRule4 = new Rule4();", customRuleClasses(), "}") .doTest(); } @Test public void refactoringUnorderedRuleChainWithoutTestRuleImport() { refactoringHelper .addInputLines( "UnorderedRuleChainWithoutTestRuleImport.java", "package orderedrulechainwithouttestruleimport;", "import org.junit.Rule;", "import org.junit.rules.RuleChain;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithoutTestRuleImport {", "@Rule", "// BUG: Diagnostic contains: Do not use RuleChain", "public final RuleChain ruleChain = RuleChain.outerRule((base, description) ->", "new Statement() {", "@Override", "public void evaluate() throws Throwable {", "// Do nothing", "}", "});", "}") .addOutputLines( "UnorderedRuleChainWithoutTestRuleImport.java", "package orderedrulechainwithouttestruleimport;", "import org.junit.Rule;", "import org.junit.rules.TestRule;", "import org.junit.runners.model.Statement;", "public class UnorderedRuleChainWithoutTestRuleImport {", "@Rule(order = 0)", "public final TestRule testRuleTestRule =", "(base, description) ->", "new Statement() {", "@Override", "public void evaluate() throws Throwable {", "// Do nothing", "}", "};", "}") .doTest(); } private static String customRuleClasses() { return "private class BaseCustomRule implements TestRule {\n" + "@Override\n" + "public Statement apply(Statement base, Description description) {\n" + "return new Statement() {\n" + "@Override\n" + "public void evaluate() throws Throwable {\n" + "// Do nothing\n" + "}\n" + "};\n" + "}\n" + "}\n" + "private class Rule1 extends BaseCustomRule {\n" + "private Rule1(String unusedString, TestRule unusedRule) {\n" + " // Example with parameter\n" + "}\n" + "}\n" + "private class Rule2 extends BaseCustomRule {}\n" + "private class Rule3 extends BaseCustomRule {}\n" + "private static class Rule4 implements TestRule {\n" + "@Override\n" + "public Statement apply(Statement base, Description description) {\n" + "return new Statement() {\n" + "@Override\n" + "public void evaluate() throws Throwable {\n" + "// Do nothing\n" + "}\n" + "};\n" + "}\n" + "}\n" + "private class Rule5<T extends TestRule> extends BaseCustomRule {}\n" + "private class Rule6<T extends TestRule, V extends TestRule> extends BaseCustomRule {}\n"; } }
19,574
37.685771
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ShouldHaveEvenArgsTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link ShouldHaveEvenArgs} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class ShouldHaveEvenArgsTest { CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(ShouldHaveEvenArgs.class, getClass()); } @Test public void positiveCase() { compilationHelper.addSourceFile("ShouldHaveEvenArgsPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("ShouldHaveEvenArgsNegativeCases.java").doTest(); } @org.junit.Ignore("Public truth doesn't contain this method") @Test public void positiveCase_multimap() { compilationHelper.addSourceFile("ShouldHaveEvenArgsMultimapPositiveCases.java").doTest(); } @org.junit.Ignore("Public truth doesn't contain this method") @Test public void negativeCase_multimap() { compilationHelper.addSourceFile("ShouldHaveEvenArgsMultimapNegativeCases.java").doTest(); } }
1,861
29.52459
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnusedCollectionModifiedInPlaceTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link UnusedCollectionModifiedInPlace}Test */ @RunWith(JUnit4.class) public class UnusedCollectionModifiedInPlaceTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnusedCollectionModifiedInPlace.class, getClass()); @Test public void collectionsMethodCoverage() { compilationHelper .addSourceLines( "Test.java", "import java.util.Collections;", "import java.util.ArrayList;", "import java.util.List;", "class Test {", " void doIt(List<String> myList) {", " // BUG: Diagnostic contains:", " Collections.copy(new ArrayList<>(myList), null);", " // BUG: Diagnostic contains:", " Collections.fill(new ArrayList<>(myList), null);", " // BUG: Diagnostic contains:", " Collections.reverse(new ArrayList<>(myList));", " // BUG: Diagnostic contains:", " Collections.rotate(new ArrayList<>(myList), 5);", " // BUG: Diagnostic contains:", " Collections.shuffle(new ArrayList<>(myList));", " // BUG: Diagnostic contains:", " Collections.shuffle(new ArrayList<>(myList), null);", " // BUG: Diagnostic contains:", " Collections.sort(new ArrayList<>(myList));", " // BUG: Diagnostic contains:", " Collections.sort(new ArrayList<>(myList), null);", " // BUG: Diagnostic contains:", " Collections.swap(new ArrayList<>(myList), 1, 2);", " }", "}") .doTest(); } @Test public void listsNewArrayList() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.Lists;", "import java.util.Collections;", "import java.util.List;", "class Test {", " void doIt(List<String> myList) {", " // BUG: Diagnostic contains:", " Collections.sort(Lists.newArrayList(myList));", " // BUG: Diagnostic contains:", " Collections.sort(Lists.newArrayList(myList), null);", " }", "}") .doTest(); } @Test public void listsNewLinkedList() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.collect.Lists;", "import java.util.Collections;", "import java.util.List;", "class Test {", " void doIt(List<String> myList) {", " // BUG: Diagnostic contains:", " Collections.sort(Lists.newLinkedList(myList));", " // BUG: Diagnostic contains:", " Collections.sort(Lists.newLinkedList(myList), null);", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import java.util.Collections;", "import java.util.List;", "class Test {", " void doIt(List<String> myList) {", " Collections.sort(myList);", " }", "}") .doTest(); } }
4,119
34.213675
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/MissingDefaultTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import static org.junit.Assume.assumeTrue; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link MissingDefault}Test */ @RunWith(JUnit4.class) public class MissingDefaultTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(MissingDefault.class, getClass()); @Test public void positive() { BugCheckerRefactoringTestHelper.newInstance(MissingDefault.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " boolean f(int i) {", " // BUG: Diagnostic contains:", " switch (i) {", " case 42:", " return true;", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " boolean f(int i) {", " // BUG: Diagnostic contains:", " switch (i) {", " case 42:", " return true;", " default: // fall out", " }", " return false;", " }", "}") .doTest(TEXT_MATCH); } @Test public void positiveBreak() { BugCheckerRefactoringTestHelper.newInstance(MissingDefault.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " void f(int i) {", " // BUG: Diagnostic contains:", " switch (i) {", " case 42:", " System.err.println(42);", " }", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " void f(int i) {", " // BUG: Diagnostic contains:", " switch (i) {", " case 42:", " System.err.println(42);", " break;", " default: // fall out", " }", " }", "}") .doTest(TEXT_MATCH); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "class Test {", " boolean f(int i) {", " switch (i) {", " case 42:", " return true;", " default:", " return false;", " }", " }", "}") .doTest(); } @Test public void enumSwitch() { compilationHelper .addSourceLines( "Test.java", "class Test {", " enum E { ONE, TWO }", " boolean f(E e) {", " switch (e) {", " case ONE:", " return true;", " }", " return false;", " }", "}") .doTest(); } @Test public void empty() { compilationHelper .addSourceLines( "Test.java", "class Test {", " boolean f(int i) {", " switch (i) {", " case 42:", " return true;", " default: // fall out", " }", " return false;", " }", "}") .doTest(); } @Test public void emptyNoComment() { BugCheckerRefactoringTestHelper.newInstance(MissingDefault.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " boolean f(int i) {", " switch (i) {", " case 42:", " return true;", " default:", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " boolean f(int i) {", " switch (i) {", " case 42:", " return true;", " default: // fall out", " }", " return false;", " }", "}") .doTest(TEXT_MATCH); } @Test public void interiorEmptyNoComment() { compilationHelper .addSourceLines( "Test.java", "class Test {", " boolean f(int i) {", " switch (i) {", " default:", " case 42:", " return true;", " }", " }", "}") .doTest(); } @Test public void multipleStatementsInGroup() { BugCheckerRefactoringTestHelper.newInstance(MissingDefault.class, getClass()) .addInputLines( "in/Test.java", "class Test {", " boolean f(int i) {", " // BUG: Diagnostic contains:", " switch (i) {", " case 42:", " System.err.println();", " return true;", " }", " return false;", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " boolean f(int i) {", " // BUG: Diagnostic contains:", " switch (i) {", " case 42:", " System.err.println();", " return true;", " default: // fall out", " }", " return false;", " }", "}") .doTest(TEXT_MATCH); } @Test public void arrowSwitch() { assumeTrue(RuntimeVersion.isAtLeast14()); compilationHelper .addSourceLines( "Test.java", "class Test {", " void m(int i) {", " // BUG: Diagnostic contains:", " switch (i) {", " case 1 -> {}", " case 2 -> {}", " }", " }", "}") .doTest(); } @Test public void arrowSwitchNegative() { assumeTrue(RuntimeVersion.isAtLeast14()); compilationHelper .addSourceLines( "Test.java", "class Test {", " void m(int i) {", " switch (i) {", " case 1 -> {}", " case 2 -> {}", " default -> {} // fall out", " }", " }", "}") .doTest(); } }
7,448
26.898876
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnsafeReflectiveConstructionCastTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link UnsafeReflectiveConstructionCast} bug pattern. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class UnsafeReflectiveConstructionCastTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance( UnsafeReflectiveConstructionCast.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnsafeReflectiveConstructionCast.class, getClass()); @Test public void positiveCase() { testHelper .addInputLines( "in/Test.java", "class Test {", " private String newInstanceOnGetDeclaredConstructorChained() throws Exception {", " return (String) ", " Class.forName(\"java.lang.String\").getDeclaredConstructor().newInstance();", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " private String newInstanceOnGetDeclaredConstructorChained() throws Exception {", " return Class.forName(\"java.lang.String\")", " .asSubclass(String.class).getDeclaredConstructor().newInstance();", " }", "}") .doTest(); } @Test public void positiveCaseConstructor() { testHelper .addInputLines( "in/Test.java", "class Test {", " private String newInstanceOnGetConstructorChained() throws Exception {", " return (String) ", " Class.forName(\"java.lang.String\").getConstructor().newInstance();", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " private String newInstanceOnGetConstructorChained() throws Exception {", " return Class.forName(\"java.lang.String\")", " .asSubclass(String.class).getConstructor().newInstance();", " }", "}") .doTest(); } @Test public void positiveCaseWithErasure() { testHelper .addInputLines( "in/Test.java", "class Test {", " class Fn<T> {};", " private Fn<String> newInstanceOnGetDeclaredConstructorChained() throws Exception {", " return (Fn<String>) Class.forName(\"Fn\").getDeclaredConstructor().newInstance();", " }", "}") .addOutputLines( "out/Test.java", "class Test {", " class Fn<T> {};", " private Fn<String> newInstanceOnGetDeclaredConstructorChained() throws Exception {", " return (Fn<String>) Class.forName(\"Fn\")", " .asSubclass(Fn.class).getDeclaredConstructor().newInstance();", " }", "}") .doTest(); } @Test public void negativeCaseWithIntersection() { compilationHelper .addSourceLines( "in/Test.java", "import java.io.Serializable;", "class Test {", " interface Fn {};", " private Fn newInstanceOnGetDeclaredConstructorChained() throws Exception {", " return (Serializable & Fn) ", " Class.forName(\"Fn\").getDeclaredConstructor().newInstance();", " }", "}") .doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("UnsafeReflectiveConstructionCastNegativeCases.java").doTest(); } }
4,444
34.277778
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/SwigMemoryLeakTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author irogers@google.com (Ian Rogers) */ @RunWith(JUnit4.class) public class SwigMemoryLeakTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(SwigMemoryLeak.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("SwigMemoryLeakPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("SwigMemoryLeakNegativeCases.java").doTest(); } }
1,291
29.046512
81
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ForEachIterableTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ForEachIterable}Test */ @RunWith(JUnit4.class) public class ForEachIterableTest { @Test public void positive() { BugCheckerRefactoringTestHelper.newInstance(ForEachIterable.class, getClass()) .addInputLines( "in/Test.java", "import java.util.Iterator;", "abstract class Test<T> {", " abstract void doSomething(T element);", " void iteratorFor(Iterable<T> list) {", " for (Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) {", " doSomething(iterator.next());", " }", " }", " void iteratorWhile(Iterable<T> list) {", " Iterator<T> iterator = list.iterator();", " while (iterator.hasNext()) {", " doSomething(iterator.next());", " }", " }", "}") .addOutputLines( "out/Test.java", "import java.util.Iterator;", "abstract class Test<T> {", " abstract void doSomething(T element);", " void iteratorFor(Iterable<T> list) {", " for (T element : list) {", " doSomething(element);", " }", " }", " void iteratorWhile(Iterable<T> list) {", " for (T element : list) {", " doSomething(element);", " }", " }", "}") .doTest(); } @Test public void reuseVariable() { BugCheckerRefactoringTestHelper.newInstance(ForEachIterable.class, getClass()) .addInputLines( "in/Test.java", "import java.util.Iterator;", "abstract class Test<T> {", " abstract void doSomething(T element);", " void iteratorWhile(Iterable<T> list) {", " Iterator<T> iterator = list.iterator();", " while (iterator.hasNext()) {", " T t = iterator.next();", " doSomething(t);", " }", " }", "}") .addOutputLines( "out/Test.java", "import java.util.Iterator;", "abstract class Test<T> {", " abstract void doSomething(T element);", " void iteratorWhile(Iterable<T> list) {", " for (T t : list) {", " doSomething(t);", " }", " }", "}") .doTest(); } @Test public void wildcard() { BugCheckerRefactoringTestHelper.newInstance(ForEachIterable.class, getClass()) .addInputLines( "in/Test.java", "import java.util.Iterator;", "abstract class Test {", " abstract void doSomething(Object element);", " void iteratorWhile(Iterable<?> list) {", " Iterator<?> iterator = list.iterator();", " while (iterator.hasNext()) {", " doSomething(iterator.next());", " }", " }", "}") .addOutputLines( "out/Test.java", "import java.util.Iterator;", "abstract class Test {", " abstract void doSomething(Object element);", " void iteratorWhile(Iterable<?> list) {", " for (Object element : list) {", " doSomething(element);", " }", " }", "}") .doTest(); } @Test public void empty() { BugCheckerRefactoringTestHelper.newInstance(ForEachIterable.class, getClass()) .addInputLines( "in/Test.java", "import java.util.Iterator;", "abstract class Test {", " abstract void doSomething(Object element);", " void iteratorWhile(Iterable<?> list) {", " Iterator<?> iterator = list.iterator();", " while (iterator.hasNext()) {", " iterator.next();", " }", " }", "}") .addOutputLines( "out/Test.java", "import java.util.Iterator;", "abstract class Test {", " abstract void doSomething(Object element);", " void iteratorWhile(Iterable<?> list) {", " for (Object element : list) {", " }", " }", "}") .doTest(); } @Test public void wildcardExtends() { BugCheckerRefactoringTestHelper.newInstance(ForEachIterable.class, getClass()) .addInputLines( "in/Test.java", "import java.util.Iterator;", "abstract class Test {", " abstract void doSomething(String element);", " void iteratorWhile(Iterable<? extends String> list) {", " Iterator<? extends String> iterator = list.iterator();", " while (iterator.hasNext()) {", " iterator.next();", " }", " }", "}") .addOutputLines( "out/Test.java", "import java.util.Iterator;", "abstract class Test {", " abstract void doSomething(String element);", " void iteratorWhile(Iterable<? extends String> list) {", " for (String element : list) {", " }", " }", "}") .doTest(); } @Test public void iteratorMemberMethod() { BugCheckerRefactoringTestHelper.newInstance(ForEachIterable.class, getClass()) .addInputLines( "in/Test.java", "import java.util.Iterator;", "import java.lang.Iterable;", "class Test<V> implements Iterable<V> {", " @Override", " public Iterator<V> iterator() {", " return null;", " }", " void test() {", " Iterator<V> iter = iterator();", " while (iter.hasNext()) {", " iter.next();", " }", " }", "}") .addOutputLines( "out/Test.java", "import java.util.Iterator;", "import java.lang.Iterable;", "class Test<V> implements Iterable<V> {", " @Override", " public Iterator<V> iterator() {", " return null;", " }", " void test() {", " for (V element : this) {", " }", " }", "}") .doTest(); } @Test public void negative() { CompilationTestHelper.newInstance(ForEachIterable.class, getClass()) .addSourceLines( "in/Test.java", "import java.util.Iterator;", "abstract class Test<T> {", " abstract void doSomething(T element);", " void forUpdate(Iterable<T> list) {", " for (Iterator<T> it = list.iterator(); it.hasNext(); it.next()) {", " doSomething(it.next());", " }", " }", " void forMultiVariable(Iterable<T> list) {", " for (Iterator<T> iterator = list.iterator(), y = null; iterator.hasNext(); ) {", " doSomething(iterator.next());", " }", " }", " void forTwoStep(Iterable<T> list) {", " for (Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) {", " doSomething(iterator.next());", " doSomething(iterator.next());", " }", " }", " void whileTwoStep(Iterable<T> list) {", " Iterator<T> iterator = list.iterator();", " while (iterator.hasNext()) {", " doSomething(iterator.next());", " doSomething(iterator.next());", " }", " }", " void whileUseOutsideLoop(Iterable<T> list) {", " Iterator<T> iterator = list.iterator();", " while (iterator.hasNext()) {", " doSomething(iterator.next());", " }", " doSomething(iterator.next());", " }", " void forIteratorUse(Iterable<?> list) {", " Iterator<?> iterator = list.iterator();", " while (iterator.hasNext()) {", " iterator.next();", " iterator.remove();", " }", " }", "}") .doTest(); } }
9,443
34.238806
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/InputStreamSlowMultibyteReadTest.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class InputStreamSlowMultibyteReadTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InputStreamSlowMultibyteRead.class, getClass()); @Test public void doingItRight() { compilationHelper .addSourceLines( "TestClass.java", "class TestClass extends java.io.InputStream {", " byte[] buf = new byte[42];", " public int read(byte[] b, int a, int c) { return 0; }", " public int read() { return buf[0]; }", "}") .doTest(); } @Test public void basic() { compilationHelper .addSourceLines( "TestClass.java", "class TestClass extends java.io.InputStream {", " byte[] buf = new byte[42];", " // BUG: Diagnostic contains:", " public int read() { return buf[0]; }", "}") .doTest(); } @Test public void abstractOverride() { compilationHelper .addSourceLines( "TestClass.java", "abstract class TestClass extends java.io.InputStream {", " // BUG: Diagnostic contains:", " public abstract int read();", "}") .doTest(); } @Test public void nativeOverride() { compilationHelper .addSourceLines( "TestClass.java", "abstract class TestClass extends java.io.InputStream {", " // BUG: Diagnostic contains:", " public native int read();", "}") .doTest(); } @Test public void dummyStreamIgnored() { compilationHelper .addSourceLines( "TestClass.java", "class TestClass extends java.io.InputStream {", " public int read() { return 0; }", "}") .doTest(); } // Here, the superclass still can't effectively multibyte-read without the underlying // read() method. @Test public void inherited() { compilationHelper .addSourceLines( "Super.java", "abstract class Super extends java.io.InputStream {", " public int read(byte[] b, int a, int c) { return 0; }", "}") .addSourceLines( "TestClass.java", "class TestClass extends Super {", " byte[] buf = new byte[42];", " // BUG: Diagnostic contains:", " public int read() { return buf[0]; }", "}") .doTest(); } @Test public void junit3TestIgnored() { compilationHelper .addSourceLines( "javatests/TestClass.java", "class TestClass extends junit.framework.TestCase {", " static class SomeStream extends java.io.InputStream {", " byte[] buf = new byte[42];", " public int read() { return buf[0]; }", "}}") .doTest(); } @Test public void junit4TestIgnored() { compilationHelper .addSourceLines( "javatests/TestClass.java", "@org.junit.runner.RunWith(org.junit.runners.JUnit4.class)", "class TestClass {", " static class SomeStream extends java.io.InputStream {", " byte[] buf = new byte[42];", " public int read() { return buf[0]; }", "}}") .doTest(); } }
4,183
29.318841
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AnnotationMirrorToStringTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link AnnotationMirrorToString}Test */ @RunWith(JUnit4.class) public class AnnotationMirrorToStringTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(AnnotationMirrorToString.class, getClass()); @Test public void refactoring() { testHelper .addInputLines( "Test.java", "import javax.lang.model.element.AnnotationMirror;", "class Test {", " String f(AnnotationMirror av) {", " return av.toString();", " }", "}") .addOutputLines( "Test.java", "import com.google.auto.common.AnnotationMirrors;", "import javax.lang.model.element.AnnotationMirror;", "class Test {", " String f(AnnotationMirror av) {", " return AnnotationMirrors.toString(av);", " }", "}") .allowBreakingChanges() // TODO(cushon): remove after the next auto-common release .doTest(); } }
1,861
32.854545
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/DeadExceptionTest.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author alexeagle@google.com (Alex Eagle) */ @RunWith(JUnit4.class) public class DeadExceptionTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(DeadException.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("DeadExceptionPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("DeadExceptionNegativeCases.java").doTest(); } /** * It's somewhat common to test the side-effects of Exception constructors by creating one, and * asserting that an exception is thrown in the constructor. */ @Test public void negativeCaseWhenExceptionsUnthrownInTests() { compilationHelper.addSourceFile("DeadExceptionTestingNegativeCases.java").doTest(); } }
1,623
30.230769
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OperatorPrecedenceTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link OperatorPrecedence}Test */ @RunWith(JUnit4.class) public class OperatorPrecedenceTest { private final CompilationTestHelper compilationTestHelper = CompilationTestHelper.newInstance(OperatorPrecedence.class, getClass()); private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(OperatorPrecedence.class, getClass()); @Test public void positive() { compilationTestHelper .addSourceLines( "Test.java", "class Test {", " boolean f(boolean a, boolean b, boolean c) {", " // BUG: Diagnostic contains: (a && b) || c", " boolean r = a && b || c;", " // BUG: Diagnostic contains: a || (b && c)", " r = a || b && c;", " // BUG: Diagnostic contains: a || (b && c) || !(b && c)", " r = a || b && c || !(b && c);", " return r;", " }", " int f(int a, int b) {", " // BUG: Diagnostic contains: (a + b) << 2", " return a + b << 2;", " }", "}") .doTest(); } @Test public void negative() { compilationTestHelper .addSourceLines( "Test.java", "class Test {", " int f(int a, int b) {", " int r = a + a * b;", " return r;", " }", " boolean f(boolean a, boolean b) {", " boolean r = (a && b) || (!a && !b);", " r = (a = a && b);", " return r;", " }", "}") .doTest(); } @Test public void positiveNotSpecialParenthesisCase() { helper .addInputLines( "Test.java", "class Test {", " boolean f(boolean a, boolean b, boolean c, boolean d, boolean e) {", " boolean r = a || (b && c) && (d && e);", " return r;", " }", " int f2(int a, int b, int c, int d) {", " int e = a << (b + c) + d;", " return e;", " }", " boolean f3(boolean a, boolean b, boolean c, boolean d, boolean e) {", " boolean r = a || b && c;", " return r;", " }", "}") .addOutputLines( "Test.java", "class Test {", " boolean f(boolean a, boolean b, boolean c, boolean d, boolean e) {", " boolean r = a || ((b && c) && (d && e));", " return r;", " }", " int f2(int a, int b, int c, int d) {", " int e = a << (b + c + d);", " return e;", " }", " boolean f3(boolean a, boolean b, boolean c, boolean d, boolean e) {", " boolean r = a || (b && c);", " return r;", " }", "}") .doTest(); } @Test public void extraParenthesis() { helper .addInputLines( "Test.java", // "class Test {", " void f(boolean a, boolean b, boolean c, boolean d, boolean e) {", " boolean g = (a || (b && c && d) && e);", " }", "}") .addOutputLines( "Test.java", // "class Test {", " void f(boolean a, boolean b, boolean c, boolean d, boolean e) {", " boolean g = (a || (b && c && d && e));", " }", "}") .doTest(); } @Test public void rightAndParenthesis() { helper .addInputLines( "Test.java", // "class Test {", " void f(boolean a, boolean b, boolean c, boolean d) {", " boolean g = a || b && (c && d);", " }", "}") .addOutputLines( "Test.java", // "class Test {", " void f(boolean a, boolean b, boolean c, boolean d) {", " boolean g = a || (b && c && d);", " }", "}") .doTest(); } @Test public void leftAndParenthesis() { helper .addInputLines( "Test.java", // "class Test {", " void f(boolean a, boolean b, boolean c, boolean d) {", " boolean g = a || (b && c) && d;", " }", "}") .addOutputLines( "Test.java", // "class Test {", " void f(boolean a, boolean b, boolean c, boolean d) {", " boolean g = a || (b && c && d);", " }", "}") .doTest(); } @Test public void aLotOfParenthesis() { helper .addInputLines( "Test.java", // "class Test {", " void f(boolean a, boolean b, boolean c, boolean d, boolean e) {", " boolean g = (a || (b && c && d) && e);", " }", "}") .addOutputLines( "Test.java", // "class Test {", " void f(boolean a, boolean b, boolean c, boolean d, boolean e) {", " boolean g = (a || (b && c && d && e));", " }", "}") .doTest(); } }
6,108
30.328205
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NarrowCalculationTest.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link NarrowCalculation}. */ @RunWith(JUnit4.class) public final class NarrowCalculationTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(NarrowCalculation.class, getClass()); private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(NarrowCalculation.class, getClass()); @Test public void integerDivision() { helper .addSourceLines( "Test.java", // "class Test {", " // BUG: Diagnostic contains:", " final float a = 1 / 2;", "}") .doTest(); } @Test public void integerDivision_actuallyInteger() { helper .addSourceLines( "Test.java", // "class Test {", " final float a = 8 / 2;", "}") .doTest(); } @Test public void integerDivision_fix() { refactoring .addInputLines( "Test.java", // "class Test {", " final float a = 1 / 2;", "}") .addOutputLines( "Test.java", // "class Test {", " final float a = 1 / 2f;", "}") .doTest(); } @Test public void longDivision_fix() { refactoring .addInputLines( "Test.java", // "class Test {", " final double a = 1 / 2L;", "}") .addOutputLines( "Test.java", // "class Test {", " final double a = 1 / 2.0;", "}") .doTest(); } @Test public void targetTypeInteger_noFinding() { helper .addSourceLines( "Test.java", // "class Test {", " final int a = 1 / 2;", "}") .doTest(); } @Test public void multiplication_doesNotOverflow() { helper .addSourceLines( "Test.java", // "class Test {", " final long a = 2 * 100;", "}") .doTest(); } @Test public void multiplication_wouldOverflow() { helper .addSourceLines( "Test.java", // "class Test {", " // BUG: Diagnostic contains:", " final long a = 1_000_000_000 * 1_000_000_000;", "}") .doTest(); } @Test public void multiplication_couldOverflow() { helper .addSourceLines( "Test.java", // "class Test {", " void t(int a) {", " // BUG: Diagnostic contains: 2L * a", " long b = 2 * a;", " }", "}") .doTest(); } }
3,545
24.883212
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/OptionalMapToOptionalTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link OptionalMapToOptional} bugpattern. */ @RunWith(JUnit4.class) public final class OptionalMapToOptionalTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(OptionalMapToOptional.class, getClass()); @Test public void positiveWithJavaOptional() { helper .addSourceLines( "Test.java", "import java.util.Optional;", "class Test {", " public boolean test(Optional<Integer> optional) {", " // BUG: Diagnostic contains:", " return optional.map(i -> Optional.of(1)).isPresent();", " }", "}") .doTest(); } @Test public void positiveWithGuavaOptional() { helper .addSourceLines( "Test.java", "import com.google.common.base.Optional;", "class Test {", " public boolean test(Optional<Integer> optional) {", " // BUG: Diagnostic contains:", " return optional.transform(i -> Optional.of(1)).isPresent();", " }", "}") .doTest(); } @Test public void positiveReturned() { helper .addSourceLines( "Test.java", "import com.google.common.base.Optional;", "class Test {", " public Optional<Optional<Integer>> test(Optional<Integer> optional) {", " // BUG: Diagnostic contains:", " return optional.transform(i -> Optional.of(1));", " }", "}") .doTest(); } @Test public void negativeFlatMap() { helper .addSourceLines( "Test.java", "import java.util.Optional;", "class Test {", " public Optional<Integer> test(Optional<Integer> optional) {", " return optional.flatMap(i -> Optional.of(1));", " }", "}") .doTest(); } @Test public void negativeNotToOptional() { helper .addSourceLines( "Test.java", "import java.util.Optional;", "class Test {", " public Optional<Integer> test(Optional<Integer> optional) {", " return optional.map(i -> 1);", " }", "}") .doTest(); } @Test public void rawOptional() { helper .addSourceLines( "Test.java", "import java.util.Optional;", "class Test {", " public Optional<Integer> test(Optional optional) {", " return optional.map(i -> 1);", " }", "}") .doTest(); } }
3,458
29.078261
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ArrayHashCodeTest.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class ArrayHashCodeTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ArrayHashCode.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("ArrayHashCodePositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("ArrayHashCodeNegativeCases.java").doTest(); } /** Tests java.util.Objects hashCode methods, which are only in JDK 7 and above. */ @Test public void java7NegativeCase() { compilationHelper.addSourceFile("ArrayHashCodeNegativeCases2.java").doTest(); } }
1,510
29.836735
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ObjectsHashCodePrimitiveTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link ObjectsHashCodePrimitive}. */ @RunWith(JUnit4.class) public class ObjectsHashCodePrimitiveTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(ObjectsHashCodePrimitive.class, getClass()); @Test public void hashCodeIntLiteral() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " int y = Objects.hashCode(3);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " int y = Integer.hashCode(3);", " }", "}") .doTest(); } @Test public void hashCodeByte() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " byte x = 3;", " int y = Objects.hashCode(x);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " byte x = 3;", " int y = Byte.hashCode(x);", " }", "}") .doTest(); } @Test public void hashCodeShort() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " short x = 3;", " int y = Objects.hashCode(x);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " short x = 3;", " int y = Short.hashCode(x);", " }", "}") .doTest(); } @Test public void hashCodeInt() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " int x = 3;", " int y = Objects.hashCode(x);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " int x = 3;", " int y = Integer.hashCode(x);", " }", "}") .doTest(); } @Test public void hashCodeLong() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " long x = 3;", " int y = Objects.hashCode(x);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " long x = 3;", " int y = Long.hashCode(x);", " }", "}") .doTest(); } @Test public void hashCodeFloat() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " float x = 3;", " int y = Objects.hashCode(x);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " float x = 3;", " int y = Float.hashCode(x);", " }", "}") .doTest(); } @Test public void hashCodeDouble() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " double x = 3;", " int y = Objects.hashCode(x);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " double x = 3;", " int y = Double.hashCode(x);", " }", "}") .doTest(); } @Test public void hashCodeChar() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " char x = 'C';", " int y = Objects.hashCode(x);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " char x = 'C';", " int y = Character.hashCode(x);", " }", "}") .doTest(); } @Test public void hashCodeBoolean() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " boolean x = true;", " int y = Objects.hashCode(x);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " void f() {", " boolean x = true;", " int y = Boolean.hashCode(x);", " }", "}") .doTest(); } @Test public void hashCodeClassVariable() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " boolean x = true;", " void f() {", " int y = Objects.hashCode(x);", " }", "}") .addOutputLines( "Test.java", // "import java.util.Objects;", "class Test {", " boolean x = true;", " void f() {", " int y = Boolean.hashCode(x);", " }", "}") .doTest(); } @Test public void hashCodeObjectNegative() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " Object o = new Object();", " void f() {", " int y = Objects.hashCode(o);", " }", "}") .expectUnchanged() .doTest(); } @Test public void hashCodeBoxedPrimitiveNegative() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " Integer x = Integer.valueOf(3);", " void f() {", " int y = Objects.hashCode(x);", " }", "}") .expectUnchanged() .doTest(); } @Test public void hashCodeOtherMethodNegative() { helper .addInputLines( "Test.java", // "import java.util.Objects;", "class Test {", " Integer x = Integer.valueOf(3);", " void f() {", " int y = x.hashCode();", " }", "}") .expectUnchanged() .doTest(); } }
8,266
25.078864
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ProtoTruthMixedDescriptorsTest.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.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link ProtoTruthMixedDescriptors} bugpattern. * * @author ghm@google.com (Graeme Morgan) */ @RunWith(JUnit4.class) @Ignore("b/130672458") public final class ProtoTruthMixedDescriptorsTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ProtoTruthMixedDescriptors.class, getClass()); @Test public void positive() { 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() {", " assertThat(TestFieldProtoMessage.getDefaultInstance())", " // BUG: Diagnostic contains:", " .ignoringFields(", " TestProtoMessage.MESSAGE_FIELD_NUMBER);", " }", "}") .doTest(); } @Test public void positive_wrongType() { 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() {", " assertThat(TestFieldProtoMessage.getDefaultInstance())", " // BUG: Diagnostic contains:", " .ignoringFields(", " TestProtoMessage.MULTI_FIELD_FIELD_NUMBER,", " TestProtoMessage.MESSAGE_FIELD_NUMBER);", " }", "}") .doTest(); } @Test public void positive_fluentChain() { 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() {", " assertThat(TestFieldProtoMessage.getDefaultInstance())", " .ignoringFields(TestFieldProtoMessage.FIELD_FIELD_NUMBER)", " // BUG: Diagnostic contains:", " .ignoringFields(TestProtoMessage.MESSAGE_FIELD_NUMBER);", " }", "}") .doTest(); } @Test public void negative() { 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;", "import com.google.protobuf.Message;", "final class Test {", " void test() {", " assertThat(TestProtoMessage.getDefaultInstance())", " .ignoringFields(", " TestProtoMessage.MULTI_FIELD_FIELD_NUMBER,", " TestProtoMessage.MESSAGE_FIELD_NUMBER);", " assertThat((Message) TestFieldProtoMessage.getDefaultInstance())", " .ignoringFields(TestProtoMessage.MULTI_FIELD_FIELD_NUMBER);", " }", "}") .doTest(); } }
4,526
38.025862
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ClassNameTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link ClassName}Test */ @RunWith(JUnit4.class) public class ClassNameTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ClassName.class, getClass()); @Test public void twoClasses() { compilationHelper .addSourceLines( "a/A.java", "// BUG: Diagnostic contains: A inside A.java, instead found: One, Two", "package a;", "class One {}", "class Two {}") .doTest(); } @Test public void packageInfo() { compilationHelper .addSourceLines("a/package-info.java", "/** Documentation for our package */", "package a;") .addSourceLines( "b/Test.java", "// BUG: Diagnostic contains: Test inside Test.java, instead found: Green", "package b;", "class Green {}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines("a/A.java", "package a;", "class A {}") .addSourceLines("b/B.java", "package b;", "class B {}") .doTest(); } @Test public void negativeMultipleTopLevel() { compilationHelper .addSourceLines("a/A.java", "package a;", "class A {}") .addSourceLines("b/B.java", "package b;", "class B {}", "class C {}") .doTest(); } @Test public void negativeInnerClass() { compilationHelper .addSourceLines("b/B.java", "package b;", "class B {", " static class Inner {}", "}") .doTest(); } @Test public void negativeInterface() { compilationHelper .addSourceLines("b/B.java", "package b;", "interface B {", " static class Inner {}", "}") .doTest(); } @Test public void negativeEnum() { compilationHelper.addSourceLines("b/B.java", "package b;", "enum B {", " ONE;", "}").doTest(); } @Test public void negativeAnnotation() { compilationHelper .addSourceLines("b/B.java", "package b;", "public @interface B {", "}") .doTest(); } @Test public void negativeIsPublic() { compilationHelper .addSourceLines( "b/B.java", "package b;", "// BUG: Diagnostic contains: should be declared in a file named Test.java", "public class Test {", "}") .matchAllDiagnostics() .doTest(); } @Test public void suppression() { compilationHelper .addSourceLines( "b/Test.java", // "package b;", "@SuppressWarnings(\"ClassName\")", "class Green {}") .doTest(); } }
3,404
27.140496
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NullableConstructorTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link NullableConstructor}Test */ @RunWith(JUnit4.class) public class NullableConstructorTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(NullableConstructor.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "class Test {", " // BUG: Diagnostic contains: Constructors should not be annotated with @Nullable", " @Nullable public Test() {}", "}") .doTest(); } @Test public void negativeNotAnnotated() { compilationHelper .addSourceLines( "Test.java", // "class Test {", " public Test() {}", "}") .doTest(); } @Test public void negativeNotConstructor() { compilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "class Test {", " @Nullable public int f() { return 42; }", "}") .doTest(); } // regression test for #418 @Test public void typeParameter() { compilationHelper .addSourceLines( "Nullable.java", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Retention;", "import java.lang.annotation.RetentionPolicy;", "import java.lang.annotation.Target;", "@Retention(RetentionPolicy.RUNTIME)", "@Target(ElementType.TYPE_USE)", "public @interface Nullable {}") .addSourceLines( "Test.java", // "class Test {", " <@Nullable T> Test(T t) {}", "}") .doTest(); } }
2,599
28.545455
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StringCaseLocaleUsageTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link StringCaseLocaleUsage}. */ @RunWith(JUnit4.class) public final class StringCaseLocaleUsageTest { private final CompilationTestHelper compilationTestHelper = CompilationTestHelper.newInstance(StringCaseLocaleUsage.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringTestHelper = BugCheckerRefactoringTestHelper.newInstance(StringCaseLocaleUsage.class, getClass()); @Test public void identification() { compilationTestHelper .addSourceLines( "A.java", "import static java.util.Locale.ROOT;", "", "import java.util.Locale;", "", "class A {", " void m() {", " \"a\".toLowerCase(Locale.ROOT);", " \"a\".toUpperCase(Locale.ROOT);", " \"b\".toLowerCase(ROOT);", " \"b\".toUpperCase(ROOT);", " \"c\".toLowerCase(Locale.getDefault());", " \"c\".toUpperCase(Locale.getDefault());", " \"d\".toLowerCase(Locale.ENGLISH);", " \"d\".toUpperCase(Locale.ENGLISH);", " \"e\".toLowerCase(new Locale(\"foo\"));", " \"e\".toUpperCase(new Locale(\"foo\"));", "", " // BUG: Diagnostic contains:", " \"f\".toLowerCase();", " // BUG: Diagnostic contains:", " \"g\".toUpperCase();", "", " String h = \"h\";", " // BUG: Diagnostic contains:", " h.toLowerCase();", " String i = \"i\";", " // BUG: Diagnostic contains:", " i.toUpperCase();", " }", "}") .doTest(); } @Test public void replacementFirstSuggestedFix() { refactoringTestHelper .addInputLines( "A.java", "class A {", " void m() {", " \"a\".toLowerCase(/* Comment with parens: (). */ );", " \"b\".toUpperCase();", " \"c\".toLowerCase().toString();", "", " toString().toLowerCase();", " toString().toUpperCase /* Comment with parens: (). */();", "", " this.toString().toLowerCase() /* Comment with parens: (). */;", " this.toString().toUpperCase();", " }", "}") .addOutputLines( "A.java", "import java.util.Locale;", "", "class A {", " void m() {", " \"a\".toLowerCase(/* Comment with parens: (). */ Locale.ROOT);", " \"b\".toUpperCase(Locale.ROOT);", " \"c\".toLowerCase(Locale.ROOT).toString();", "", " toString().toLowerCase(Locale.ROOT);", " toString().toUpperCase /* Comment with parens: (). */(Locale.ROOT);", "", " this.toString().toLowerCase(Locale.ROOT) /* Comment with parens: (). */;", " this.toString().toUpperCase(Locale.ROOT);", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void replacementSecondSuggestedFix() { refactoringTestHelper .setFixChooser(FixChoosers.SECOND) .addInputLines( "A.java", "class A {", " void m() {", " \"a\".toLowerCase();", " \"b\".toUpperCase(/* Comment with parens: (). */ );", " \"c\".toLowerCase().toString();", "", " toString().toLowerCase();", " toString().toUpperCase /* Comment with parens: (). */();", "", " this.toString().toLowerCase() /* Comment with parens: (). */;", " this.toString().toUpperCase();", " }", "}") .addOutputLines( "A.java", "import java.util.Locale;", "", "class A {", " void m() {", " \"a\".toLowerCase(Locale.getDefault());", " \"b\".toUpperCase(/* Comment with parens: (). */ Locale.getDefault());", " \"c\".toLowerCase(Locale.getDefault()).toString();", "", " toString().toLowerCase(Locale.getDefault());", " toString().toUpperCase /* Comment with parens: (). */(Locale.getDefault());", "", " this.toString().toLowerCase(Locale.getDefault()) /* Comment with parens: (). */;", " this.toString().toUpperCase(Locale.getDefault());", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void replacementThirdSuggestedFix() { refactoringTestHelper .setFixChooser(FixChoosers.THIRD) .addInputLines( "A.java", "class A {", " void m() {", " \"a\".toLowerCase();", " \"c\".toLowerCase().toString();", " }", "}") .addOutputLines( "A.java", "import com.google.common.base.Ascii;", "class A {", " void m() {", " Ascii.toLowerCase(\"a\");", " Ascii.toLowerCase(\"c\").toString();", " }", "}") .doTest(); } }
6,367
35.597701
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NonApiTypeTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link NonApiType}. */ @RunWith(JUnit4.class) public final class NonApiTypeTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(NonApiType.class, getClass()) // Indicate that we're compiling "publicly visible code" // See ErrorProneOptions.COMPILING_PUBLICLY_VISIBLE_CODE .setArgs("-XepCompilingPubliclyVisibleCode"); @Test public void listImplementations() { helper .addSourceLines( "Test.java", "public class Test {", " // BUG: Diagnostic contains: java.util.List", " private void test1(java.util.ArrayList value) {}", " // BUG: Diagnostic contains: java.util.List", " private void test1(java.util.LinkedList value) {}", "}") .doTest(); } @Test public void setImplementations() { helper .addSourceLines( "Test.java", "public class Test {", " // BUG: Diagnostic contains: java.util.Set", " private void test1(java.util.HashSet value) {}", " // BUG: Diagnostic contains: java.util.Set", " private void test1(java.util.LinkedHashSet value) {}", " // BUG: Diagnostic contains: java.util.Set", " private void test1(java.util.TreeSet value) {}", "}") .doTest(); } @Test public void mapImplementations() { helper .addSourceLines( "Test.java", "public class Test {", " // BUG: Diagnostic contains: java.util.Map", " private void test1(java.util.HashMap value) {}", " // BUG: Diagnostic contains: java.util.Map", " private void test1(java.util.LinkedHashMap value) {}", " // BUG: Diagnostic contains: java.util.Map", " private void test1(java.util.TreeMap value) {}", "}") .doTest(); } @Test public void guavaOptionals() { helper .addSourceLines( "Test.java", "import com.google.common.base.Optional;", "public class Test {", " // BUG: Diagnostic contains: java.util.Optional", " public Optional<String> middleName() { return Optional.of(\"alfred\"); }", " // BUG: Diagnostic contains: java.util.Optional", " public void setMiddleName(Optional<String> middleName) {}", "}") .doTest(); } @Test public void jdkOptionals() { helper .addSourceLines( "Test.java", "import java.util.Optional;", "public class Test {", " public Optional<String> middleName() { return Optional.of(\"alfred\"); }", " // BUG: Diagnostic contains: Avoid Optional parameters", " public void setMiddleName(Optional<String> middleName) {}", "}") .doTest(); } @Test public void immutableFoos() { helper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableCollection;", "import com.google.common.collect.ImmutableList;", "import com.google.common.collect.ImmutableMap;", "import com.google.common.collect.ImmutableSet;", "public class Test {", // ImmutableFoos as return types are great! " public ImmutableCollection testImmutableCollection() { return null; }", " public ImmutableList testImmutableList() { return null; }", " public ImmutableMap testImmutableMap() { return null; }", " public ImmutableSet testImmutableSet() { return null; }", // ImmutableFoos as method parameters are less great... " // BUG: Diagnostic contains: java.util.Collection", " public void test1(ImmutableCollection<String> values) {}", " // BUG: Diagnostic contains: java.util.List", " public void test2(ImmutableList<String> values) {}", " // BUG: Diagnostic contains: java.util.Map", " public void test3(ImmutableMap<String, String> values) {}", " // BUG: Diagnostic contains: java.util.Set", " public void test4(ImmutableSet<String> values) {}", "}") .doTest(); } @Test public void primitiveArrays() { helper .addSourceLines( "Test.java", "public class Test {", " // BUG: Diagnostic contains: ImmutableIntArray", " public int[] testInts() { return null; }", " // BUG: Diagnostic contains: ImmutableDoubleArray", " public void testDoubles1(double[] values) {}", " // BUG: Diagnostic contains: ImmutableDoubleArray", " public void testDoubles2(Double[] values) {}", "}") .doTest(); } @Test public void protoTime() { helper .addSourceLines( "Test.java", "import com.google.protobuf.Duration;", "import com.google.protobuf.Timestamp;", "public class Test {", " // BUG: Diagnostic contains: java.time.Duration", " public Duration test() { return null; }", " // BUG: Diagnostic contains: java.time.Instant", " public void test(Timestamp timestamp) {}", "}") .doTest(); } @Test public void varargs() { helper .addSourceLines( "Test.java", "import com.google.protobuf.Timestamp;", "public class Test {", // TODO(kak): we should _probably_ flag this too " public void test(Timestamp... timestamps) {}", "}") .doTest(); } @Test public void typeArguments() { helper .addSourceLines( "Test.java", "import com.google.protobuf.Timestamp;", "import java.util.List;", "import java.util.Map;", "public class Test {", " // BUG: Diagnostic contains: java.time.Instant", " public void test1(List<Timestamp> timestamps) {}", " // BUG: Diagnostic contains: java.time.Instant", " public void test2(List<Map<String, Timestamp>> timestamps) {}", "}") .doTest(); } @Test public void nonPublicApisInPublicClassAreNotFlagged() { helper .addSourceLines( "Test.java", "import com.google.protobuf.Timestamp;", "public class Test {", " void test1(Timestamp timestamp) {}", " protected void test2(Timestamp timestamp) {}", " private void test3(Timestamp timestamp) {}", "}") .doTest(); } @Test public void publicApisInNonPublicClassAreNotFlagged() { helper .addSourceLines( "Test.java", "import com.google.protobuf.Timestamp;", "class Test {", " public void test1(Timestamp timestamp) {}", "}") .doTest(); } @Test public void normalApisAreNotFlagged() { helper .addSourceLines( "Test.java", "public class Test {", " public Test(int a) {}", " public int doSomething() { return 42; }", " public void doSomething(int a) {}", "}") .doTest(); } @Test public void streams() { helper .addSourceLines( "Test.java", "import java.util.stream.Stream;", "public class Test {", " // BUG: Diagnostic contains: NonApiType", " public Test(Stream<String> iterator) {}", " // BUG: Diagnostic contains: NonApiType", " public void methodParam(Stream<String> iterator) {}", "}") .doTest(); } @Test public void iterators() { helper .addSourceLines( "Test.java", "import java.util.Iterator;", "public class Test {", " // BUG: Diagnostic contains: NonApiType", " public Iterator<String> returnType() { return null; }", "}") .doTest(); } }
9,017
33.030189
89
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/IterablePathParameterTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link IterablePathParameter}Test */ @RunWith(JUnit4.class) public class IterablePathParameterTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(IterablePathParameter.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "Test.java", "import java.nio.file.Path;", "class Test {", " // BUG: Diagnostic contains: f(Collection<? extends Path> xs)", " void f(Iterable<? extends Path> xs) {}", " // BUG: Diagnostic contains: g(Collection<? super Path> xs)", " void g(Iterable<? super Path> xs) {}", " // BUG: Diagnostic contains: h(Collection<Path> xs)", " void h(Iterable<Path> xs) {}", "}") .doTest(); } @Test public void negative() { testHelper .addSourceLines( "Test.java", "import java.nio.file.Path;", "import java.util.Collection;", "class Test {", " void f(Collection<Path> xs) {}", "}") .doTest(); } @Test public void raw() { testHelper .addSourceLines("Test.java", "class Test {", " void f(Iterable xs) {}", "}") .doTest(); } @Test public void implicitLambda() { testHelper .addSourceLines( "Test.java", "import java.nio.file.Path;", "import java.util.function.Consumer;", "class Test {", " // BUG: Diagnostic contains:", " Consumer<Iterable<Path>> c = (paths) -> {};", "}") .doTest(); } }
2,460
29.382716
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/BadImportTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link BadImport}. */ @RunWith(JUnit4.class) public final class BadImportTest { private final CompilationTestHelper compilationTestHelper = CompilationTestHelper.newInstance(BadImport.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringTestHelper = BugCheckerRefactoringTestHelper.newInstance(BadImport.class, getClass()); @Test public void positive_static_simpleCase() { compilationTestHelper .addSourceLines( "Test.java", "import static com.google.common.collect.ImmutableList.of;", "import com.google.common.collect.ImmutableList;", "class Test {", " // BUG: Diagnostic contains: ImmutableList.of()", " ImmutableList<?> list = of();", "}") .doTest(); } @Test public void positive_identifiers() { compilationTestHelper .addSourceLines( "Test.java", "import static com.google.errorprone.CompilationTestHelper.newInstance;", "import com.google.errorprone.CompilationTestHelper;", "import com.google.errorprone.bugpatterns.BugChecker;", "", "class Test {", " private final CompilationTestHelper compilationTestHelper =", " // BUG: Diagnostic contains: CompilationTestHelper.newInstance", " newInstance(BugChecker.class, getClass());", "}") .doTest(); } @Test public void msg() { compilationTestHelper .addSourceLines( "Test.java", "import static com.google.common.collect.ImmutableList.of;", "import com.google.common.collect.ImmutableList;", "class Test {", " // BUG: Diagnostic contains: qualified class: ImmutableList", " ImmutableList<?> list = of();", "}") .doTest(); } @Test public void positive_static_differentOverloadsInvoked() { compilationTestHelper .addSourceLines( "Test.java", "import static com.google.common.collect.ImmutableList.of;", "import com.google.common.collect.ImmutableList;", "class Test {", " // BUG: Diagnostic contains: " + "ImmutableList.of(ImmutableList.of(1, 2, 3), ImmutableList.of())", " ImmutableList<?> list = of(of(1, 2, 3), of());", "}") .doTest(); } @Test public void positive_static_locallyDefinedMethod() { refactoringTestHelper .addInputLines( "in/Test.java", "import static com.google.common.collect.ImmutableList.of;", "import com.google.common.collect.ImmutableList;", "class Test {", " class Blah {", " Blah() {", " of(); // Left unchanged, because this is invoking Test.Blah.of.", " }", " void of() {}", " }", " ImmutableList<?> list = of();", "}") .addOutputLines( "out/Test.java", "import static com.google.common.collect.ImmutableList.of;", "import com.google.common.collect.ImmutableList;", "class Test {", " class Blah {", " Blah() {", " of(); // Left unchanged, because this is invoking Test.Blah.of.", " }", " void of() {}", " }", " ImmutableList<?> list = ImmutableList.of();", "}") .doTest(); } @Test public void negative_static_noStaticImport() { compilationTestHelper .addSourceLines( "in/Test.java", "class Test {", " void of() {}", " void foo() {", " of();", " }", "}") .doTest(); } @Test public void positive_nested() { compilationTestHelper.addSourceFile("BadImportPositiveCases.java").doTest(); } @Test public void positive_nested_parentNotAlreadyImported() { compilationTestHelper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList.Builder;", "class Test {", " // BUG: Diagnostic contains: ImmutableList.Builder<String> builder = null;", " Builder<String> builder = null;", "}") .doTest(); } @Test public void positive_nested_conflictingName() { compilationTestHelper .addSourceLines( "thing/A.java", "package thing;", "public class A {", " public static class B {", " public static class Builder {", " }", " }", "}") .addSourceLines( "Test.java", "import thing.A.B.Builder;", "class Test {", " // BUG: Diagnostic contains: A.B.Builder builder;", " Builder builder;", " static class B {}", "}") .doTest(); } @Test public void positive_nested_conflictingNames_fullyQualified() { compilationTestHelper .addSourceLines( "thing/A.java", "package thing;", "public class A {", " public static class B {", " public static class Builder {", " }", " }", "}") .addSourceLines( "Test.java", "import thing.A.B.Builder;", "class Test {", " // BUG: Diagnostic contains: thing.A.B.Builder builder", " Builder builder;", " static class A {}", " static class B {}", "}") .doTest(); } @Test public void negative_nested() { compilationTestHelper.addSourceFile("BadImportNegativeCases.java").doTest(); } @Test public void negative_badImportIsTopLevelClass() { compilationTestHelper .addSourceLines( "thing/thang/Builder.java", // Avoid rewrapping onto single line. "package thing.thang;", "public class Builder {}") .addSourceLines( "Test.java", // Avoid rewrapping onto single line. "import thing.thang.Builder;", "class Test {", " Builder builder;", "}") .doTest(); } @Test public void nestedFixes() { refactoringTestHelper .addInput("BadImportPositiveCases.java") .addOutput("BadImportPositiveCases_expected.java") .doTest(TestMode.AST_MATCH); } @Test public void nestedTypeUseAnnotation() { refactoringTestHelper .addInputLines( "input/TypeUseAnnotation.java", "package test;", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Target;", "@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})", "@interface TypeUseAnnotation {}") .expectUnchanged() .addInputLines( "input/SomeClass.java", "package test;", "class SomeClass {", " static class Builder {}", "}") .expectUnchanged() .addInputLines( "input/Test.java", "package test;", "import java.util.List;", "import test.SomeClass.Builder;", "abstract class Test {", " @TypeUseAnnotation Builder builder;", " @TypeUseAnnotation abstract Builder method1();", " abstract @TypeUseAnnotation Builder method2();", " abstract void method3(@TypeUseAnnotation Builder builder);", " abstract void method4(List<@TypeUseAnnotation Builder> builder);", "}") .addOutputLines( "output/Test.java", "package test;", "import java.util.List;", "abstract class Test {", " SomeClass.@TypeUseAnnotation Builder builder;", " abstract SomeClass.@TypeUseAnnotation Builder method1();", " abstract SomeClass.@TypeUseAnnotation Builder method2();", " abstract void method3(SomeClass.@TypeUseAnnotation Builder builder);", " abstract void method4(List<SomeClass.@TypeUseAnnotation Builder> builder);", "}") .doTest(); } @Test public void suppressed_class() { compilationTestHelper .addSourceLines( "Test.java", "import static com.google.common.collect.ImmutableList.of;", "import com.google.common.collect.ImmutableList;", "@SuppressWarnings(\"BadImport\")", "class Test {", " ImmutableList<?> list = of();", " ImmutableList<?> list2 = of();", "}") .doTest(); } @Test public void suppressed_field() { compilationTestHelper .addSourceLines( "Test.java", "import static com.google.common.collect.ImmutableList.of;", "import com.google.common.collect.ImmutableList;", "class Test {", " @SuppressWarnings(\"BadImport\")", " ImmutableList<?> list = of();", "", " // BUG: Diagnostic contains: ImmutableList.of()", " ImmutableList<?> list2 = of();", "}") .doTest(); } @Test public void suppressed_method() { compilationTestHelper .addSourceLines( "Test.java", "import static com.google.common.collect.ImmutableList.of;", "import com.google.common.collect.ImmutableList;", "class Test {", " @SuppressWarnings(\"BadImport\")", " void foo() {", " ImmutableList<?> list = of();", " }", " void bar() {", " // BUG: Diagnostic contains: ImmutableList.of()", " ImmutableList<?> list2 = of();", " }", "}") .doTest(); } @Test public void enumWithinSameCompilationUnitImported_noFinding() { compilationTestHelper .addSourceLines( "Test.java", // "package pkg;", "import pkg.Test.Type;", "class Test {", " enum Type {", " A,", " B;", " }", "}") .doTest(); } @Test public void enumWithinDifferentCompilationUnitImported_finding() { refactoringTestHelper .addInputLines( "E.java", // "package a;", "public enum E {", " INSTANCE;", "}") .expectUnchanged() .addInputLines( "Test.java", // "package pkg;", "import static a.E.INSTANCE;", "class Test {", " Object e = INSTANCE;", "}") .addOutputLines( "Test.java", // "package pkg;", "import static a.E.INSTANCE;", "import a.E;", "class Test {", " Object e = E.INSTANCE;", "}") .doTest(); } @Test public void doesNotMatchProtos() { compilationTestHelper .addSourceLines( "ProtoOuterClass.java", "package pkg;", "import com.google.protobuf.MessageLite;", "public class ProtoOuterClass {", " public static abstract class Provider implements MessageLite {}", "}") .addSourceLines( "Test.java", "import pkg.ProtoOuterClass.Provider;", "class Test {", " public void test(Provider p) {}", "}") .doTest(); } }
12,701
31.403061
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/ThreadJoinLoopTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author mariasam@google.com (Maria Sam) on 7/10/17. */ @RunWith(JUnit4.class) public class ThreadJoinLoopTest { private static CompilationTestHelper compilationTestHelper; @Before public void setup() { compilationTestHelper = CompilationTestHelper.newInstance(ThreadJoinLoop.class, getClass()); } @Test public void positiveCases() { compilationTestHelper.addSourceFile("ThreadJoinLoopPositiveCases.java").doTest(); } @Test public void negativeCases() { compilationTestHelper.addSourceFile("ThreadJoinLoopNegativeCases.java").doTest(); } @Test public void fixes() { BugCheckerRefactoringTestHelper.newInstance(ThreadJoinLoop.class, getClass()) .addInput("ThreadJoinLoopPositiveCases.java") .addOutput("ThreadJoinLoopPositiveCases_expected.java") .doTest(TestMode.AST_MATCH); } }
1,809
30.754386
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RestrictedApiCheckerTest.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import com.sun.tools.javac.main.Main.Result; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit test for {@link RestrictedApiChecker} */ @RunWith(JUnit4.class) public class RestrictedApiCheckerTest { private final CompilationTestHelper helper; private final BugCheckerRefactoringTestHelper refactoringTest; public RestrictedApiCheckerTest() { this(RestrictedApiChecker.class); } protected RestrictedApiCheckerTest(Class<? extends BugChecker> checker) { helper = CompilationTestHelper.newInstance(checker, RestrictedApiCheckerTest.class) .addSourceFile("Allowlist.java") .addSourceFile("RestrictedApiMethods.java") .matchAllDiagnostics(); refactoringTest = BugCheckerRefactoringTestHelper.newInstance(checker, RestrictedApiCheckerTest.class); } @Test public void normalCallAllowed() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " void foo(RestrictedApiMethods m) {", " m.normalMethod();", " m.accept(m::normalMethod);", " }", "}") .doTest(); } @Test public void restrictedCallProhibited() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " void foo(RestrictedApiMethods m) {", " // BUG: Diagnostic contains: lorem", " m.restrictedMethod();", " // BUG: Diagnostic contains: lorem", " m.accept(m::restrictedMethod);", " }", "}") .expectResult(Result.ERROR) .doTest(); } @Test public void restrictedCallProhibited_inherited() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " void foo(RestrictedApiMethods.Subclass m) {", " // BUG: Diagnostic contains: lorem", " m.restrictedMethod();", " // BUG: Diagnostic contains: ipsum", " m.dontCallMe();", " // BUG: Diagnostic contains: lorem", " m.accept(m::restrictedMethod);", " // BUG: Diagnostic contains: ipsum", " m.accept(m::dontCallMe);", " }", "}") .expectResult(Result.ERROR) .doTest(); } @Test public void restrictedCallAllowedOnAllowlistedPath() { helper .addSourceLines( "testsuite/Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " void foo(RestrictedApiMethods m) {", " m.restrictedMethod();", " m.accept(m::restrictedMethod);", " }", "}") .expectResult(Result.OK) .doTest(); } @Test public void restrictedStaticCallProhibited() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " void foo() {", " // BUG: Diagnostic contains: lorem", " RestrictedApiMethods.restrictedStaticMethod();", " // BUG: Diagnostic contains: lorem", " RestrictedApiMethods.accept(RestrictedApiMethods::restrictedStaticMethod);", " }", "}") .expectResult(Result.ERROR) .doTest(); } @Test public void restrictedConstructorProhibited() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " void foo() {", " // BUG: Diagnostic contains: lorem", " new RestrictedApiMethods(0);", " // BUG: Diagnostic contains: lorem", " RestrictedApiMethods.accept(RestrictedApiMethods::new);", " }", "}") .expectResult(Result.ERROR) .doTest(); } @Test public void restrictedConstructorViaAnonymousClassProhibited() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " void foo() {", " // BUG: Diagnostic contains: lorem", " new RestrictedApiMethods() {};", " }", "}") .expectResult(Result.ERROR) .doTest(); } @Test public void restrictedConstructorViaAnonymousClassAllowed() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " @Allowlist ", " void foo() {", " new RestrictedApiMethods() {};", " }", "}") .expectResult(Result.OK) .doTest(); } @Test public void restrictedCallAnonymousClassFromInterface() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " void foo() {", " new IFaceWithRestriction() {", " @Override", " public void dontCallMe() {}", " }", " // BUG: Diagnostic contains: ipsum", " .dontCallMe();", " }", "}") .expectResult(Result.ERROR) .doTest(); } @Test public void implicitRestrictedConstructorProhibited() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase extends RestrictedApiMethods {", " // BUG: Diagnostic contains: lorem", " public Testcase() {}", "}") .expectResult(Result.ERROR) .doTest(); } @Ignore("Doesn't work yet") @Test public void implicitRestrictedConstructorProhibited_implicitConstructor() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", " // BUG: Diagnostic contains: lorem", "class Testcase extends RestrictedApiMethods {}") .expectResult(Result.ERROR) .doTest(); } @Test public void allowWithWarning() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " @AllowlistWithWarning", " void foo(RestrictedApiMethods m) {", " // BUG: Diagnostic contains: lorem", " m.restrictedMethod();", " // BUG: Diagnostic contains: lorem", " m.accept(m::restrictedMethod);", " }", "}") .expectResult(Result.OK) .doTest(); } @Test public void allowWithoutWarning() { helper .addSourceLines( "Testcase.java", "package com.google.errorprone.bugpatterns.testdata;", "class Testcase {", " @Allowlist", " void foo(RestrictedApiMethods m) {", " m.restrictedMethod();", " m.accept(m::restrictedMethod);", " }", "}") .expectResult(Result.OK) .doTest(); } // Regression test for b/36160747 @Test public void allowAllDefinitionsInFile() { helper .addSourceLines( "Testcase.java", "", "package separate.test;", "", "import com.google.errorprone.annotations.RestrictedApi;", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Target;", "", "class Testcase {", " @Allowlist", " void caller() {", " restrictedMethod();", " }", " @RestrictedApi(", " explanation=\"test\",", " allowlistAnnotations = {Allowlist.class},", " link = \"foo\"", " )", " void restrictedMethod() {", " }", " @Target({ElementType.METHOD, ElementType.CONSTRUCTOR})", " @interface Allowlist {}", "}") .doTest(); } // https://github.com/google/error-prone/issues/2099 @Test public void i2099() { helper .addSourceLines( "T.java", "package t;", "class T {", " static class Foo {", " class Loo {}", " }", " public void testFoo(Foo foo) {", " foo.new Loo() {};", " }", "}") .expectResult(Result.OK) .doTest(); } @Ignore("https://github.com/google/error-prone/issues/2152") @Test public void i2152() { helper .addSourceLines( "T.java", "class T extends S {", " void f() {", " this.new I(\"\") {};", " }", "}", "abstract class S {", " public class I {", " public I(String name) {}", " }", "}") .expectResult(Result.OK) .doTest(); } @Test public void enumConstructor() { helper .addSourceLines( "T.java", // "enum E {", " ONE(1, 2) {};", " E(int x, int y) {}", "}") .expectResult(Result.OK) .doTest(); } }
10,694
29.383523
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryAnonymousClassTest.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link UnnecessaryAnonymousClass}Test */ @RunWith(JUnit4.class) public class UnnecessaryAnonymousClassTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(UnnecessaryAnonymousClass.class, getClass()); @Test public void variable_instance() { testHelper .addInputLines( "Test.java", "import java.util.function.Function;", "class Test {", " private final Function<String, String> camelCase = new Function<String, String>() {", " public String apply(String x) {", " return \"hello \" + x;", " }", " };", " void g() {", " Function<String, String> f = camelCase;", " System.err.println(camelCase.apply(\"world\"));", " }", "}") .addOutputLines( "Test.java", "import java.util.function.Function;", "class Test {", " private String camelCase(String x) {", " return \"hello \" + x;", " }", " void g() {", " Function<String, String> f = this::camelCase;", " System.err.println(camelCase(\"world\"));", " }", "}") // Make sure the method body is still reformatted correctly. .doTest(TEXT_MATCH); } @Test public void variable_static() { testHelper .addInputLines( "Test.java", "import java.util.function.Function;", "class Test {", " private static final Function<String, String> F = new Function<String, String>() {", " public String apply(String x) {", " return \"hello \" + x;", " }", " };", " void g() {", " Function<String, String> l = Test.F;", " System.err.println(F.apply(\"world\"));", " }", "}") .addOutputLines( "Test.java", "import java.util.function.Function;", "class Test {", " private static String f(String x) {", " return \"hello \" + x;", " }", " void g() {", " Function<String, String> l = Test::f;", " System.err.println(f(\"world\"));", " }", "}") .doTest(); } @Test public void abstractClass() { testHelper .addInputLines( "Test.java", "import java.util.function.Function;", "class Test {", " static abstract class Impl implements Function<String, String> {", " public String apply(String input) {", " return input;", " }", " public abstract void f(String input);", " }", " private final Function<String, String> camelCase = new Impl() {", " public void f(String input) {}", " };", " void g() {", " Function<String, String> f = camelCase;", " System.err.println(camelCase.apply(\"world\"));", " }", "}") .expectUnchanged() .doTest(); } @Test public void recursive() { testHelper .addInputLines( "Test.java", "import java.util.function.Function;", "class Test {", " private static final Function<Object, Object> STRINGIFY =", " new Function<Object, Object>() {", " @Override", " public Object apply(Object input) {", " return transform(STRINGIFY);", " }", " };", " public static Object transform(Function<Object, Object> f) {", " return f.apply(\"a\");", " }", "}") .addOutputLines( "Test.java", "import java.util.function.Function;", "class Test {", " private static Object stringify(Object input) {", " return transform(Test::stringify);", " }", " public static Object transform(Function<Object, Object> f) {", " return f.apply(\"a\");", " }", "}") .doTest(); } @Test public void invokingDefaultMethod() { testHelper .addInputLines( "Test.java", "import java.util.function.Function;", "class Test {", " interface Foo {", " int foo(int a);", " default void bar() {", " foo(1);", " }", " }", " private static final Foo FOO = new Foo() {", " @Override public int foo(int a) {", " return 2 * a;", " }", " };", " public static void test() {", " FOO.bar();", " useFoo(FOO);", " }", " public static void useFoo(Foo foo) {}", "}") .expectUnchanged() .doTest(); } @Test public void mockitoSpy() { testHelper .addInputLines( "Test.java", "import java.util.function.Function;", "import org.mockito.Spy;", "class Test {", " interface Foo {", " int foo(int a);", " }", " @Spy", " private static final Foo FOO = new Foo() {", " @Override", " public int foo(int a) {", " return 2 * a;", " }", " };", " public static void test() {", " FOO.foo(2);", " }", "}") .expectUnchanged() .doTest(); } }
6,815
31.61244
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TreeToStringTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link TreeToString}. */ @RunWith(JUnit4.class) public class TreeToStringTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(TreeToString.class, getClass()); @Test public void noMatch() { testHelper .addSourceLines( "ExampleChecker.java", "import com.google.errorprone.BugPattern;", "import com.google.errorprone.BugPattern.SeverityLevel;", "import com.google.errorprone.VisitorState;", "import com.google.errorprone.bugpatterns.BugChecker;", "import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;", "import com.google.errorprone.matchers.Description;", "import com.sun.source.tree.ClassTree;", "import com.sun.tools.javac.code.Types;", "@BugPattern(name = \"Example\", summary = \"\", severity = SeverityLevel.ERROR)", "public class ExampleChecker extends BugChecker implements ClassTreeMatcher {", " @Override public Description matchClass(ClassTree t, VisitorState s) {", " return Description.NO_MATCH;", " }", "}") .addModules("jdk.compiler/com.sun.tools.javac.code") .doTest(); } @Test public void matchInABugChecker() { testHelper .addSourceLines( "ExampleChecker.java", "import static com.google.errorprone.util.ASTHelpers.getSymbol;", "import com.google.errorprone.BugPattern;", "import com.google.errorprone.BugPattern.SeverityLevel;", "import com.google.errorprone.VisitorState;", "import com.google.errorprone.bugpatterns.BugChecker;", "import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;", "import com.google.errorprone.fixes.SuggestedFix;", "import com.google.errorprone.matchers.Description;", "import com.google.errorprone.matchers.Matcher;", "import com.sun.source.tree.ClassTree;", "import com.sun.tools.javac.code.Symbol;", "import com.sun.tools.javac.code.Symbol.ClassSymbol;", "import com.sun.tools.javac.tree.TreeMaker;", "import com.sun.tools.javac.code.Type;", "import com.sun.tools.javac.code.Types;", "@BugPattern(name = \"Example\", summary = \"\", severity = SeverityLevel.ERROR)", "public class ExampleChecker extends BugChecker implements ClassTreeMatcher {", " private static Matcher<ClassTree> matches(String name) {", " // BUG: Diagnostic contains: state.getSourceForNode(c).equals", " return (Matcher<ClassTree>) (c, state) -> c.toString().equals(name);", " }", " @Override public Description matchClass(ClassTree tree, VisitorState state) {", " // BUG: Diagnostic contains: state.getSourceForNode(tree).contains", " if (tree.toString().contains(\"match\")) {", " return describeMatch(tree);", " }", " return Description.NO_MATCH;", " }", " private String createTree(VisitorState state) {", " TreeMaker maker = TreeMaker.instance(state.context);", " // BUG: Diagnostic contains: state.getConstantExpression(\"val\")", " return maker.Literal(\"val\").toString();", " }", "}") .addModules( "jdk.compiler/com.sun.tools.javac.code", "jdk.compiler/com.sun.tools.javac.tree", "jdk.compiler/com.sun.tools.javac.util") .doTest(); } @Test public void positiveCases() { testHelper.addSourceFile("TreeToStringPositiveCases.java").doTest(); } @Test public void negativeCases() { testHelper .addSourceFile("TreeToStringNegativeCases.java") .addModules( "jdk.compiler/com.sun.tools.javac.code", "jdk.compiler/com.sun.tools.javac.util") .doTest(); } }
4,873
42.132743
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LockOnNonEnclosingClassLiteralTest.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class LockOnNonEnclosingClassLiteralTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(LockOnNonEnclosingClassLiteral.class, getClass()); @Test public void lockOnNonEnclosingClassLiteralPositiveCases() { compilationHelper.addSourceFile("LockOnNonEnclosingClassLiteralPositiveCases.java").doTest(); } @Test public void lockOnNonEnclosingClassLiteralNegativeCases() { compilationHelper.addSourceFile("LockOnNonEnclosingClassLiteralNegativeCases.java").doTest(); } }
1,372
33.325
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/StronglyTypeByteStringTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link StronglyTypeByteString}. */ @RunWith(JUnit4.class) public final class StronglyTypeByteStringTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(StronglyTypeByteString.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(StronglyTypeByteString.class, getClass()); @Test public void findingLocatedOnField() { compilationHelper .addSourceLines( "Test.java", "import com.google.protobuf.ByteString;", "class Test {", " // BUG: Diagnostic contains: ByteString instances", " private static final byte[] FOO_BYTES = new byte[10];", " public ByteString get() {", " return ByteString.copyFrom(FOO_BYTES);", " }", "}") .doTest(); } @Test public void byteStringFactory() { refactoringHelper .addInputLines( "Test.java", "import com.google.protobuf.ByteString;", "class Test {", " private static final byte[] FOO_BYTES = new byte[10];", " public ByteString get() {", " return ByteString.copyFrom(FOO_BYTES);", " }", "}") .addOutputLines( "Test.java", "import com.google.protobuf.ByteString;", "class Test {", " private static final ByteString FOO_BYTES = ByteString.copyFrom(new byte[10]);", " public ByteString get() {", " return FOO_BYTES;", " }", "}") .doTest(); } @Test public void byteStringFactory_addNewTypeToByteArrayLiterals() { refactoringHelper .addInputLines( "Test.java", "import com.google.protobuf.ByteString;", "class Test {", " private static final byte[] FOO_BYTES = {7, 7, 7};", " public ByteString get() {", " return ByteString.copyFrom(FOO_BYTES);", " }", "}") .addOutputLines( "Test.java", "import com.google.protobuf.ByteString;", "class Test {", " private static final ByteString FOO_BYTES = ByteString.copyFrom(new byte[] {7, 7," + " 7});", " public ByteString get() {", " return FOO_BYTES;", " }", "}") .doTest(); } @Test public void byteStringFactory_noNewTypeAddedIfLiteralHasType() { refactoringHelper .addInputLines( "Test.java", "import com.google.protobuf.ByteString;", "class Test {", " private static final byte[] FOO_BYTES = new byte[] {7, 7, 7};", " public ByteString get() {", " return ByteString.copyFrom(FOO_BYTES);", " }", "}") .addOutputLines( "Test.java", "import com.google.protobuf.ByteString;", "class Test {", " private static final ByteString FOO_BYTES = ByteString.copyFrom(new byte[] {7, 7," + " 7});", " public ByteString get() {", " return FOO_BYTES;", " }", "}") .doTest(); } }
4,226
33.08871
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/EqualsUnsafeCastTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link EqualsUnsafeCast} bugpattern. * * @author ghm@google.com (Graeme Morgan) */ @RunWith(JUnit4.class) public final class EqualsUnsafeCastTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(EqualsUnsafeCast.class, getClass()); @Test public void fixes() { BugCheckerRefactoringTestHelper.newInstance(EqualsUnsafeCast.class, getClass()) .addInputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " Test that = (Test) o;", " return that.a == a;", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (!(o instanceof Test)) { return false; }", " Test that = (Test) o;", " return that.a == a;", " }", "}") .doTest(); } @Test public void fixesInlineCheck() { BugCheckerRefactoringTestHelper.newInstance(EqualsUnsafeCast.class, getClass()) .addInputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " return o != null && a == ((Test) o).a;", " }", "}") .addOutputLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (!(o instanceof Test)) { return false; }", " return o != null && a == ((Test) o).a;", " }", "}") .doTest(); } @Test public void positiveWrongType() { helper .addSourceLines( "Test.java", "class SubTest extends Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (!(o instanceof Test)) { return false; }", " // BUG: Diagnostic contains: instanceof SubTest", " return o != null && a == ((SubTest) o).a;", " }", "}", "class Test {}") .doTest(); } @Test public void negative_classEquality() { helper .addSourceLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (getClass() == o.getClass()) { return false; }", " return o != null && a == ((Test) o).a;", " }", "}") .doTest(); } @Test public void negative_instanceOf() { helper .addSourceLines( "Test.java", "class Test {", " private int a;", " @Override public boolean equals(Object o) {", " if (!(o instanceof Test)) { return false; }", " return o != null && a == ((Test) o).a;", " }", "}") .doTest(); } }
4,019
29.923077
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/PrimitiveArrayPassedToVarargsMethodTest.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class PrimitiveArrayPassedToVarargsMethodTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(PrimitiveArrayPassedToVarargsMethod.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceFile("PrimitiveArrayPassedToVarargsMethodPositiveCases.java") .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceFile("PrimitiveArrayPassedToVarargsMethodNegativeCases.java") .doTest(); } }
1,417
29.170213
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryStaticImportTest.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link UnnecessaryStaticImport}Test */ @RunWith(JUnit4.class) public class UnnecessaryStaticImportTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnnecessaryStaticImport.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "b/B.java", "package b;", "public class B {", " public static class Inner {}", "}") .addSourceLines( "Test.java", "// BUG: Diagnostic contains: import b.B.Inner;", "import static b.B.Inner;", "class Test {}") .doTest(); } @Test public void positiveRename() { compilationHelper .addSourceLines( "a/A.java", "package a;", "public class A {", " public static class Inner {}", "}") .addSourceLines("b/B.java", "package b;", "import a.A;", "public class B extends A {}") .addSourceLines( "b/Test.java", "package b;", "// BUG: Diagnostic contains: import a.A.Inner;", "import static b.B.Inner;", "class Test {}") .doTest(); } @Test public void negativeStaticMethod() { compilationHelper .addSourceLines( "a/A.java", "package a;", "public class A {", " public static class Inner {", " public static void f() {}", " }", "}") .addSourceLines("b/B.java", "package b;", "import a.A;", "public class B extends A {}") .addSourceLines("b/Test.java", "package b;", "import static a.A.Inner.f;", "class Test {}") .doTest(); } @Test public void negativeGenericTypeStaticMethod() { compilationHelper .addSourceLines( "a/A.java", "package a;", "public class A {", " public static class Inner<T> {", " public static void f() {}", " }", "}") .addSourceLines("b/B.java", "package b;", "import a.A;", "public class B extends A {}") .addSourceLines("b/Test.java", "package b;", "import static a.A.Inner.f;", "class Test {}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "a/A.java", "package a;", "public class A {", " public static class Inner {}", "}") .addSourceLines("b/B.java", "package b;", "import a.A;", "public class B extends A {}") .addSourceLines("b/Test.java", "package b;", "import a.A.Inner;", "class Test {}") .doTest(); } }
3,395
32.623762
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/LockOnBoxedPrimitiveTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link LockOnBoxedPrimitive} bugpattern. */ @RunWith(JUnit4.class) public class LockOnBoxedPrimitiveTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(LockOnBoxedPrimitive.class, getClass()); @Test public void detectsSynchronizedBoxedLocks() throws Exception { compilationHelper .addSourceLines( "Test.java", "class Test {", " private Byte badByteLock;", " private Short badShortLock;", " private Integer badIntLock;", " private Long badLongLock;", " private Float badFloatLock;", " private Double badDoubleLock;", " private Boolean badBooleanLock;", " private Character badCharLock;", " private void test() {", bugOnSynchronizedBlock("badByteLock"), bugOnSynchronizedBlock("badShortLock"), bugOnSynchronizedBlock("badIntLock"), bugOnSynchronizedBlock("badLongLock"), bugOnSynchronizedBlock("badFloatLock"), bugOnSynchronizedBlock("badDoubleLock"), bugOnSynchronizedBlock("badBooleanLock"), bugOnSynchronizedBlock("badCharLock"), " }", "}") .doTest(); } @Test public void ignoresSynchronizedObjectLock() throws Exception { compilationHelper .addSourceLines( "Test.java", "class Test {", " private Object okLock;", " private void test() {", " synchronized (okLock) {", " }", " }", "}") .doTest(); } @Test public void ignoresSynchronizedObjectLock_initialized() throws Exception { compilationHelper .addSourceLines( "Test.java", "class Test {", " private final Object okLock = Test.class;", " private void test() {", " synchronized (okLock) {", " }", " }", "}") .doTest(); } @Test public void detectsMonitorMethodBoxedLock() throws Exception { compilationHelper .addSourceLines( "Test.java", "class Test {", " private Byte badByteLock;", " private Short badShortLock;", " private Integer badIntLock;", " private Long badLongLock;", " private Float badFloatLock;", " private Double badDoubleLock;", " private Boolean badBooleanLock;", " private Character badCharLock;", " private void test() throws InterruptedException {", bugOnMonitorMethods("badByteLock"), bugOnMonitorMethods("badShortLock"), bugOnMonitorMethods("badIntLock"), bugOnMonitorMethods("badLongLock"), bugOnMonitorMethods("badFloatLock"), bugOnMonitorMethods("badDoubleLock"), bugOnMonitorMethods("badBooleanLock"), bugOnMonitorMethods("badCharLock"), " }", "}") .doTest(); } @Test public void ignoresMonitorMethodObjectLock() throws Exception { compilationHelper .addSourceLines( "Test.java", "class Test {", " private Object okLock;", " private void test() throws InterruptedException {", " okLock.wait();", " okLock.wait(1);", " okLock.wait(1, 2);", " okLock.notify();", " okLock.notifyAll();", " }", "}") .doTest(); } @Test public void ignoresMonitorMethodObjectLock_initialized() throws Exception { compilationHelper .addSourceLines( "Test.java", "class Test {", " private final Object okLock = new Object();", " private void test() throws InterruptedException {", " okLock.wait();", " okLock.wait(1);", " okLock.wait(1, 2);", " okLock.notify();", " okLock.notifyAll();", " }", "}") .doTest(); } private static String bugOnSynchronizedBlock(String variableName) { String formatString = String.join( "\n", " // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock", " synchronized (%s) {", " }"); return String.format(formatString, variableName); } private static String bugOnMonitorMethods(String variableName) { String formatString = String.join( "\n", " // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock", " %s.wait();", " // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock", " %<s.wait(1);", " // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock", " %<s.wait(1, 2);", " // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock", " %<s.notify();", " // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock", " %<s.notifyAll();"); return String.format(formatString, variableName); } @Test public void refactoring() { BugCheckerRefactoringTestHelper.newInstance(LockOnBoxedPrimitive.class, getClass()) .addInputLines( "Test.java", "class Test {", " private Boolean myBoolean;", " void test(boolean value) {", " synchronized (myBoolean) {", " myBoolean = value;", " }", " }", "}") .addOutputLines( "Test.java", "import com.google.errorprone.annotations.concurrent.GuardedBy;", "class Test {", " private final Object myBooleanLock = new Object();", " @GuardedBy(\"myBooleanLock\")", " private boolean myBoolean;", " void test(boolean value) {", " synchronized (myBooleanLock) {", " myBoolean = value;", " }", " }", "}") .doTest(); } }
7,259
33.571429
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/RobolectricShadowDirectlyOnTest.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link RobolectricShadowDirectlyOn}Test */ @RunWith(JUnit4.class) public class RobolectricShadowDirectlyOnTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(RobolectricShadowDirectlyOn.class, getClass()); @Test public void positive() { testHelper .addInputLines( "Shadow.java", "package org.robolectric.shadow.api;", "import org.robolectric.util.ReflectionHelpers.ClassParameter;", "public class Shadow {", " public static <T> T directlyOn(T shadowedObject, Class<T> clazz) {", " return null;", " }", " public static <T> Runnable directlyOn(", " T shadowedObject, Class<T> clazz, String baz, ClassParameter<?>... params)" + " {", " return null;", " }", "}") .expectUnchanged() .addInputLines( "ReflectionHelpers.java", "package org.robolectric.util;", "public class ReflectionHelpers {", " public static class ClassParameter<V> {", " public static <V> ClassParameter<V> from(Class<? extends V> clazz, V val) {", " return null;", " }", " }", "}") .expectUnchanged() .addInputLines( "Foo.java", "import java.util.List;", "class Foo {", " Runnable baz(Object r, long n, List<?> x, String s) {", " return null;", " }", "}") .expectUnchanged() .addInputLines( "Test.java", "import java.util.List;", "import org.robolectric.shadow.api.Shadow;", "class Test {", " public <T> Runnable registerNativeAllocation(Foo foo, Object r, long n, List<T> x)" + " {", " return Shadow.directlyOn(foo, Foo.class).baz(r, n, x, null);", " }", "}") .addOutputLines( "Test.java", "import java.util.List;", "import org.robolectric.shadow.api.Shadow;", "import org.robolectric.util.ReflectionHelpers.ClassParameter;", "class Test {", " public <T> Runnable registerNativeAllocation(Foo foo, Object r, long n, List<T> x)" + " {", " return Shadow.directlyOn(", " foo,", " Foo.class,", " \"baz\",", " ClassParameter.from(Object.class, r),", " ClassParameter.from(long.class, n),", " ClassParameter.from(List.class, x),", " ClassParameter.from(String.class, null));", " }", "}") .doTest(); } }
3,701
36.393939
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/AnnotateFormatMethodTest.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link AnnotateFormatMethod} bug pattern. * * @author ghm@google.com (Graeme Morgan) */ @RunWith(JUnit4.class) public final class AnnotateFormatMethodTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(AnnotateFormatMethod.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceLines( "AnnotateFormatMethodPositiveCases.java", "class AnnotateFormatMethodPositiveCases {", " // BUG: Diagnostic contains: FormatMethod", " String formatMe(String formatString, Object... args) {", " return String.format(formatString, args);", " }", "}") .doTest(); } @Test public void alreadyAnnotated() { compilationHelper .addSourceLines( "AnnotateFormatMethodNegativeCases.java", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "class AnnotateFormatMethodNegativeCases {", " @FormatMethod", " String formatMe(@FormatString String formatString, Object... args) {", " return String.format(formatString, args);", " }", "}") .doTest(); } @Test public void notTerminalArguments() { compilationHelper .addSourceLines( "AnnotateFormatMethodNegativeCases.java", "class AnnotateFormatMethodNegativeCases {", " // BUG: Diagnostic contains: reordered", " String formatMe(String formatString, String surprise, Object... args) {", " return String.format(formatString, args);", " }", "}") .doTest(); } @Test public void notVarArgs() { compilationHelper .addSourceLines( "AnnotateFormatMethodNegativeCases.java", "class AnnotateFormatMethodNegativeCases {", " String formatMe(String formatString, String justTheOneArgument) {", " return String.format(formatString, justTheOneArgument);", " }", "}") .doTest(); } }
3,030
32.307692
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/TestExceptionCheckerTest.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link TestExceptionChecker}Test */ @RunWith(JUnit4.class) public class TestExceptionCheckerTest { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(TestExceptionChecker.class, getClass()); @Test public void positive() { testHelper .addInputLines( "in/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test(expected = IOException.class, timeout = 0L)", " public void test() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " Files.readAllBytes(p);", " Files.readAllBytes(p);", " }", "}") .addOutputLines( "out/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.assertThrows;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test(timeout = 0L)", " public void test() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " Files.readAllBytes(p);", " assertThrows(IOException.class, () -> Files.readAllBytes(p));", " }", "}") .doTest(); } @Test public void positive_markerAnnotation() { testHelper .addInputLines( "in/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test(expected = IOException.class)", " public void test() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " Files.readAllBytes(p);", " }", "}") .addOutputLines( "out/ExceptionTest.java", "import static com.google.common.truth.Truth.assertThat;", "import static org.junit.Assert.assertThrows;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void test() throws Exception {", " Path p = Paths.get(\"NOSUCH\");", " assertThrows(IOException.class, () -> Files.readAllBytes(p));", " }", "}") .doTest(); } @Test public void oneStatement() { testHelper .addInputLines( "in/ExceptionTest.java", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test(expected = IOException.class)", " public void test() throws Exception {", " Files.readAllBytes(Paths.get(\"NOSUCH\"));", " }", "}") .addOutputLines( "in/ExceptionTest.java", "import static org.junit.Assert.assertThrows;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void test() throws Exception {", " assertThrows(IOException.class, () -> Files.readAllBytes(Paths.get(\"NOSUCH\")));", " }", "}") .doTest(); } @Test public void oneStatement_withFullyQualifiedTestAnnotation() { testHelper .addInputLines( "in/ExceptionTest.java", "import java.io.IOException;", "import java.nio.file.*;", "class ExceptionTest {", " @org.junit.Test(expected = IOException.class)", " public void test() throws Exception {", " Files.readAllBytes(Paths.get(\"NOSUCH\"));", " }", "}") .addOutputLines( "in/ExceptionTest.java", "import static org.junit.Assert.assertThrows;", "import java.io.IOException;", "import java.nio.file.*;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void test() throws Exception {", " assertThrows(IOException.class, () -> Files.readAllBytes(Paths.get(\"NOSUCH\")));", " }", "}") .doTest(); } @Test public void empty() { testHelper .addInputLines( "in/ExceptionTest.java", "import java.io.IOException;", "import org.junit.Test;", "class ExceptionTest {", " @Test(expected = IOException.class)", " public void test() throws Exception {", " }", "}") .addOutputLines( "in/ExceptionTest.java", "import java.io.IOException;", "import org.junit.Test;", "class ExceptionTest {", " @Test", " public void test() throws Exception {", " }", "}") .doTest(); } }
6,270
34.03352
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdateTest.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@code NonAtomicVolatileUpdate}. */ @RunWith(JUnit4.class) public class NonAtomicVolatileUpdateTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(NonAtomicVolatileUpdate.class, getClass()); @Test public void positiveCases() { compilationHelper.addSourceFile("NonAtomicVolatileUpdatePositiveCases.java").doTest(); } @Test public void negativeCases() { compilationHelper.addSourceFile("NonAtomicVolatileUpdateNegativeCases.java").doTest(); } }
1,328
31.414634
90
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/UseEnumSwitchTest.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link UseEnumSwitch}Test */ @RunWith(JUnit4.class) public class UseEnumSwitchTest { private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(UseEnumSwitch.class, getClass()); @Test public void refactoring() { refactoringHelper .addInputLines( "Test.java", "class Test {", " enum E { ONE, TWO, THREE }", " int f(E e) {", " if (e.equals(E.ONE)) {", " return 1;", " } else if (e.equals(E.TWO)) {", " return 2;", " } else {", " return 3;", " }", " }", "}") .addOutputLines( "Test.java", "class Test {", " enum E { ONE, TWO, THREE }", " int f(E e) {", " switch (e) {", " case ONE:", " return 1;", " case TWO:", " return 2;", " default:", " return 3;", " }", " }", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void nonConstantEnum() { refactoringHelper .addInputLines( "Test.java", "class Test {", " enum E {", " ONE, TWO, THREE;", " E one() {", " return ONE;", " }", " }", " int f(E e) {", " if (e == e.one()) {", " return 1;", " } else if (e == E.TWO) {", " return 2;", " } else {", " return 3;", " }", " }", "}") .expectUnchanged() .doTest(TestMode.TEXT_MATCH); } @Test public void notActuallyEnum_noFinding() { refactoringHelper .addInputLines( "Test.java", "class Test {", " interface A {}", " enum E implements A { ONE, TWO, THREE }", " int f(A e) {", " if (e.equals(E.ONE)) {", " return 1;", " } else if (e.equals(E.TWO)) {", " return 2;", " } else {", " return 3;", " }", " }", "}") .expectUnchanged() .doTest(TestMode.TEXT_MATCH); } }
3,349
28.385965
83
java