repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/ParcelableCreatorNegativeCases.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.android.testdata; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.ClassLoaderCreator; /** * @author bhagwani@google.com (Sumit Bhagwani) */ public class ParcelableCreatorNegativeCases { public abstract static class PublicAbstractParcelableClass implements Parcelable { // since the class is abstract, it is ok to not have CREATOR. } public static class PublicParcelableClass implements Parcelable { public static final Parcelable.Creator<PublicParcelableClass> CREATOR = new Parcelable.Creator<PublicParcelableClass>() { public PublicParcelableClass createFromParcel(Parcel in) { return new PublicParcelableClass(); } public PublicParcelableClass[] newArray(int size) { return new PublicParcelableClass[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { // no op } } public static class PublicParcelableClassWithClassLoaderCreator implements Parcelable { public static final ClassLoaderCreator<PublicParcelableClassWithClassLoaderCreator> CREATOR = new ClassLoaderCreator<PublicParcelableClassWithClassLoaderCreator>() { @Override public PublicParcelableClassWithClassLoaderCreator createFromParcel( Parcel source, ClassLoader loader) { return new PublicParcelableClassWithClassLoaderCreator(); } @Override public PublicParcelableClassWithClassLoaderCreator createFromParcel(Parcel source) { return new PublicParcelableClassWithClassLoaderCreator(); } @Override public PublicParcelableClassWithClassLoaderCreator[] newArray(int size) { return new PublicParcelableClassWithClassLoaderCreator[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { // no op } } public interface EmptyInterface {} public static class EmptyInterfaceAndParcelableImpl implements EmptyInterface, Parcelable { public static final Parcelable.Creator<EmptyInterface> CREATOR = new Parcelable.Creator<EmptyInterface>() { public EmptyInterfaceAndParcelableImpl createFromParcel(Parcel in) { return new EmptyInterfaceAndParcelableImpl(); } public EmptyInterfaceAndParcelableImpl[] newArray(int size) { return new EmptyInterfaceAndParcelableImpl[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { // no op } } public static class PublicParcelableWithRawCreatorClass implements Parcelable { public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public PublicParcelableWithRawCreatorClass createFromParcel(Parcel in) { return new PublicParcelableWithRawCreatorClass(); } public PublicParcelableWithRawCreatorClass[] newArray(int size) { return new PublicParcelableWithRawCreatorClass[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { // no op } } }
4,028
30.232558
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/RectIntersectReturnValueIgnoredPositiveCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.android.testdata; import android.graphics.Rect; /** * @author avenet@google.com (Arnaud J. Venet) */ public class RectIntersectReturnValueIgnoredPositiveCases { void checkSimpleCall(Rect rect, int aLeft, int aTop, int aRight, int aBottom) { // BUG: Diagnostic contains: Return value of android.graphics.Rect.intersect() must be checked rect.intersect(aLeft, aTop, aRight, aBottom); } void checkOverload(Rect rect1, Rect rect2) { // BUG: Diagnostic contains: Return value of android.graphics.Rect.intersect() must be checked rect1.intersect(rect2); } class RectContainer { int xPos; int yPos; Rect rect; boolean intersect(int length, int width) { // BUG: Diagnostic contains: Return value of android.graphics.Rect.intersect() must be checked rect.intersect(xPos, yPos, xPos + length, yPos + width); return true; } } void checkInMethod(int length, int width) { RectContainer container = new RectContainer(); container.intersect(length, width); } void checkInField(RectContainer container) { // BUG: Diagnostic contains: Return value of android.graphics.Rect.intersect() must be checked container.rect.intersect( container.xPos, container.yPos, container.xPos + 10, container.yPos + 20); } }
1,947
32.586207
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/HardCodedSdCardPathPositiveCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.android.testdata; /** * @author avenet@google.com (Arnaud J. Venet) */ public class HardCodedSdCardPathPositiveCases { // BUG: Diagnostic contains: Environment static final String PATH1 = "/sdcard"; // BUG: Diagnostic contains: Environment static final String PATH2 = "/sdcard/file1"; // BUG: Diagnostic contains: Environment static final String PATH3 = "/mnt/sdcard/file2"; // BUG: Diagnostic contains: Environment static final String PATH4 = "/" + "sd" + "card"; // BUG: Diagnostic contains: Environment static final String PATH5 = "/system/media/sdcard"; // BUG: Diagnostic contains: Environment static final String PATH6 = "/system/media/sdcard/file3"; // BUG: Diagnostic contains: Environment static final String PATH7 = "file://sdcard/file2"; // BUG: Diagnostic contains: Environment static final String PATH8 = "file:///sdcard/file2"; // BUG: Diagnostic contains: Context static final String PATH9 = "/data/data/dir/file"; // BUG: Diagnostic contains: Context static final String PATH10 = "/data/user/file1"; static final String FRAGMENT1 = "/data"; static final String FRAGMENT2 = "/user"; // BUG: Diagnostic contains: Context static final String PATH11 = "/data" + "/" + "user"; }
1,904
30.75
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/CustomParcelableList.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.android.testdata; import android.os.Parcel; import android.os.Parcelable; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * @author epmjohnston@google.com (Emily P.M. Johnston) */ public class CustomParcelableList<T> implements List<T>, Parcelable { @Override public int size() { return 0; } @Override public boolean isEmpty() { return false; } @Override public boolean contains(Object o) { return false; } @Override public Iterator<T> iterator() { return null; } @Override public Object[] toArray() { return null; } @Override public <T> T[] toArray(T[] a) { return null; } @Override public boolean add(T e) { return false; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<? extends T> c) { return false; } @Override public boolean addAll(int index, Collection<? extends T> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() {} @Override public T get(int index) { return null; } @Override public T set(int index, T element) { return null; } @Override public void add(int index, T element) {} @Override public T remove(int index) { return null; } @Override public int indexOf(Object o) { return 0; } @Override public int lastIndexOf(Object o) { return 0; } @Override public ListIterator<T> listIterator() { return null; } @Override public ListIterator<T> listIterator(int index) { return null; } @Override public List<T> subList(int fromIndex, int toIndex) { return null; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) {} public static final Parcelable.Creator<CustomParcelableList> CREATOR = new Parcelable.Creator<CustomParcelableList>() { @Override public CustomParcelableList createFromParcel(Parcel in) { return new CustomParcelableList(); } @Override public CustomParcelableList[] newArray(int size) { return new CustomParcelableList[size]; } }; }
3,153
18.231707
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/HardCodedSdCardPathNegativeCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.android.testdata; /** * @author avenet@google.com (Arnaud J. Venet) */ public class HardCodedSdCardPathNegativeCases { static final String PATH1 = "/home/sdcard"; static final String PATH2 = "/data/file1"; static final String FRAGMENT1 = "/root"; static final String FRAGMENT2 = "sdcard"; static final String PATH3 = FRAGMENT1 + "/" + FRAGMENT2; static final String PATH4 = "/data/dir/file2"; static final String FRAGMENT3 = "/data"; static final String FRAGMENT4 = "1user"; static final String PATH5 = FRAGMENT3 + "/" + FRAGMENT4; }
1,214
28.634146
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/FragmentNotInstantiableNegativeCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.android.testdata; import android.app.Fragment; /** * @author avenet@google.com (Arnaud J. Venet) */ public class FragmentNotInstantiableNegativeCases { public static class NotAFragment1 { public NotAFragment1(int x) {} } public static class NotAFragment2 { private NotAFragment2() {} } private static class NotAFragment3 {} public class NotAFragment4 {} private abstract class AbstractFragment extends Fragment { public AbstractFragment(int x) {} } private abstract class AbstractV4Fragment extends android.support.v4.app.Fragment { private int a; public int value() { return a; } } public static class MyFragment extends Fragment { private int a; public int value() { return a; } } public static class DerivedFragment extends MyFragment {} public static class MyV4Fragment extends android.support.v4.app.Fragment {} public static class DerivedV4Fragment extends MyV4Fragment { private int a; public int value() { return a; } } public static class MyFragment2 extends Fragment { public MyFragment2() {} public MyFragment2(int x) {} } public static class DerivedFragment2 extends MyFragment2 { public DerivedFragment2() {} public DerivedFragment2(boolean b) {} } public static class EnclosingClass { public static class InnerFragment extends Fragment { public InnerFragment() {} } } interface AnInterface { public class ImplicitlyStaticInnerFragment extends Fragment {} class ImplicitlyStaticAndPublicInnerFragment extends Fragment {} } }
2,264
23.354839
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/CustomFragmentNotInstantiablePositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.android.testdata; /** * @author jasonlong@google.com (Jason Long) */ public class CustomFragmentNotInstantiablePositiveCases { // BUG: Diagnostic contains: public static class PrivateFragment extends CustomFragment { public PrivateFragment() {} } public static class PrivateConstructor extends CustomFragment { // BUG: Diagnostic contains: public PrivateConstructor() {} } // BUG: Diagnostic contains: nullary constructor public static class NoConstructor extends CustomFragment { public NoConstructor(int x) {} } // BUG: Diagnostic contains: nullary constructor public static class NoConstructorV4 extends android.support.v4.app.Fragment { public NoConstructorV4(int x) {} } public static class ParentFragment extends CustomFragment { public ParentFragment() {} } public static class ParentFragmentV4 extends android.support.v4.app.Fragment { public ParentFragmentV4() {} } // BUG: Diagnostic contains: nullary constructor public static class DerivedFragmentNoConstructor extends ParentFragment { public DerivedFragmentNoConstructor(int x) {} } // BUG: Diagnostic contains: nullary constructor public static class DerivedFragmentNoConstructorV4 extends ParentFragmentV4 { public DerivedFragmentNoConstructorV4(boolean b) {} } public class EnclosingClass { // BUG: Diagnostic contains: static public class InnerFragment extends CustomFragment { public InnerFragment() {} } public CustomFragment create1() { // BUG: Diagnostic contains: public return new CustomFragment() {}; } public CustomFragment create2() { // BUG: Diagnostic contains: public class LocalFragment extends CustomFragment {} return new LocalFragment(); } } }
2,437
29.860759
80
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/CustomFragment.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.android.testdata; /** * @author jasonlong@google.com (Jason Long) */ public class CustomFragment {}
754
31.826087
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/R.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 android; public class R { public static final class string { public static final int yes = 0; public static final int no = 1; public static final int copy = 2; } }
797
30.92
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/preference/PreferenceActivity.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 android.preference; @SuppressWarnings("FragmentInjection") public class PreferenceActivity { protected boolean isValidFragment(String className) { return true; } }
790
30.64
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/util/Log.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 android.util; public class Log { public static boolean isLoggable(String tag, int level) { return false; } public static final int INFO = 0; }
772
28.730769
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/graphics/Rect.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 android.graphics; public class Rect { public boolean intersect(int x, int y, int x2, int y2) { return false; } public boolean intersect(Rect other) { return false; } public void setEmpty() {} }
831
27.689655
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/support/v4/app/Fragment.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 android.support.v4.app; public class Fragment {}
667
32.4
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/app/Fragment.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 android.app; public class Fragment {}
656
31.85
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/os/Binder.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 android.os; public class Binder { public static final long clearCallingIdentity() { return 1; } public static final void restoreCallingIdentity(long token) {} }
790
29.423077
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/os/PowerManager.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 android.os; public interface PowerManager { class WakeLock { public void acquire() {} public void acquire(int timeout) {} public boolean isHeld() { return true; } public void release() {} public void setReferenceCounted(boolean referenceCounted) {} } }
909
25.764706
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/os/Bundle.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 android.os; import java.io.Serializable; /** Stub for android.os.Bundle */ public class Bundle { public Bundle() {} public Serializable getSerializable(String key) { return null; } }
813
27.068966
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/os/Parcelable.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 android.os; public interface Parcelable { interface Creator<T> { T createFromParcel(Parcel in); T[] newArray(int size); } int describeContents(); void writeToParcel(Parcel dest, int flags); interface ClassLoaderCreator<T> extends Creator<T> { T createFromParcel(Parcel source, ClassLoader loader); } }
948
26.911765
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/stubs/android/os/Parcel.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 android.os; public interface Parcel {}
656
33.578947
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inlineme/SuggesterTest.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.inlineme; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for the {@link Suggester}. */ @RunWith(JUnit4.class) public class SuggesterTest { private final BugCheckerRefactoringTestHelper refactoringTestHelper = BugCheckerRefactoringTestHelper.newInstance(Suggester.class, getClass()); @Test public void buildAnnotation_withImports() { assertThat( InlineMeData.buildAnnotation( "REPLACEMENT", ImmutableSet.of("java.time.Duration", "java.time.Instant"), ImmutableSet.of())) .isEqualTo( "@InlineMe(replacement = \"REPLACEMENT\", " + "imports = {\"java.time.Duration\", \"java.time.Instant\"})\n"); } @Test public void buildAnnotation_withSingleImport() { assertThat( InlineMeData.buildAnnotation( "REPLACEMENT", ImmutableSet.of("java.time.Duration"), ImmutableSet.of())) .isEqualTo( "@InlineMe(replacement = \"REPLACEMENT\", " + "imports = \"java.time.Duration\")\n"); } @Test public void instanceMethodNewImport() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " private Duration deadline = Duration.ofSeconds(5);", " @Deprecated", " public void setDeadline(long millis) {", " setDeadline(Duration.ofMillis(millis));", " }", " public void setDeadline(Duration deadline) {", " this.deadline = deadline;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " private Duration deadline = Duration.ofSeconds(5);", " @InlineMe(replacement = \"this.setDeadline(Duration.ofMillis(millis))\"," + " imports = \"java.time.Duration\")", " @Deprecated", " public void setDeadline(long millis) {", " setDeadline(Duration.ofMillis(millis));", " }", " public void setDeadline(Duration deadline) {", " this.deadline = deadline;", " }", "}") .doTest(); } @Test public void staticMethodInNewClass() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " @Deprecated", " public Duration fromMillis(long millis) {", " return Duration.ofMillis(millis);", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @InlineMe(", " replacement = \"Duration.ofMillis(millis)\", ", " imports = \"java.time.Duration\")", " @Deprecated", " public Duration fromMillis(long millis) {", " return Duration.ofMillis(millis);", " }", "}") .doTest(); } @Test public void unqualifiedStaticFieldReference() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public static final String STR = \"kurt\";", " @Deprecated", " public int stringLength() {", " return STR.length();", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " public static final String STR = \"kurt\";", // TODO(b/234643232): this is a bug; it should be "Client.STR.length()" plus an import " @InlineMe(replacement = \"STR.length()\")", " @Deprecated", " public int stringLength() {", " return STR.length();", " }", "}") .doTest(); } @Test public void qualifiedStaticFieldReference() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " public static final String STR = \"kurt\";", " @Deprecated", " public int stringLength() {", " return Client.STR.length();", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " public static final String STR = \"kurt\";", " @InlineMe(replacement = \"Client.STR.length()\", " + "imports = \"com.google.frobber.Client\")", " @Deprecated", " public int stringLength() {", " return Client.STR.length();", " }", "}") .doTest(); } @Test public void protectedConstructor() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " @Deprecated", " protected Client() {}", "}") .expectUnchanged() .doTest(); } @Test public void returnField() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " @Deprecated", " public Duration getZero() {", " return Duration.ZERO;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @InlineMe(replacement = \"Duration.ZERO\", imports = \"java.time.Duration\")", " @Deprecated", " public Duration getZero() {", " return Duration.ZERO;", " }", "}") .doTest(); } @Test public void implementationSplitOverMultipleLines() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "import java.time.Instant;", "public final class Client {", " @Deprecated", " public Duration getElapsed() {", " return Duration.between(", " Instant.ofEpochMilli(42),", " Instant.now());", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "import java.time.Instant;", "public final class Client {", " @InlineMe(", " replacement = \"Duration.between(Instant.ofEpochMilli(42), Instant.now())\", ", " imports = {\"java.time.Duration\", \"java.time.Instant\"})", " @Deprecated", " public Duration getElapsed() {", " return Duration.between(", " Instant.ofEpochMilli(42),", " Instant.now());", " }", "}") .doTest(); } @Test public void anonymousClass() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " @Deprecated", " public Object getUselessObject() {", " return new Object() {", " @Override", " public int hashCode() {", " return 42;", " }", " };", " }", "}") .expectUnchanged() .doTest(); } @Test public void methodReference() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "import java.util.Optional;", "public final class Client {", " @Deprecated", " public Optional<Duration> silly(Optional<Long> input) {", " return input.map(Duration::ofMillis);", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "import java.util.Optional;", "public final class Client {", " @InlineMe(replacement = \"input.map(Duration::ofMillis)\", ", " imports = \"java.time.Duration\")", " @Deprecated", " public Optional<Duration> silly(Optional<Long> input) {", " return input.map(Duration::ofMillis);", " }", "}") .doTest(); } @Test public void newClass() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import org.joda.time.Instant;", "public final class Client {", " @Deprecated", " public Instant silly() {", " return new Instant();", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import org.joda.time.Instant;", "public final class Client {", " @InlineMe(replacement = \"new Instant()\", imports = \"org.joda.time.Instant\")", " @Deprecated", " public Instant silly() {", " return new Instant();", " }", "}") .doTest(); } @Test public void newArray() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import org.joda.time.Instant;", "public final class Client {", " @Deprecated", " public Instant[] silly() {", " return new Instant[42];", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import org.joda.time.Instant;", "public final class Client {", " @InlineMe(replacement = \"new Instant[42]\", imports = \"org.joda.time.Instant\")", " @Deprecated", " public Instant[] silly() {", " return new Instant[42];", " }", "}") .doTest(); } @Test public void newNestedClass() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " @Deprecated", " public NestedClass silly() {", " return new NestedClass();", " }", " public static class NestedClass {}", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"new NestedClass()\", ", " imports = \"com.google.frobber.Client.NestedClass\")", " @Deprecated", " public NestedClass silly() {", " return new NestedClass();", " }", " public static class NestedClass {}", "}") .doTest(); } @Test public void returnStringLiteral() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " @Deprecated", " public String getName() {", " return \"kurt\";", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"\\\"kurt\\\"\")", " @Deprecated", " public String getName() {", " return \"kurt\";", " }", "}") .doTest(); } @Test public void callMethodWithStringLiteral() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " @Deprecated", " public String getName() {", " return getName(\"kurt\");", " }", " public String getName(String defaultValue) {", " return \"test\";", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"this.getName(\\\"kurt\\\")\")", " @Deprecated", " public String getName() {", " return getName(\"kurt\");", " }", " public String getName(String defaultValue) {", " return \"test\";", " }", "}") .doTest(); } @Test public void returnPrivateVariable() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " private final Duration myDuration = Duration.ZERO;", " @Deprecated", " public Duration getMyDuration() {", " return myDuration;", " }", "}") .expectUnchanged() .doTest(); } @Test public void returnPrivateVariable_qualifiedWithThis() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " private final Duration myDuration = Duration.ZERO;", " @Deprecated", " public Duration getMyDuration() {", " return this.myDuration;", " }", "}") .expectUnchanged() .doTest(); } @Test public void settingPrivateVariable() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " private Duration duration = Duration.ZERO;", " @Deprecated", " public void setDuration(Duration duration) {", " this.duration = duration;", " }", "}") .expectUnchanged() .doTest(); } @Test public void delegateToParentClass() { refactoringTestHelper .addInputLines( "Parent.java", "package com.google.frobber;", "import java.time.Duration;", "public class Parent {", " private Duration duration = Duration.ZERO;", " public final Duration after() {", " return duration;", " }", "}") .expectUnchanged() .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client extends Parent {", " private Duration duration = Duration.ZERO;", " @Deprecated", " public final Duration before() {", " return after();", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client extends Parent {", " private Duration duration = Duration.ZERO;", " @InlineMe(replacement = \"this.after()\")", " @Deprecated", " public final Duration before() {", " return after();", " }", "}") .doTest(); } @Test public void withCast() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " @Deprecated", " public void setDuration(Object duration) {", " foo((Duration) duration);", " }", " public void foo(Duration duration) {", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @InlineMe(replacement = \"this.foo((Duration) duration)\", imports =" + " \"java.time.Duration\")", " @Deprecated", " public void setDuration(Object duration) {", " foo((Duration) duration);", " }", " public void foo(Duration duration) {", " }", "}") .doTest(); } @Test public void accessPrivateVariable() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " private final Duration myDuration = Duration.ZERO;", " @Deprecated", " public boolean silly() {", " return myDuration.isZero();", " }", "}") .expectUnchanged() .doTest(); } @Test public void accessPrivateMethod() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public final class Client {", " @Deprecated", " public boolean silly() {", " return privateDelegate();", " }", " private boolean privateDelegate() {", " return false;", " }", "}") .expectUnchanged() .doTest(); } @Test public void tryWithResources() { refactoringTestHelper .addInputLines( "Client.java", "import java.io.BufferedReader;", "import java.io.FileReader;", "import java.io.IOException;", "public class Client {", " @Deprecated", " public String readLine(String path) throws IOException {", " try (BufferedReader br = new BufferedReader(new FileReader(path))) {", " return br.readLine();", " }", " }", "}") .expectUnchanged() .doTest(); } @Test public void ifStatement() { refactoringTestHelper .addInputLines( "Client.java", "public class Client {", " @Deprecated", " public void foo(String input) {", " if (input.equals(\"hi\")) {", " return;", " }", " }", "}") .expectUnchanged() .doTest(); } @Test public void nestedBlock() { refactoringTestHelper .addInputLines( "Client.java", "public class Client {", " @Deprecated", " public String foo(String input) {", " {", " return input.toLowerCase();", " }", " }", "}") .expectUnchanged() .doTest(); } @Test public void ternaryOverMultipleLines() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " @Deprecated", " public Duration getDeadline(Duration deadline) {", " return deadline.compareTo(Duration.ZERO) > 0", " ? Duration.ofSeconds(42)", " : Duration.ZERO;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @InlineMe(replacement = \"deadline.compareTo(Duration.ZERO) > 0 ?" + " Duration.ofSeconds(42) : Duration.ZERO\", ", "imports = \"java.time.Duration\")", " @Deprecated", " public Duration getDeadline(Duration deadline) {", " return deadline.compareTo(Duration.ZERO) > 0", " ? Duration.ofSeconds(42)", " : Duration.ZERO;", " }", "}") .doTest(); } @Test public void staticCallingAnotherQualifiedStatic() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.time.Duration;", "public final class Client {", " @Deprecated", " public static Duration getDeadline() {", " return Client.getDeadline2();", " }", " public static Duration getDeadline2() {", " return Duration.ZERO;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @InlineMe(replacement = \"Client.getDeadline2()\", ", " imports = \"com.google.frobber.Client\")", " @Deprecated", " public static Duration getDeadline() {", " return Client.getDeadline2();", " }", " public static Duration getDeadline2() {", " return Duration.ZERO;", " }", "}") .doTest(); } @Test public void staticReferenceToJavaLang() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import static java.lang.String.format;", "public final class Client {", " @Deprecated", " public static String myFormat(String template, String arg) {", " return format(template, arg);", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import static java.lang.String.format;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"format(template, arg)\", staticImports =" + " \"java.lang.String.format\")", " @Deprecated", " public static String myFormat(String template, String arg) {", " return format(template, arg);", " }", "}") .doTest(); } @Test public void replacementContainsGenericInvocation() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.util.ArrayList;", "import java.util.List;", "public final class Client {", " @Deprecated", " public static List<Void> newArrayList() {", " return new ArrayList<Void>();", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.util.ArrayList;", "import java.util.List;", "public final class Client {", " @InlineMe(replacement = \"new ArrayList<Void>()\", imports =" + " \"java.util.ArrayList\")", " @Deprecated", " public static List<Void> newArrayList() {", " return new ArrayList<Void>();", " }", "}") .doTest(); } @Test public void suggestedFinalOnOtherwiseGoodMethod() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public class Client {", " @Deprecated", " public int method() {", " return 42;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "public class Client {", " @InlineMe(replacement = \"42\")", " @Deprecated", " public final int method() {", " return 42;", " }", "}") .doTest(); } @Test public void dontSuggestOnDefaultMethods() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public interface Client {", " @Deprecated", " public default int method() {", " return 42;", " }", "}") .expectUnchanged() .doTest(); } // Since constructors can't be "overridden" in the same way as other non-final methods, it's // OK to inline them even if there could be a subclass of the surrounding class. @Test public void deprecatedConstructorInNonFinalClass() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public class Client {", " @Deprecated", " public Client() {", " this(42);", " }", " public Client(int value) {}", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "public class Client {", " @InlineMe(replacement = \"this(42)\")", " @Deprecated", " public Client() {", " this(42);", " }", " public Client(int value) {}", "}") .doTest(); } @Test public void publicStaticFactoryCallsPrivateConstructor() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "public class Client {", " @Deprecated", " public static Client create() {", " return new Client();", " }", " private Client() {}", "}") .expectUnchanged() .doTest(); } @Test public void deprecatedMethodWithDoNotCall() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.DoNotCall;", "public class Client {", " @DoNotCall", " @Deprecated", " public void before() {", " after();", " }", " public void after() {}", "}") .expectUnchanged() .doTest(); } @Test public void implementationUsingPublicStaticField() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.frobber;", "import java.util.function.Supplier;", "public class Client {", " public static final Supplier<Integer> MAGIC = () -> 42;", " @Deprecated", " public static int before() {", " return after(MAGIC.get());", " }", " public static int after(int value) {", " return value;", " }", "}") .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.util.function.Supplier;", "public class Client {", " public static final Supplier<Integer> MAGIC = () -> 42;", " @InlineMe(" // TODO(b/202145711): MAGIC.get() should be Client.MAGIC.get() + "replacement = \"Client.after(MAGIC.get())\", " + "imports = \"com.google.frobber.Client\")", " @Deprecated", " public static int before() {", " return after(MAGIC.get());", " }", " public static int after(int value) {", " return value;", " }", "}") .doTest(); } @Test public void apisLikelyUsedReflectively() { refactoringTestHelper .addInputLines( "Test.java", "import com.google.errorprone.annotations.Keep;", "import com.google.inject.Provides;", "import java.time.Duration;", "import java.util.Optional;", "public class Test {", " @Deprecated", " @Provides", " public Optional<Duration> provides(Optional<Long> input) {", " return input.map(Duration::ofMillis);", " }", " @Deprecated", " @Keep", " public Optional<Duration> reflective(Optional<Long> input) {", " return input.map(Duration::ofMillis);", " }", "}") .expectUnchanged() .doTest(); } @Test public void importStatic_getsCorrectlySuggestedAsStaticImports() { refactoringTestHelper .addInputLines( "KeymasterEncrypter.java", "package com.google.security.keymaster;", "import static java.nio.charset.StandardCharsets.US_ASCII;", "import com.google.errorprone.annotations.InlineMe;", "public final class KeymasterEncrypter {", " @Deprecated", " public final byte[] encryptASCII(String plaintext) {", " return encrypt(plaintext.getBytes(US_ASCII));", " }", " public byte[] encrypt(byte[] plaintext) {", " return plaintext;", " }", "}") .addOutputLines( "KeymasterEncrypter.java", "package com.google.security.keymaster;", "import static java.nio.charset.StandardCharsets.US_ASCII;", "import com.google.errorprone.annotations.InlineMe;", "public final class KeymasterEncrypter {", " @InlineMe(", " replacement = \"this.encrypt(plaintext.getBytes(US_ASCII))\",", " staticImports =\"java.nio.charset.StandardCharsets.US_ASCII\")", " @Deprecated", " public final byte[] encryptASCII(String plaintext) {", " return encrypt(plaintext.getBytes(US_ASCII));", " }", " public byte[] encrypt(byte[] plaintext) {", " return plaintext;", " }", "}") .doTest(); } @Test public void importStatic_getsIncorrectlySuggestedAsImportsInsteadOfStaticImports() { refactoringTestHelper .addInputLines( "KeymasterCrypter.java", "package com.google.security.keymaster;", "import static java.nio.charset.StandardCharsets.US_ASCII;", "import com.google.errorprone.annotations.InlineMe;", "public final class KeymasterCrypter {", " @Deprecated", " public final String decryptASCII(byte[] ciphertext) {", " return new String(decrypt(ciphertext), US_ASCII);", " }", " public byte[] decrypt(byte[] ciphertext) {", " return ciphertext;", " }", "}") .addOutputLines( "KeymasterCrypter.java", "package com.google.security.keymaster;", "import static java.nio.charset.StandardCharsets.US_ASCII;", "import com.google.errorprone.annotations.InlineMe;", "public final class KeymasterCrypter {", // TODO(b/242890437): This line is wrong: " @InlineMe(replacement = \"new String(this.decrypt(ciphertext), US_ASCII)\", imports" + " = \"US_ASCII\")", // It should be this instead: // " @InlineMe(", // " replacement = \"new String(this.decrypt(ciphertext), US_ASCII)\",", // " staticImports =\"java.nio.charset.StandardCharsets.US_ASCII\")", " @Deprecated", " public final String decryptASCII(byte[] ciphertext) {", " return new String(decrypt(ciphertext), US_ASCII);", " }", " public byte[] decrypt(byte[] ciphertext) {", " return ciphertext;", " }", "}") .doTest(); } }
35,556
32.86381
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inlineme/ValidatorTest.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.inlineme; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import java.util.regex.Pattern; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for the {@code @InlineMe} {@link Validator}. */ @RunWith(JUnit4.class) public class ValidatorTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(Validator.class, getClass()); @Test public void staticFactoryToConstructor() { helper .addSourceLines( "Client.java", "package com.google.foo;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"new Client();\", imports ={\"com.google.foo.Client\"})", " @Deprecated", " public static Client create() {", " return new Client();", " }", " public Client() {", " }", "}") .doTest(); } @Test public void annotationWithImportsAsASingleMember() { helper .addSourceLines( "Client.java", "package com.google.foo;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"new Client();\", imports = \"com.google.foo.Client\")", " @Deprecated", " public static Client create() {", " return new Client();", " }", " public Client() {", " }", "}") .doTest(); } @Test public void arrayConstructor_fromInstanceMethod() { helper .addSourceLines( "Foo.java", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Foo {", " @InlineMe(replacement = \"new Duration[size]\", ", " imports = {\"java.time.Duration\"})", " @Deprecated", " public Duration[] someDurations(int size) {", " return new Duration[size];", " }", "}") .doTest(); } @Test public void arrayConstructor_fromStaticMethod() { helper .addSourceLines( "Foo.java", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Foo {", " @InlineMe(replacement = \"new Duration[size]\", ", " imports = {\"java.time.Duration\"})", " @Deprecated", " public static Duration[] someDurations(int size) {", " return new Duration[size];", " }", "}") .doTest(); } @Test public void instanceMethod_withInlineComment() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.util.function.Supplier;", "public final class Client {", " @InlineMe(replacement = \"this.after(string);\")", " @Deprecated", " public void before(String string) {", " after(/* string= */ string);", " }", " public void after(String string) {", " }", "}") .doTest(); } @Test public void instanceMethod_withInlineCommentInAnnotation() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.util.function.Supplier;", "public final class Client {", " @InlineMe(replacement = \"this.after(/* name= */ name);\")", " @Deprecated", " public void before(String name) {", " after(/* name= */ name);", " }", " public void after(String name) {", " }", "}") .doTest(); } @Test public void instanceMethod_with2InlineCommentInAnnotation() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.util.function.Supplier;", "public final class Client {", " @InlineMe(replacement = \"this.after(/* name1= */ name1, /* name2= */ name2);\")", " @Deprecated", " public void before(String name1, String name2) {", " after(/* name1= */ name1, /* name2= */ name2);", " }", " public void after(String name1, String name2) {", " }", "}") .doTest(); } @Test public void instanceMethod_withTrailingComment() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.util.function.Supplier;", "public final class Client {", " @InlineMe(replacement = \"this.after(string);\")", " @Deprecated", " public void before(String string) {", " after( // string", " string);", " }", " public void after(String string) {", " }", "}") .doTest(); } @Test public void instanceMethod_withLambda() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.util.function.Supplier;", "public final class Client {", " @InlineMe(replacement = \"this.after(() -> string);\")", " @Deprecated", " // BUG: Diagnostic contains: evaluation timing", " public void before(String string) {", " after(() -> string);", " }", " public void after(Supplier<String> supplier) {", " }", "}") .doTest(); } @Test public void instanceMethod_withLambdaAndVariable() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.util.function.Function;", "public final class Client {", " @InlineMe(replacement = \"this.after(str -> Integer.parseInt(str));\")", " @Deprecated", " public void before() {", " after(str -> Integer.parseInt(str));", " }", " public void after(Function<String, Integer> function) {", " }", "}") .doTest(); } @Test public void instanceMethod_privateVariable() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " private final String str = null;", " @InlineMe(replacement = \"str;\")", " @Deprecated", " // BUG: Diagnostic contains: deprecated or less visible API elements: str", " public String before() {", " return str;", " }", "}") .doTest(); } @Test public void instanceMethod_publicVariable() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " public final String str = null;", " @InlineMe(replacement = \"this.str;\")", " @Deprecated", " public String before() {", " return str;", " }", "}") .doTest(); } @Test public void instanceMethod_privateMethod() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"this.privateMethod();\")", " @Deprecated", " // BUG: Diagnostic contains: deprecated or less visible API elements:" + " privateMethod()", " public String before() {", " return privateMethod();", " }", " private String privateMethod() {", " return null;", " }", "}") .doTest(); } @Test public void instanceMethod_splitOverMultipleLines_withLambda() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.util.function.Supplier;", "public final class Client {", " @InlineMe(replacement = \"this.after(() -> string);\")", " @Deprecated", " // BUG: Diagnostic contains: evaluation timing", " public void before(String string) {", " after(() ->", " string);", " }", " public void after(Supplier<String> supplier) {", " }", "}") .doTest(); } private static final Pattern FROM_ANNOTATION = Pattern.compile("FromAnnotation: \\[.*;]"); @Test public void constructor() { helper .addSourceLines( "ProfileTimer.java", "import com.google.common.base.Ticker;", "import com.google.errorprone.annotations.InlineMe;", "public final class ProfileTimer {", " @InlineMe(", " replacement = \"this(Ticker.systemTicker(), name)\", ", " imports = {\"com.google.common.base.Ticker\"})", " @Deprecated", " public ProfileTimer(String name) {", " this(Ticker.systemTicker(), name);", " }", " public ProfileTimer(Ticker ticker, String name) {", " }", "}") .doTest(); } @Test public void missingImport() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @InlineMe(replacement = \"this.setDeadline(Duration.ofMillis(millis))\")", " @Deprecated", " // BUG: Diagnostic matches: BAR", " public void setDeadlineInMillis(long millis) {", " this.setDeadline(Duration.ofMillis(millis));", " }", " public void setDeadline(Duration deadline) {", " }", "}") .expectErrorMessage( "BAR", str -> str.contains("InferredFromBody: [java.time.Duration") && str.contains("FromAnnotation: []")) .doTest(); } @Test public void fullQualifiedReplacementType() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"this.setDeadline(java.time.Duration.ofMillis(millis))\")", " @Deprecated", " public void setDeadlineInMillis(long millis) {", " this.setDeadline(java.time.Duration.ofMillis(millis));", " }", " public void setDeadline(java.time.Duration deadline) {", " }", "}") .doTest(); } @Test public void replacementWithJavaLangClass() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.after(String.valueOf(value))\")", " public void before(long value) {", " after(String.valueOf(value));", " }", " public void after(String string) {", " }", "}") .doTest(); } @Test public void stringLiteralThatLooksLikeAMethodCall() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"this.after(\\\"not actually() a method call\\\")\")", " @Deprecated", " public void before() {", " after(\"not actually() a method call\");", " }", " public void after(String string) {", " }", "}") .doTest(); } @Test public void tryStatement() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"try { int x = 0; } catch (RuntimeException e) {}\")", " @Deprecated", " // BUG: Diagnostic contains: InlineMe cannot inline complex statements", " public void before() {", " try { int x = 0; } catch (RuntimeException e) {}", " }", "}") .doTest(); } @Test public void noOpMethod() { helper .addSourceLines( "RpcClient.java", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class RpcClient {", " @InlineMe(replacement = \"\")", " @Deprecated", " // BUG: Diagnostic contains: cannot inline methods with more than 1 statement", " public void setDeadline(org.joda.time.Duration deadline) {}", " public void setDeadline(Duration deadline) {}", "}") .doTest(); } @Test public void instanceMethod_withConstant() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @InlineMe(replacement = \"this.after(Duration.ZERO);\", ", " imports = {\"java.time.Duration\"})", " @Deprecated", " public void before() {", " after(Duration.ZERO);", " }", " public void after(Duration duration) {", " }", "}") .doTest(); } @Test public void instanceMethod_withConstantStaticallyImported() { helper .addSourceLines( "Client.java", "import static java.time.Duration.ZERO;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @InlineMe(replacement = \"this.after(ZERO);\", ", " staticImports = {\"java.time.Duration.ZERO\"})", " @Deprecated", " public void before() {", " after(ZERO);", " }", " public void after(Duration duration) {", " }", "}") .doTest(); } @Test public void staticMethod_typeParameter() { helper .addSourceLines( "Client.java", "package com.google.foo;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(", " replacement = \"Client.after()\",", " imports = {\"com.google.foo.Client\"})", " public static <T> T before() {", " return after();", " }", " public static <T> T after() {", " return (T) null;", " }", "}") .doTest(); } private static final Pattern INFERRED_FROM_BODY = Pattern.compile("InferredFromBody: .*\\.Builder]"); @Test public void allowingNestedClassImport() { helper .addSourceLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " public static final class Builder {", " @InlineMe(", " replacement = \"this.setDeadline(Client.Builder.parseDeadline(deadline));\",", " imports = {\"com.google.frobber.Client\"})", " @Deprecated", // TODO(b/176094331): we shouldn't need to import `Builder` " // BUG: Diagnostic matches: BAR", " public void setDeadline(String deadline) {", " setDeadline(parseDuration(deadline));", " }", " public void setDeadline(Duration deadline) {", " }", " public static Duration parseDuration(String string) {", " return Duration.parse(string);", " }", " }", "}") .expectErrorMessage("BAR", INFERRED_FROM_BODY.asPredicate()::test) .doTest(); } @Test public void nestedClassWithInstanceMethodCallingStatic_implementationQualified() { helper .addSourceLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " public static final class Builder {", " @InlineMe(", " replacement = \"this.setDeadline(Client.Builder.parseDuration(deadline));\",", " imports = {\"com.google.frobber.Client\"})", " @Deprecated", " public void setDeadline(String deadline) {", " setDeadline(Client.Builder.parseDuration(deadline));", " }", " public void setDeadline(Duration deadline) {", " }", " public static Duration parseDuration(String string) {", " return Duration.parse(string);", " }", " }", "}") .doTest(); } @Test public void assignmentToPrivateField() { helper .addSourceLines( "RpcClient.java", "import com.google.errorprone.annotations.InlineMe;", "public final class RpcClient {", " private String name;", " @InlineMe(replacement = \"this.name = name;\")", " @Deprecated", " // BUG: Diagnostic contains: deprecated or less visible API elements: this.name", " public void setName(String name) {", " this.name = name;", " }", "}") .doTest(); } @Test public void assignmentToPublicField() { helper .addSourceLines( "RpcClient.java", "import com.google.errorprone.annotations.InlineMe;", "public final class RpcClient {", " public String name;", " @InlineMe(replacement = \"this.name = name;\")", " @Deprecated", " public void setName(String name) {", " this.name = name;", " }", "}") .doTest(); } @Test public void suppressionWithSuppressWarningsDoesntWork() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @SuppressWarnings(\"InlineMeValidator\")", " @Deprecated", " @InlineMe(replacement = \"Client.create()\", imports = \"foo.Client\")", " // BUG: Diagnostic contains: cannot be applied", " public Client() {}", " ", " public static Client create() { return new Client(); }", "}") .doTest(); } @Test public void suppressionWithCustomAnnotationWorks() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import com.google.errorprone.annotations." + "InlineMeValidationDisabled;", "public final class Client {", " @InlineMeValidationDisabled(\"Migrating to factory method\")", " @Deprecated", " @InlineMe(replacement = \"Client.create()\", imports = \"foo.Client\")", " public Client() {}", " ", " public static Client create() { return new Client(); }", "}") .doTest(); } @Test public void varargsPositive() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.after(inputs)\")", " public void before(int... inputs) {", " after(inputs);", " }", "", " @Deprecated", " @InlineMe(replacement = \"this.after(inputs)\")", " public void extraBefore(int first, int... inputs) {", " after(inputs);", " }", "", " @Deprecated", " @InlineMe(replacement = \"this.after(first)\")", " public void ignoringVarargs(int first, int... inputs) {", " after(first);", // Sneaky! " }", " public void after(int... inputs) {}", "}") .doTest(); } @Test public void varargs_toNonVarargsMethod() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.after(inputs)\")", " // BUG: Diagnostic contains: varargs", " public void before(int... inputs) {", " after(inputs);", " }", " public void after(int[] inputs) {}", "}") .doTest(); } @Test public void emptyMethod() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"return\")", " // BUG: Diagnostic contains: no-op", " public void noOp() {", " return;", " }", "}") .doTest(); } @Test public void multiply() { helper .addSourceLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"x * y\")", " public final int multiply(int x, int y) {", " return x * y;", " }", "}") .doTest(); } @Test public void customInlineMe() { helper .addSourceLines( "InlineMe.java", // "package bespoke;", "public @interface InlineMe {", " String replacement();", " String[] imports() default {};", " String[] staticImports() default {};", "}") .addSourceLines( "Client.java", "import bespoke.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.foo3(value)\")", // should be foo2(value)!!! " // BUG: Diagnostic contains: @InlineMe(replacement = \"this.foo2(value)\")", " public void foo1(String value) {", " foo2(value);", " }", " public void foo2(String value) {", " }", "}") .doTest(); } private BugCheckerRefactoringTestHelper getHelperInCleanupMode() { return BugCheckerRefactoringTestHelper.newInstance(Validator.class, getClass()) .setArgs("-XepOpt:" + Validator.CLEANUP_INLINE_ME_FLAG + "=true"); } }
25,087
32.85695
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.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.inlineme; import static com.google.errorprone.bugpatterns.inlineme.Inliner.PREFIX_FLAG; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.scanner.ScannerSupplier; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for the {@link Inliner}. */ @RunWith(JUnit4.class) public class InlinerTest { /* We expect that all @InlineMe annotations we try to use as inlineable targets are valid, so we run both checkers here. If the Validator trips on a method, we'll suggest some replacement which should trip up the checker. */ private final BugCheckerRefactoringTestHelper refactoringTestHelper = BugCheckerRefactoringTestHelper.newInstance( ScannerSupplier.fromBugCheckerClasses(Inliner.class, Validator.class), getClass()); @Test public void instanceMethod_withThisLiteral() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.foo2(value)\")", " public void foo1(String value) {", " foo2(value);", " }", " public void foo2(String value) {", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.foo1(\"frobber!\");", " client.foo1(\"don't change this!\");", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.foo2(\"frobber!\");", " client.foo2(\"don't change this!\");", " }", "}") .doTest(); } @Test public void nestedQuotes() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.after(foo)\")", " public String before(String foo) {", " return after(foo);", " }", " public String after(String foo) {", " return \"frobber\";", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " String result = client.before(\"\\\"\");", // "\"" - a single quote character " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " String result = client.after(\"\\\"\");", " }", "}") .doTest(); } @Test public void method_withParamSwap() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.after(paramB, paramA)\")", " public void before(String paramA, String paramB) {", " after(paramB, paramA);", " }", " public void after(String paramB, String paramA) {", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "import java.time.Duration;", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " String a = \"a\";", " String b = \"b\";", " client.before(a, b);", " }", "}") .addOutputLines( "out/Caller.java", "import java.time.Duration;", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " String a = \"a\";", " String b = \"b\";", " client.after(b, a);", " }", "}") .doTest(); } @Test public void method_withReturnStatement() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.after()\")", " public String before() {", " return after();", " }", " public String after() {", " return \"frobber\";", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " String result = client.before();", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " String result = client.after();", " }", "}") .doTest(); } @Test public void staticMethod_explicitTypeParam() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.foo;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(", " replacement = \"Client.after()\",", " imports = {\"com.google.foo.Client\"})", " public static <T> T before() {", " return after();", " }", " public static <T> T after() {", " return (T) null;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "package com.google.foo;", "public final class Caller {", " public void doTest() {", " String str = Client.<String>before();", " }", "}") .addOutputLines( "out/Caller.java", "package com.google.foo;", "public final class Caller {", " public void doTest() {", // TODO(b/166285406): Client.<String>after(); " String str = Client.after();", " }", "}") .doTest(); } @Test public void instanceMethod_withConflictingImport() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " private Duration deadline = Duration.ofSeconds(5);", " @Deprecated", " @InlineMe(", " replacement = \"this.setDeadline(Duration.ofMillis(millis))\",", " imports = {\"java.time.Duration\"})", " public void setDeadline(long millis) {", " setDeadline(Duration.ofMillis(millis));", " }", " public void setDeadline(Duration deadline) {", " this.deadline = deadline;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "import org.joda.time.Duration;", "public final class Caller {", " public void doTest() {", " Duration jodaDuration = Duration.millis(42);", " Client client = new Client();", " client.setDeadline(42);", " }", "}") .addOutputLines( "out/Caller.java", "import org.joda.time.Duration;", "public final class Caller {", " public void doTest() {", " Duration jodaDuration = Duration.millis(42);", " Client client = new Client();", " client.setDeadline(java.time.Duration.ofMillis(42));", " }", "}") .doTest(); } @Test public void instanceMethod_withPartiallyQualifiedInnerType() { refactoringTestHelper .addInputLines( "A.java", "package com.google;", "public class A {", " public static class Inner {", " public static void foo() {", " }", " }", "}") .expectUnchanged() .addInputLines( "Client.java", "import com.google.A;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"A.Inner.foo()\", imports = \"com.google.A\")", " public void something() {", " A.Inner.foo();", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.something();", " }", "}") .addOutputLines( "out/Caller.java", "import com.google.A;", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " A.Inner.foo();", " }", "}") .doTest(); } @Test public void instanceMethod_withConflictingMethodNameAndParameterName() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " private long deadline = 5000;", " @Deprecated", " @InlineMe(replacement = \"this.millis(millis)\")", " public void setDeadline(long millis) {", " millis(millis);", " }", " public void millis(long millis) {", " this.deadline = millis;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.setDeadline(42);", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.millis(42);", " }", "}") .doTest(); } @Test public void staticMethod_withStaticImport_withImport() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.test;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(", " replacement = \"Client.after(value)\", ", " imports = {\"com.google.test.Client\"})", " public static void before(int value) {", " after(value);", " }", " public static void after(int value) {", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "import static com.google.test.Client.before;", "public final class Caller {", " public void doTest() {", " before(42);", " }", "}") .addOutputLines( "Caller.java", "import static com.google.test.Client.before;", "import com.google.test.Client;", "public final class Caller {", " public void doTest() {", " Client.after(42);", " }", "}") .doTest(); } // With the new suggester implementation, we always import the surrounding class, so the suggested // replacement here isn't considered valid. @Ignore("b/176439392") @Test public void staticMethod_withStaticImport_withStaticImportReplacement() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.test;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(", " replacement = \"after(value)\", ", " staticImports = {\"com.google.test.Client.after\"})", " public static void before(int value) {", " after(value);", " }", " public static void after(int value) {", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "import static com.google.test.Client.before;", "public final class Caller {", " public void doTest() {", " before(42);", " }", "}") .addOutputLines( "Caller.java", "import static com.google.test.Client.after;", "import static com.google.test.Client.before;", "public final class Caller {", " public void doTest() {", " after(42);", " }", "}") .doTest(); } @Test public void instanceMethodCalledBySubtype() { refactoringTestHelper .addInputLines( "Parent.java", "package com.google.test;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public class Parent {", " @Deprecated", " @InlineMe(", " replacement = \"this.after(Duration.ofMillis(value))\", ", " imports = {\"java.time.Duration\"})", " protected final void before(int value) {", " after(Duration.ofMillis(value));", " }", " protected void after(Duration value) {", " }", "}") .expectUnchanged() .addInputLines( "Child.java", "package com.google.test;", "public final class Child extends Parent {", " public void doTest() {", " before(42);", " }", "}") .addOutputLines( "Child.java", "package com.google.test;", "import java.time.Duration;", "public final class Child extends Parent {", " public void doTest() {", " after(Duration.ofMillis(42));", " }", "}") .doTest(); } @Test public void constructorCalledBySubtype() { refactoringTestHelper .addInputLines( "Parent.java", "package com.google.test;", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public class Parent {", " @Deprecated", " @InlineMe(", " replacement = \"this(Duration.ofMillis(value))\", ", " imports = {\"java.time.Duration\"})", " protected Parent(int value) {", " this(Duration.ofMillis(value));", " }", " protected Parent(Duration value) {", " }", "}") .expectUnchanged() .addInputLines( "Child.java", "package com.google.test;", "public final class Child extends Parent {", " public Child() {", " super(42);", " }", "}") .addOutputLines( "Child.java", "package com.google.test;", "import java.time.Duration;", "public final class Child extends Parent {", " public Child() {", " super(Duration.ofMillis(42));", " }", "}") .doTest(); } @Test public void fluentMethodChain() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.baz()\")", " public Client foo() {", " return baz();", " }", " @Deprecated", " @InlineMe(replacement = \"this.baz()\")", " public Client bar() {", " return baz();", " }", " public Client baz() {", " return this;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client().foo().bar();", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client().baz().baz();", " }", "}") .doTest(); } @Test public void inliningWithField() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.setTimeout(Duration.ZERO)\", imports =" + " {\"java.time.Duration\"})", " public void clearTimeout() {", " setTimeout(Duration.ZERO);", " }", " public void setTimeout(Duration timeout) {", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " new Client().clearTimeout();", " }", "}") .addOutputLines( "out/Caller.java", "import java.time.Duration;", "public final class Caller {", " public void doTest() {", " new Client().setTimeout(Duration.ZERO);", " }", "}") .doTest(); } @Test public void returnThis() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this\")", " public Client noOp() {", " return this;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client = client.noOp();", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client = client;", " }", "}") .doTest(); } @Test public void returnThis_preChained() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this\")", " public Client noOp() {", " return this;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client().noOp();", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " }", "}") .doTest(); } @Test public void returnThis_postChained() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this\")", " public Client noOp() {", " return this;", " }", " public void bar() {", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " new Client().noOp().bar();", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " new Client().bar();", " }", "}") .doTest(); } @Test public void returnThis_alone() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this\")", " public Client noOp() {", " return this;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.noOp();", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " }", "}") .doTest(); } @Test public void inlineUnvalidatedInline() { refactoringTestHelper .addInputLines( "Client.java", "package foo;", "import com.google.errorprone.annotations.InlineMe;", "import com.google.errorprone.annotations.InlineMeValidationDisabled;", "public final class Client {", " @Deprecated", " @InlineMeValidationDisabled(\"Migrating to factory method\")", " @InlineMe(replacement = \"Client.create()\", imports = \"foo.Client\")", " public Client() {}", " ", // The Inliner wants to inline the body of this factory method to the factory method :) " @SuppressWarnings(\"InlineMeInliner\")", " public static Client create() { return new Client(); }", "}") .expectUnchanged() .addInputLines( "Caller.java", "import foo.Client;", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " }", "}") .addOutputLines( "out/Caller.java", "import foo.Client;", "public final class Caller {", " public void doTest() {", " Client client = Client.create();", " }", "}") .doTest(); } @Test public void inlineUnvalidatedInlineMessage() { CompilationTestHelper.newInstance(Inliner.class, getClass()) .addSourceLines( "Client.java", "package foo;", "import com.google.errorprone.annotations.InlineMe;", "import com.google.errorprone.annotations.InlineMeValidationDisabled;", "public final class Client {", " @Deprecated", " @InlineMeValidationDisabled(\"Migrating to factory method\")", " @InlineMe(replacement = \"Client.create()\", imports = \"foo.Client\")", " public Client() {}", " ", // The Inliner wants to inline the body of this factory method to the factory method :) " @SuppressWarnings(\"InlineMeInliner\")", " public static Client create() { return new Client(); }", "}") .addSourceLines( "Caller.java", "import foo.Client;", "public final class Caller {", " public void doTest() {", " // BUG: Diagnostic contains: NOTE: this is an unvalidated inlining!" + " Reasoning: Migrating to factory method", " Client client = new Client();", " }", "}") .doTest(); } @Test public void varargs() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.after(inputs)\")", " public void before(int... inputs) {", " after(inputs);", " }", " public void after(int... inputs) {}", " @Deprecated", " @InlineMe(replacement = \"this.after(inputs)\")", " public void extraBefore(int first, int... inputs) {", " after(inputs);", " }", " @Deprecated", " @InlineMe(replacement = \"this.after(first)\")", " public void ignoreVarargs(int first, int... inputs) {", " after(first);", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.before(1);", " client.before();", " client.before(1, 2, 3);", " client.extraBefore(42, 1);", " client.extraBefore(42);", " client.extraBefore(42, 1, 2, 3);", " client.ignoreVarargs(42, 1);", " client.ignoreVarargs(42);", " client.ignoreVarargs(42, 1, 2, 3);", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.after(1);", " client.after();", " client.after(1, 2, 3);", " client.after(1);", " client.after();", " client.after(1, 2, 3);", " client.after(42);", " client.after(42);", " client.after(42);", " }", "}") .doTest(); } @Test public void varargsWithPrecedingElements() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.after(first, inputs)\")", " public void before(int first, int... inputs) {", " after(first, inputs);", " }", " public void after(int first, int... inputs) {}", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.before(1);", " client.before(1, 2, 3);", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.after(1);", " client.after(1, 2, 3);", " }", "}") .doTest(); } @Test public void replaceWithJustParameter() { bugCheckerWithCheckFixCompiles() .allowBreakingChanges() .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "import java.time.Duration;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"x\")", " public final int identity(int x) {", " return x;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " int x = client.identity(42);", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", // TODO(b/180976346): replacements of the form that terminate in a parameter by itself // don't work with the new replacement tool, but this is uncommon enough " int x = client.identity(42);", " }", "}") .doTest(); } @Test public void orderOfOperations() { bugCheckerWithCheckFixCompiles() .allowBreakingChanges() .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"x * y\")", " public int multiply(int x, int y) {", " return x * y;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " int x = client.multiply(5, 10);", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", // TODO(kak): hmm, why don't we inline this? " int x = client.multiply(5, 10);", " }", "}") .doTest(); } @Test public void orderOfOperationsWithParamAddition() { bugCheckerWithCheckFixCompiles() .allowBreakingChanges() .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"x * y\")", " public int multiply(int x, int y) {", " return x * y;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " int x = client.multiply(5 + 3, 10);", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", // TODO(kak): hmm, why don't we inline this? " int x = client.multiply(5 + 3, 10);", " }", "}") .doTest(); } @Test public void orderOfOperationsWithTrailingOperand() { bugCheckerWithCheckFixCompiles() .allowBreakingChanges() .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"x * y\")", " public int multiply(int x, int y) {", " return x * y;", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " int x = client.multiply(5 + 3, 10) * 5;", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", // TODO(kak): hmm, why don't we inline this? " int x = client.multiply(5 + 3, 10) * 5;", " }", "}") .doTest(); } @Test public void booleanParameterWithInlineComment() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"this.after(/* isAdmin = */ isAdmin)\")", " @Deprecated", " public void before(boolean isAdmin) {", " after(/* isAdmin= */ isAdmin);", " }", " public void after(boolean isAdmin) {", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.before(false);", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", // TODO(b/189535612): this is a bug! " client.after(/* false = */ false);", " }", "}") .doTest(); } @Test public void trailingSemicolon() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(replacement = \"this.after(/* foo= */ isAdmin);;;;\")", " @Deprecated", " public boolean before(boolean isAdmin) {", " return after(/* foo= */ isAdmin);", " }", " public boolean after(boolean isAdmin) { return isAdmin; }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " boolean x = (client.before(false) || true);", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " boolean x = (client.after(/* false = */ false) || true);", " }", "}") .doTest(); } @Test public void customInlineMe() { refactoringTestHelper .addInputLines( "InlineMe.java", // "package bespoke;", "public @interface InlineMe {", " String replacement();", " String[] imports() default {};", " String[] staticImports() default {};", "}") .expectUnchanged() .addInputLines( "Client.java", "import bespoke.InlineMe;", "public final class Client {", " @Deprecated", " @InlineMe(replacement = \"this.foo2(value)\")", " public void foo1(String value) {", " foo2(value);", " }", " public void foo2(String value) {", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.foo1(\"frobber!\");", " client.foo1(\"don't change this!\");", " }", "}") .addOutputLines( "out/Caller.java", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " client.foo2(\"frobber!\");", " client.foo2(\"don't change this!\");", " }", "}") .doTest(); } @Test public void ternaryInlining_b266848535() { refactoringTestHelper .addInputLines( "Client.java", "import com.google.common.collect.ImmutableList;", "import com.google.errorprone.annotations.InlineMe;", "import java.util.Optional;", "public final class Client {", " @Deprecated", " @InlineMe(", " replacement = ", "\"this.getList().isEmpty() ? Optional.empty() : Optional.of(this.getList().get(0))\",", " imports = {\"java.util.Optional\"})", " public Optional<String> getFoo() {", " return getList().isEmpty() ? Optional.empty() : Optional.of(getList().get(0));", " }", " public ImmutableList<String> getList() {", " return ImmutableList.of();", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "import static com.google.common.truth.Truth.assertThat;", "public final class Caller {", " public void doTest() {", " Client client = new Client();", " assertThat(client.getFoo().get()).isEqualTo(\"hi\");", " }", "}") .addOutputLines( "out/Caller.java", "import static com.google.common.truth.Truth.assertThat;", "import java.util.Optional;", "public final class Caller {", " public void doTest() {", " Client client = new Client();", // TODO(b/266848535): this is a bug; we need to add parens around the ternary " assertThat(", " client.getList().isEmpty() ", " ? Optional.empty()", " : Optional.of(client.getList().get(0)).get())", " .isEqualTo(\"hi\");", " }", "}") .doTest(); } @Test public void varArgs_b268215956() { refactoringTestHelper .addInputLines( "Client.java", "package com.google.foo;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " @InlineMe(", " replacement = \"Client.execute2(format, args)\",", " imports = {\"com.google.foo.Client\"})", " public static void execute1(String format, Object... args) {", " execute2(format, args);", " }", " public static void execute2(String format, Object... args) {", " // do nothing", " }", "}") .expectUnchanged() .addInputLines( "Caller.java", "import com.google.foo.Client;", "public final class Caller {", " public void doTest() {", " Client.execute1(\"hi %s\");", " }", "}") .addOutputLines( "Caller.java", "import com.google.foo.Client;", "public final class Caller {", " public void doTest() {", " Client.execute2(\"hi %s\");", " }", "}") .doTest(); } private BugCheckerRefactoringTestHelper bugCheckerWithPrefixFlag(String prefix) { return BugCheckerRefactoringTestHelper.newInstance(Inliner.class, getClass()) .setArgs("-XepOpt:" + PREFIX_FLAG + "=" + prefix); } private BugCheckerRefactoringTestHelper bugCheckerWithCheckFixCompiles() { return BugCheckerRefactoringTestHelper.newInstance(Inliner.class, getClass()) .setArgs("-XepOpt:InlineMe:CheckFixCompiles=true"); } }
42,235
33.033844
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/ExtendsObjectTest.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.nullness; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link ExtendsObject}. */ @RunWith(JUnit4.class) public final class ExtendsObjectTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(ExtendsObject.class, getClass()); @Test public void positive() { helper .addInputLines( "Test.java", // "class Foo<T extends Object> {}") .addOutputLines( "Test.java", // "import org.checkerframework.checker.nullness.qual.NonNull;", "class Foo<T extends @NonNull Object> {}") .doTest(); } @Test public void extendsParameterWithObjectErasure_noFinding() { helper .addInputLines( "Test.java", // "class Foo<S, T extends S> {}") .expectUnchanged() .doTest(); } @Test public void negative() { helper .addInputLines( "Test.java", // "import org.checkerframework.checker.nullness.qual.NonNull;", "class Foo<T extends @NonNull Object> {}") .expectUnchanged() .doTest(); } }
1,915
28.9375
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/UnnecessaryCheckNotNullTest.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.nullness; import static com.google.common.truth.Truth.assertWithMessage; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.matchers.CompilerBasedAbstractTest; import com.google.errorprone.scanner.Scanner; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link UnnecessaryCheckNotNull} check. * * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class UnnecessaryCheckNotNullTest extends CompilerBasedAbstractTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnnecessaryCheckNotNull.class, getClass()); @Test public void positive_newClass() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.base.Preconditions;", "import com.google.common.base.Verify;", "import java.util.Objects;", "class Test {", " void positive_checkNotNull() {", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Preconditions.checkNotNull(new String(\"\"));", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Preconditions.checkNotNull(new String(\"\"), new Object());", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Preconditions.checkNotNull(new String(\"\"), \"Message %s\", \"template\");", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "String pa = Preconditions.checkNotNull(new String(\"\"));", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "String pb = Preconditions.checkNotNull(new String(\"\"), new Object());", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "String pc = Preconditions.checkNotNull(new String(\"\"), \"Message %s\"," + " \"template\");", "}", " void positive_verifyNotNull() {", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Verify.verifyNotNull(new String(\"\"));", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Verify.verifyNotNull(new String(\"\"), \"Message\");", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Verify.verifyNotNull(new String(\"\"), \"Message %s\", \"template\");", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "String va = Verify.verifyNotNull(new String(\"\"));", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "String vb = Verify.verifyNotNull(new String(\"\"), \"Message\");", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "String vc = Verify.verifyNotNull(new String(\"\"), \"Message %s\", \"template\");", "}", " void positive_requireNonNull() {", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Objects.requireNonNull(new String(\"\"));", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Objects.requireNonNull(new String(\"\"), \"Message\");", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "String va = Objects.requireNonNull(new String(\"\"));", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "String vb = Objects.requireNonNull(new String(\"\"), \"Message\");", "}", "}") .doTest(); } @Test public void positive_newArray() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.base.Preconditions;", "import com.google.common.base.Verify;", "import java.util.Objects;", "class Test {", " void positive_checkNotNull() {", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Preconditions.checkNotNull(new int[3]);", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Preconditions.checkNotNull(new int[]{1, 2, 3});", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Preconditions.checkNotNull(new int[5][2]);", "}", " void positive_verifyNotNull() {", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Verify.verifyNotNull(new int[3]);", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Verify.verifyNotNull(new int[]{1, 2, 3});", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Verify.verifyNotNull(new int[5][2]);", "}", " void positive_requireNonNull() {", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Objects.requireNonNull(new int[3]);", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Objects.requireNonNull(new int[]{1, 2, 3});", "// BUG: Diagnostic contains: UnnecessaryCheckNotNull", "Objects.requireNonNull(new int[5][2]);", "}", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "import com.google.common.base.Preconditions;", "import com.google.common.base.Verify;", "import java.util.Objects;", "class Test {", "void negative() {", "Preconditions.checkNotNull(new String(\"\").substring(0, 0));", "Verify.verifyNotNull(new String(\"\").substring(0, 0));", "Objects.requireNonNull(new String(\"\").substring(0, 0));", "}", "}") .doTest(); } @Test public void positiveCase() { compilationHelper.addSourceFile("UnnecessaryCheckNotNullPositiveCase.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("UnnecessaryCheckNotNullNegativeCase.java").doTest(); } @Test public void primitivePositiveCases() { compilationHelper.addSourceFile("UnnecessaryCheckNotNullPrimitivePositiveCases.java").doTest(); } @Test public void primitiveNegativeCases() { compilationHelper.addSourceFile("UnnecessaryCheckNotNullPrimitiveNegativeCases.java").doTest(); } @Test public void getVariableUses() { writeFile("A.java", "public class A {", " public String b;", " void foo() {}", "}"); writeFile( "B.java", "public class B {", " A my;", " B bar() { return null; }", " void foo(String x, A a) {", " x.trim().intern();", " a.b.trim().intern();", " this.my.foo();", " my.foo();", " this.bar();", " String.valueOf(0);", " java.lang.String.valueOf(1);", " bar().bar();", " System.out.println();", " a.b.indexOf(x.substring(1));", " }", "}"); TestScanner scanner = new TestScanner.Builder() .add("x.trim().intern()", "x") .add("a.b.trim().intern()", "a") .add("this.my.foo()", "this") .add("my.foo()", "my") .add("this.bar()", "this") .add("String.valueOf(0)") .add("java.lang.String.valueOf(1)") .add("bar().bar()") .add("System.out.println()") .add("a.b.indexOf(x.substring(1))", "a", "x") .build(); assertCompiles(scanner); scanner.assertFoundAll(); } // TODO(mdempsky): Make this more reusable. private static class TestScanner extends Scanner { private static class Match { private final ImmutableList<String> expected; private boolean found = false; private Match(String... expected) { this.expected = ImmutableList.copyOf(expected); } } private static class Builder { private final ImmutableMap.Builder<String, Match> builder = ImmutableMap.builder(); @CanIgnoreReturnValue public Builder add(String expression, String... expected) { builder.put(expression, new Match(expected)); return this; } public TestScanner build() { return new TestScanner(builder.buildOrThrow()); } } private final ImmutableMap<String, Match> matches; private TestScanner(ImmutableMap<String, Match> matches) { this.matches = matches; } @Override public Void visitExpressionStatement(ExpressionStatementTree node, VisitorState state) { ExpressionTree expression = node.getExpression(); Match match = matches.get(expression.toString()); if (match != null) { assertMatch(expression, match.expected); match.found = true; } return super.visitExpressionStatement(node, state); } private static void assertMatch(ExpressionTree node, List<String> expected) { List<IdentifierTree> uses = UnnecessaryCheckNotNull.getVariableUses(node); assertWithMessage("variables used in " + node) .that(Lists.transform(uses, Functions.toStringFunction())) .isEqualTo(expected); } public void assertFoundAll() { for (Map.Entry<String, Match> entry : matches.entrySet()) { assertWithMessage("found " + entry.getKey()).that(entry.getValue().found).isTrue(); } } } }
10,548
37.783088
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/NullArgumentForNonNullParameterTest.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.nullness; 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 NullArgumentForNonNullParameter}Test */ @RunWith(JUnit4.class) public class NullArgumentForNonNullParameterTest { private final CompilationTestHelper conservativeHelper = CompilationTestHelper.newInstance(NullArgumentForNonNullParameter.class, getClass()); private final CompilationTestHelper aggressiveHelper = CompilationTestHelper.newInstance(NullArgumentForNonNullParameter.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); private final BugCheckerRefactoringTestHelper aggressiveRefactoringHelper = BugCheckerRefactoringTestHelper.newInstance(NullArgumentForNonNullParameter.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); @Test public void positivePrimitive() { conservativeHelper .addSourceLines( "Foo.java", "import java.util.Optional;", "class Foo {", " void consume(int i) {}", " void foo(Optional<Integer> o) {", " // BUG: Diagnostic contains: ", " consume(o.orElse(null));", " }", "}") .doTest(); } @Test public void positiveAnnotatedNonnullAggressive() { aggressiveHelper .addSourceLines( "Foo.java", "import javax.annotation.Nonnull;", "class Foo {", " void consume(@Nonnull String s) {}", " void foo() {", " // BUG: Diagnostic contains: ", " consume(null);", " }", "}") .doTest(); } @Test public void negativeAnnotatedNonnullConservative() { conservativeHelper .addSourceLines( "Foo.java", "import javax.annotation.Nonnull;", "class Foo {", " void consume(@Nonnull String s) {}", " void foo() {", " consume(null);", " }", "}") .doTest(); } @Test public void positiveJavaOptionalOf() { conservativeHelper .addSourceLines( "Foo.java", "import java.util.Optional;", "class Foo {", " void foo() {", " // BUG: Diagnostic contains: ", " Optional.of(null);", " }", "}") .doTest(); } @Test public void positiveGuavaOptionalOf() { conservativeHelper .addSourceLines( "Foo.java", "import com.google.common.base.Optional;", "class Foo {", " void foo() {", " // BUG: Diagnostic contains: ", " Optional.of(null);", " }", "}") .doTest(); } @Test public void positiveGuavaImmutableSetOf() { conservativeHelper .addSourceLines( "Foo.java", "import com.google.common.collect.ImmutableSet;", "class Foo {", " void foo() {", " // BUG: Diagnostic contains: ", " ImmutableSet.of(null);", " }", "}") .doTest(); } @Test public void positiveGuavaImmutableSetBuilderAdd() { conservativeHelper .addSourceLines( "Foo.java", "import com.google.common.collect.ImmutableSet;", "class Foo {", " void foo(boolean b) {", " // BUG: Diagnostic contains: ", // We use a ternary to avoid: // "non-varargs call of varargs method with inexact argument type for last parameter" " ImmutableSet.builder().add(b ? 1 : null);", " }", "}") .doTest(); } @Test public void positiveArgumentCaptorForClass() { conservativeHelper .addSourceLines( "Foo.java", "import org.mockito.ArgumentCaptor;", "class Foo {", " void foo() {", " // BUG: Diagnostic contains: ", " ArgumentCaptor.forClass(null);", " }", "}") .doTest(); } @Test public void negativeNullMarkedComGoogleCommonButNullable() { conservativeHelper .addSourceLines( "Foo.java", "import com.google.common.collect.ImmutableSet;", "class Foo {", " void foo() {", " ImmutableSet.of().contains(null);", " }", "}") .doTest(); } @Test public void positiveNullMarkedOtherPackageAggressive() { aggressiveHelper .addSourceLines( "Foo.java", "import org.jspecify.nullness.NullMarked;", "@NullMarked", "class Foo {", " void consume(String s) {}", " void foo() {", " // BUG: Diagnostic contains: ", " consume(null);", " }", "}") .doTest(); } @Test public void negativeNullMarkedNonComGoogleCommonPackageConservative() { conservativeHelper .addSourceLines( "Foo.java", "import org.jspecify.nullness.NullMarked;", "@NullMarked", "class Foo {", " void consume(String s) {}", " void foo() {", " consume(null);", " }", "}") .doTest(); } @Test public void negativeNullMarkedTypeVariable() { aggressiveHelper .addSourceLines( "Foo.java", "import com.google.common.collect.ConcurrentHashMultiset;", "class Foo {", " void foo() {", " ConcurrentHashMultiset.create().add(null);", " }", "}") .doTest(); } }
6,591
28.693694
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.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.nullness; 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 ReturnMissingNullable}Test */ @RunWith(JUnit4.class) public class ReturnMissingNullableTest { @Test public void literalNullReturn() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage(boolean b) {", " if (b) {", " // BUG: Diagnostic contains: @Nullable", " return null;", " } else {", " return \"negative\";", " }", " }", "}") .doTest(); } @Test public void parenthesizedLiteralNullReturn() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage(boolean b) {", " if (b) {", " // BUG: Diagnostic contains: @Nullable", " return (null);", " } else {", " return \"negative\";", " }", " }", "}") .doTest(); } @Test public void assignmentOfLiteralNullReturn() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " String cachedMessage;", " public String getMessage(boolean b) {", " if (b) {", " // BUG: Diagnostic contains: @Nullable", " return cachedMessage = null;", " } else {", " return \"negative\";", " }", " }", "}") .doTest(); } @Test public void castLiteralNullReturn() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage(boolean b) {", " if (b) {", " // BUG: Diagnostic contains: @Nullable", " return (String) null;", " } else {", " return \"negative\";", " }", " }", "}") .doTest(); } @Test public void conditionalLiteralNullReturn() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage(int x) {", " // BUG: Diagnostic contains: @Nullable", " return x >= 0 ? null : \"negative\";", " }", "}") .doTest(); } @Test public void parenthesizedConditionalLiteralNullReturn() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage(int x) {", " // BUG: Diagnostic contains: @Nullable", " return (x >= 0 ? null : \"negative\");", " }", "}") .doTest(); } @Test public void switchExpressionTree() { assumeTrue(RuntimeVersion.isAtLeast12()); createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage(int x) {", " // BUG: Diagnostic contains: @Nullable", " return switch (x) {", " case 0 -> null;", " default -> \"non-zero\";", " };", " }", "}") .doTest(); } @Test public void switchExpressionTree_negative() { assumeTrue(RuntimeVersion.isAtLeast12()); createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage(int x) {", " return switch (x) {", " case 0 -> \"zero\";", " default -> \"non-zero\";", " };", " }", "}") .doTest(); } @Test public void switchStatement() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage(int x) {", " switch (x) {", " case 0:", " // BUG: Diagnostic contains: @Nullable", " return null;", " default:", " return \"non-zero\";", " }", " }", "}") .doTest(); } @Test public void switchStatement_negative() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage(int x) {", " switch (x) {", " case 0:", " return \"zero\";", " default:", " return \"non-zero\";", " }", " }", "}") .doTest(); } @Test public void voidReturn() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object get() {", " // BUG: Diagnostic contains: @Nullable", " return getVoid();", " }", " abstract Void getVoid();", "}") .doTest(); } @Test public void subtypeOfVoidReturn() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object get(Supplier<? extends Void> s) {", " // BUG: Diagnostic contains: @Nullable", " return s.get();", " }", " interface Supplier<T> {", " T get();", " }", "}") .doTest(); } @Test public void staticFinalFieldAboveUsage() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " static final Object NULL = null;", " Object get() {", " // BUG: Diagnostic contains: @Nullable", " return NULL;", " }", "}") .doTest(); } @Test public void staticFinalFieldBelowUsage() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object get() {", " // BUG: Diagnostic contains: @Nullable", " return NULL;", " }", " static final Object NULL = null;", "}") .doTest(); } @Test public void instanceFinalField() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " final Object nullObject = null;", " Object get() {", " // BUG: Diagnostic contains: @Nullable", " return nullObject;", " }", "}") .doTest(); } @Test public void memberSelectFinalField() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " final Object nullObject = null;", " Object get() {", " // BUG: Diagnostic contains: @Nullable", " return this.nullObject;", " }", "}") .doTest(); } @Test public void multipleFilesFinalField() { createCompilationTestHelper() .addSourceLines( "Foo.java", "class Foo {", " final Object nullObject = null;", " Object get() {", " // BUG: Diagnostic contains: @Nullable", " return nullObject;", " }", "}") .addSourceLines( "Bar.java", "class Bar {", " final Object nullObject = null;", " Object get() {", " // BUG: Diagnostic contains: @Nullable", " return nullObject;", " }", "}") .doTest(); } @Test public void voidField() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Void nullObject;", " Object get() {", " // BUG: Diagnostic contains: @Nullable", " return nullObject;", " }", "}") .doTest(); } @Test public void typeAnnotatedArrayElement() { createRefactoringTestHelper() .addInputLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " @Nullable String[] getMessage(boolean b, String[] s) {", " return b ? s : null;", " }", "}") .addOutputLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " @Nullable String @Nullable [] getMessage(boolean b, String[] s) {", " return b ? s : null;", " }", "}") .doTest(); } @Test public void testTypeAnnotatedMultidimensionalArrayElement() { createRefactoringTestHelper() .addInputLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " String [] @Nullable [] getMessage(boolean b, String[][] s) {", " return b ? s : null;", " }", "}") .addOutputLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " String @Nullable [] @Nullable [] getMessage(boolean b, String[][] s) {", " return b ? s : null;", " }", "}") .doTest(); } @Test public void finalLocalVariable() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object get() {", " final Object nullObject = null;", " // BUG: Diagnostic contains: @Nullable", " return nullObject;", " }", "}") .doTest(); } @Test public void effectivelyFinalLocalVariable() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object get() {", " Object nullObject = null;", " // BUG: Diagnostic contains: @Nullable", " return nullObject;", " }", "}") .doTest(); } @Test public void finalLocalVariableComplexTree() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object get(boolean b1, boolean b2, Object someObject) {", " final Object nullObject = null;", " // BUG: Diagnostic contains: @Nullable", " return (b1 ? someObject : b2 ? nullObject : \"\");", " }", "}") .doTest(); } @Test public void returnXIfXIsNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object foo(Object o) {", " // BUG: Diagnostic contains: @Nullable", " return (o == null ? o : \"\");", " }", "}") .doTest(); } @Test public void returnXUnlessXIsXNotNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object foo(Object o) {", " // BUG: Diagnostic contains: @Nullable", " return (o != null ? \"\" : o);", " }", "}") .doTest(); } @Test public void returnXInsideIfNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object foo(Object o) {", " if (o == null) {", " // BUG: Diagnostic contains: @Nullable", " return o;", " }", " return \"\";", " }", "}") .doTest(); } @Test public void returnXInsideElseOfNotNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object foo(Object o) {", " if (o != null) {", " return \"\";", " } else {", " // BUG: Diagnostic contains: @Nullable", " return o;", " }", " }", "}") .doTest(); } @Test public void returnFieldInsideIfNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object o;", " Object foo() {", " if (o == null) {", " // BUG: Diagnostic contains: @Nullable", " return o;", " }", " return \"\";", " }", "}") .doTest(); } @Test public void otherVerify() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import static com.google.common.base.Verify.verify;", "class LiteralNullReturnTest {", " public String getMessage(boolean b) {", " verify(b);", " // BUG: Diagnostic contains: @Nullable", " return null;", " }", "}") .doTest(); } @Test public void orNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import com.google.common.base.Optional;", "class LiteralNullReturnTest {", " public String getMessage(Optional<String> m) {", " // BUG: Diagnostic contains: @Nullable", " return m.orNull();", " }", "}") .doTest(); } @Test public void orElseNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import java.util.Optional;", "class LiteralNullReturnTest {", " public String getMessage(Optional<String> m) {", " // BUG: Diagnostic contains: @Nullable", " return m.orElse(null);", " }", "}") .doTest(); } @Test public void emptyToNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import static com.google.common.base.Strings.emptyToNull;", "class LiteralNullReturnTest {", " public String getMessage(String s) {", " // BUG: Diagnostic contains: @Nullable", " return emptyToNull(s);", " }", "}") .doTest(); } @Test public void implementsMap() { createCompilationTestHelper() .addSourceLines( "NotMap.java", // "interface NotMap {", " Integer get(String o);", "}") .addSourceLines( "MyMap.java", "import java.util.Map;", "interface MyMap<K, V> extends Map<K, V>, NotMap {", " // BUG: Diagnostic contains: @Nullable", " @Override V get(Object o);", " // BUG: Diagnostic contains: @Nullable", " @Override V replace(K k, V v);", " @Override boolean replace(K k, V expect, V update);", " @Override Integer get(String o);", "}") .doTest(); } @Test public void implementsMapButAlwaysThrows() { createCompilationTestHelper() .addSourceLines( "MyMap.java", "import java.util.Map;", "abstract class MyMap<K, V> implements Map<K, V> {", " @Override", " public V put(K k, V v) {", " throw new UnsupportedOperationException();", " }", "}") .doTest(); } @Test public void implementsMapButDoNotCall() { createCompilationTestHelper() .addSourceLines( "MyMap.java", "import com.google.errorprone.annotations.DoNotCall;", "import java.util.Map;", "interface MyMap<K, V> extends Map<K, V> {", " @DoNotCall", " @Override", " V put(K k, V v);", "}") .doTest(); } @Test public void onlyIfAlreadyInScopeAndItIs() { createCompilationTestHelper() .setArgs("-XepOpt:Nullness:OnlyIfAnnotationAlreadyInScope=true") .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " String getMessage(boolean b) {", " // BUG: Diagnostic contains: @Nullable", " return b ? \"\" : null;", " }", "}") .doTest(); } @Test public void onlyStatementIsNullReturnButCannotBeOverridden() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public final class LiteralNullReturnTest {", " public String getMessage() {", " // BUG: Diagnostic contains: @Nullable", " return null;", " }", "}") .doTest(); } @Test public void arrayDeclaration() { createRefactoringTestHelper() .addInputLines( "in/com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class LiteralNullReturnTest {", " public String[] getMessage(boolean b) {", " return b ? null : new String[0];", " }", "}") .addOutputLines( "out/com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class LiteralNullReturnTest {", " @Nullable public String[] getMessage(boolean b) {", " return b ? null : new String[0];", " }", "}") .doTest(); } @Test public void arrayTypeUse() { createRefactoringTestHelper() .addInputLines( "in/com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " public String[] getMessage(boolean b) {", " return b ? null : new String[0];", " }", "}") .addOutputLines( "out/com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " public String @Nullable [] getMessage(boolean b) {", " return b ? null : new String[0];", " }", "}") .doTest(); } @Test public void arrayTypeUseTwoDimensional() { createRefactoringTestHelper() .addInputLines( "in/com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " public String[][] getMessage(boolean b, String[][] s) {", " return b ? null : s;", " }", "}") .addOutputLines( "out/com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " public String @Nullable [][] getMessage(boolean b, String[][] s) {", " return b ? null : s;", " }", "}") .doTest(); } @Test public void alreadyTypeAnnotatedInnerClassMemberSelect() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " class Inner {}", " LiteralNullReturnTest.@Nullable Inner getMessage(boolean b, Inner i) {", " return b ? i : null;", " }", "}") .doTest(); } @Test public void alreadyTypeAnnotatedInnerClassNonMemberSelect() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " class Inner {}", " @Nullable Inner getMessage(boolean b, Inner i) {", " return b ? i : null;", " }", "}") .doTest(); } @Test public void limitation_staticFinalFieldInitializedLater() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " static final Object NULL;", " static {", " NULL = null;", " }", " Object get() {", " return NULL;", " }", "}") .doTest(); } @Test public void limitation_instanceFinalFieldInitializedLater() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " final Object nullObject;", " {", " nullObject = null;", // or, more likely, in a constructor " }", " Object get() {", " return nullObject;", " }", "}") .doTest(); } @Test public void limitation_finalLocalVariableInitializedLater() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object get() {", " final Object nullObject;", " nullObject = null;", " return nullObject;", " }", "}") .doTest(); } @Test public void limitation_returnThisXInsideIfNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object o;", " Object foo() {", " if (this.o == null) {", " return this.o;", " }", " return \"\";", " }", "}") .doTest(); } @Test public void removeSuppressWarnings_removeNullnessReturnWarning() { createRefactoringTestHelper() .setArgs("-XepOpt:Nullness:RemoveSuppressWarnings=true") .addInputLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " @SuppressWarnings(\"nullness:return\")", " public String getMessage(boolean b) {", " if (b) {", " return null;", " } else {", " return \"negative\";", " }", " }", "}") .addOutputLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.jspecify.nullness.Nullable;", "public class LiteralNullReturnTest {", "", " public @Nullable String getMessage(boolean b) {", " if (b) {", " return null;", " } else {", " return \"negative\";", " }", " }", "}") .doTest(TEXT_MATCH); } @Test public void negativeCases_onlyStatementIsNullReturn() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage() {", " return null;", " }", "}") .doTest(); } @Test public void negativeCases_typeVariableUsage() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public <T> T getMessage(boolean b, T t) {", " return b ? null : t;", " }", "}") .doTest(); } @Test public void negativeCases_alreadyAnnotated() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class LiteralNullReturnTest {", " @Nullable", " public String getMessage(boolean b) {", " return b ? \"\" :null;", " }", "}") .doTest(); } @Test public void negativeCases_alreadyAnnotatedNullableDecl() { createCompilationTestHelper() .addSourceLines( "com/google/anno/my/NullableDecl.java", "package com.google.anno.my;", "public @interface NullableDecl {}") .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import com.google.anno.my.NullableDecl;", "public class LiteralNullReturnTest {", " @NullableDecl", " public String getMessage(boolean b) {", " return b ? \"\" :null;", " }", "}") .doTest(); } @Test public void negativeCases_alreadyAnnotatedNullableType() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.compatqual.NullableType;", "public class LiteralNullReturnTest {", " public @NullableType String getMessage(boolean b) {", " return b ? \"\" : null;", " }", "}") .doTest(); } @Test public void negativeCases_alreadyTypeAnnotated() { createCompilationTestHelper() .addSourceLines( "com/google/anno/my/Nullable.java", "package com.google.anno.my;", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Target;", "@Target({ElementType.TYPE_USE})", "public @interface Nullable {}") .addSourceLines( "com/google/errorprone/bugpatterns/nullness/TypeAnnoReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class TypeAnnoReturnTest {", " public @com.google.anno.my.Nullable String getMessage(boolean b) {", " return b ? \"\" : null;", " }", "}") .doTest(); } @Test public void negativeCases_alreadyDeclarationAnnotatedArray() { createAggressiveCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class LiteralNullReturnTest {", " @Nullable", " String[] getMessage(boolean b, String[] s) {", " return b ? s : null;", " }", "}") .doTest(); } @Test public void negativeCases_alreadyTypeAnnotatedArray() { createAggressiveCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " String @Nullable [] getMessage(boolean b, String[] s) {", " return b ? s : null;", " }", "}") .doTest(); } @Test public void negativeCases_alreadyTypeAnnotatedMemberSelect() { createAggressiveCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class LiteralNullReturnTest {", " java.lang.@Nullable String getMessage(boolean b) {", " return b ? \"\" : null;", " }", "}") .doTest(); } @Test public void negativeCases_checkNotNullNullableInput() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class NullReturnTest {", " @Nullable String message;", " public String getMessage() {", " return checkNotNull(message);", " }", // One style of "check not null" method, whose type argument is unannotated, and accepts // a @Nullable input. " private static <T> T checkNotNull(@Nullable T obj) {", " if (obj==null) throw new NullPointerException();", " return obj;", " }", "}") .doTest(); } @Test public void negativeCases_nonNullArrayWithNullableElements() { createCompilationTestHelper() .addSourceLines( "com/google/anno/my/Nullable.java", "package com.google.anno.my;", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Target;", "@Target({ElementType.TYPE_USE})", "public @interface Nullable {}") .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NullableParameterTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import com.google.anno.my.Nullable;", "public class NullableParameterTest {", " public String[] apply(@Nullable String[] message) {", " return message;", " }", "}") .doTest(); } @Test public void negativeCases_nonNullLiteral() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage() {", " return \"hello\";", " }", "}") .doTest(); } @Test public void negativeCases_nonNullMethod() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NonNullMethodTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class NonNullMethodTest {", " public String getMessage(int x) {", " return String.valueOf(x);", " }", "}") .doTest(); } @Test public void negativeCases_nonNullField() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NonNullFieldTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class NonNullFieldTest {", " private String message;", " public String getMessage() {", " return message;", " }", "}") .doTest(); } @Test public void negativeCases_nonNullParameter() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NonNullParameterTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class NonNullParameterTest {", " public String apply(String message) {", " return message;", " }", "}") .doTest(); } @Test public void negativeCases_this() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/ThisTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class ThisTest {", " private String message;", " public ThisTest setMessage(String message) {", " this.message = message;", " return this;", " }", "}") .doTest(); } @Test public void negativeCases_capturedLocal() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/CapturedLocalTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public abstract class CapturedLocalTest {", " public abstract String getMessage();", " public CapturedLocalTest withMessage(final String message) {", " return new CapturedLocalTest() {", " public String getMessage() {", " return message;", " }", " };", " }", "}") .doTest(); } /** * Makes sure the check never flags methods returning a primitive. Returning null from them is a * bug, of course, but we're not trying to find those bugs in this check. */ @Test public void negativeCases_primitiveReturnType() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/PrimitiveReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class PrimitiveReturnTest {", " public int getCount() {", " return (Integer) null;", " }", "}") .doTest(); } @Test public void negativeCases_voidMethod() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/VoidMethodTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class VoidMethodTest {", " public void run(int iterations) {", " if (iterations <= 0) { return; }", " run(iterations - 1);", " }", "}") .doTest(); } @Test public void negativeCases_voidTypedMethod() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/VoidTypeTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class VoidTypeTest {", " public Void run(int iterations) {", " if (iterations <= 0) { return null; }", " run(iterations - 1);", " return null;", " }", "}") .doTest(); } @Test public void negativeCases_nullableReturnInLambda() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/MissingNullableReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class MissingNullableReturnTest {", " public static final java.util.function.Function<String, String> IDENTITY =", " (s -> { return s != null ? s : null; });", "}") .doTest(); } @Test public void negativeCases_returnLambda() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/MissingNullableReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class MissingNullableReturnTest {", " public static java.util.function.Function<String, String> identity() {", " return s -> s;", " }", "}") .doTest(); } @Test public void negativeCases_returnParenthesizedLambda() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/MissingNullableReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class MissingNullableReturnTest {", " public static java.util.function.Function<String, String> identity() {", " return (s -> s);", " }", "}") .doTest(); } // Regression test for b/110812469; verifies that untracked access paths that mix field access // and method invocation are "trusted" to yield nonNull values @Test public void negativeCases_mixedMethodFieldAccessPath() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/MissingNullableReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nonnull;", "public class MissingNullableReturnTest {", " public @Nonnull MyClass test() {", " return ((MyClass) null).myMethod().myField;", " }", " abstract class MyClass {", " abstract MyClass myMethod();", " MyClass myField;", " }", "}") .doTest(); } // Regression test for b/113123074 @Test public void negativeCases_delegate() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/MissingNullableReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "import java.util.Optional;", "public class MissingNullableReturnTest {", " public String get() {", " return getInternal(true, null);", " }", " private String getInternal(boolean flag, @Nullable Integer i) {", " return \"hello\";", " }", "}") .doTest(); } @Test public void negativeCases_lambda() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/MissingNullableReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "import java.util.concurrent.Callable;", "public class MissingNullableReturnTest {", " public Callable<?> get() {", " return () -> { return null; };", " }", "}") .doTest(); } @Test public void negativeCases_staticNonFinalField() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " static Object NULL = null;", " Object get() {", " return NULL;", " }", "}") .doTest(); } @Test public void negativeCases_polyNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.PolyNull;", "public class LiteralNullReturnTest {", " public @PolyNull String getMessage(@PolyNull String s) {", " if (s == null) {", " return null;", " } else {", " return \"negative\";", " }", " }", "}") .doTest(); } @Test public void negativeCases_unreachableExit() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "class LiteralNullReturnTest {", " public String getMessage() {", " System.exit(1);", " return null;", " }", "}") .doTest(); } @Test public void negativeCases_unreachableFail() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import static org.junit.Assert.fail;", "class LiteralNullReturnTest {", " public String getMessage() {", " fail();", " return null;", " }", "}") .doTest(); } @Test public void negativeCases_unreachableThrowExceptionMethod() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import static org.junit.Assert.fail;", "class LiteralNullReturnTest {", " void throwRuntimeException() {}", " public String getMessage() {", " throwRuntimeException();", " return null;", " }", "}") .doTest(); } @Test public void negativeCases_unreachableCheckFalse() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import static com.google.common.base.Preconditions.checkState;", "class LiteralNullReturnTest {", " public String getMessage() {", " checkState(false);", " return null;", " }", "}") .doTest(); } @Test public void negativeCases_unreachableVerifyFalse() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import static com.google.common.base.Verify.verify;", "class LiteralNullReturnTest {", " public String getMessage() {", " verify(false);", " return null;", " }", "}") .doTest(); } @Test public void negativeCases_staticFinalNonNullField() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " static final Object SOMETHING = 1;", " Object get() {", " return SOMETHING;", " }", "}") .doTest(); } @Test public void negativeCases_returnXIfXIsNotNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object foo(Object o) {", " return (o != null ? o : \"\");", " }", "}") .doTest(); } @Test public void negativeCases_returnXIfSameSymbolDifferentObjectIsNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object o;", " Object foo(LiteralNullReturnTest other) {", " return (o == null ? other.o : \"\");", " }", "}") .doTest(); } @Test public void negativeCases_returnXUnlessXIsXNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object foo(Object o) {", " return (o == null ? \"\" : o);", " }", "}") .doTest(); } @Test public void negativeCases_returnXInsideIfNotNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object foo(Object o) {", " if (o != null) {", " return o;", " }", " return \"\";", " }", "}") .doTest(); } @Test public void negativeCases_returnXInsideIfNullElse() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object foo(Object o) {", " if (o == null) {", " return \"\";", " } else {", " return o;", " }", " }", "}") .doTest(); } @Test public void negativeCases_returnXInsideIfNullButAfterOtherStatement() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object foo(Object o) {", " if (o == null) {", " o = \"\";", " return o;", " }", " return \"\";", " }", "}") .doTest(); } @Test public void negativeCases_onlyIfAlreadyInScopeAndItIsNot() { createCompilationTestHelper() .setArgs("-XepOpt:Nullness:OnlyIfAnnotationAlreadyInScope=true") .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " String getMessage(boolean b) {", " return b ? \"\" : null;", " }", "}") .doTest(); } @Test public void negativeCases_orElseNotNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import java.util.Optional;", "class LiteralNullReturnTest {", " public String getMessage(Optional<String> m) {", " return m.orElse(\"\");", " }", "}") .doTest(); } @Test public void negativeCases_doesNotImplementMap() { createCompilationTestHelper() .addSourceLines( "NotMap.java", "interface NotMap<K, V> {", " String get(Object o);", " V replace(K k, V v);", "}") .addSourceLines( "MyMap.java", "interface MyMap extends NotMap<Integer, Double> {", " @Override String get(Object o);", " @Override Double replace(Integer k, Double v);", "}") .doTest(); } @Test public void negativeCases_suppressionForReturnTreeBased() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import java.util.Optional;", "class LiteralNullReturnTest {", " @SuppressWarnings(\"ReturnMissingNullable\")", " public String getMessage(Optional<String> m) {", " return m.orElse(null);", " }", "}") .doTest(); } @Test public void negativeCases_suppressionForMethodTreeBased() { createCompilationTestHelper() .addSourceLines( "NotMap.java", // "interface NotMap {", " Integer get(String o);", "}") .addSourceLines( "MyMap.java", "import java.util.Map;", "interface MyMap<K, V> extends Map<K, V>, NotMap {", " @SuppressWarnings(\"ReturnMissingNullable\")", " @Override V get(Object o);", "}") .doTest(); } @Test public void negativeCases_suppressionAboveMethodLevel() { createCompilationTestHelper() .addSourceLines( "NotMap.java", // "interface NotMap {", " Integer get(String o);", "}") .addSourceLines( "MyMap.java", "import java.util.Map;", "@SuppressWarnings(\"ReturnMissingNullable\")", "interface MyMap<K, V> extends Map<K, V>, NotMap {", " @Override V get(Object o);", "}") .doTest(); } @Test public void returnSameSymbolDifferentObjectInsideIfNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "abstract class LiteralNullReturnTest {", " Object o;", " Object foo(LiteralNullReturnTest other) {", " if (o == null) {", " return other.o;", " }", " return \"\";", " }", "}") .doTest(); } @Test public void suggestNonJsr305Nullable() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "class T {", " @Nullable private final Object obj1 = null;", " private final Object method(boolean b) { return b ? null : 0; }", " @interface Nullable {}", "}") .addOutputLines( "out/Test.java", "class T {", " @Nullable private final Object obj1 = null;", " @Nullable private final Object method(boolean b) { return b ? null : 0; }", " @interface Nullable {}", "}") .doTest(); } @Test public void nonAnnotationNullable() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "class T {", " private final Object method(boolean b) { return b ? null : 0; }", " class Nullable {}", "}") .addOutputLines( "out/Test.java", "class T {", " @org.jspecify.nullness.Nullable private final Object method(boolean b) { return b ?" + " null : 0; }", " class Nullable {}", "}") .doTest(); } @Test public void multipleNullReturns() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "class T {", " private final Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .addOutputLines( "out/Test.java", "import org.jspecify.nullness.Nullable;", "class T {", " private final @Nullable Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .doTest(); } @Test public void memberSelectReturnType() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " java.lang.Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .addOutputLines( "out/Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " java.lang.@Nullable Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .doTest(); } @Test public void annotationInsertedAfterModifiers() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " final Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .addOutputLines( "out/Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " final @Nullable Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .doTest(TEXT_MATCH); } @Test public void parameterizedMemberSelectReturnType() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " java.util.List<java.lang.Object> method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .addOutputLines( "out/Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " java.util.@Nullable List<java.lang.Object> method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .doTest(); } @Test public void annotatedMemberSelectReturnType() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "import org.checkerframework.checker.initialization.qual.UnderInitialization;", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " java.lang.@UnderInitialization Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .addOutputLines( "out/Test.java", "import org.checkerframework.checker.initialization.qual.UnderInitialization;", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " java.lang.@Nullable @UnderInitialization Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .doTest(); } @Test public void annotationNotNamedNullable() { createRefactoringTestHelper() .setArgs("-XepOpt:Nullness:DefaultNullnessAnnotation=javax.annotation.CheckForNull") .addInputLines( "in/Test.java", "class T {", " Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .addOutputLines( "out/Test.java", "import javax.annotation.CheckForNull;", "class T {", " @CheckForNull Object method(boolean b) {", " if (b) {", " return null;", " } else {", " return null;", " }", " }", "}") .doTest(); } @Test public void aggressive_onlyStatementIsNullReturn() { createAggressiveCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public String getMessage() {", " // BUG: Diagnostic contains: @Nullable", " return null;", " }", "}") .doTest(); } @Test public void aggressive_typeVariableUsage() { createAggressiveCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " public <T> T getMessage(boolean b, T t) {", " // BUG: Diagnostic contains: @Nullable", " return b ? null : t;", " }", "}") .doTest(); } @Test public void aggressive_voidTypedMethod() { createAggressiveCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/VoidTypeTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class VoidTypeTest {", " public Void run(int iterations) {", " // BUG: Diagnostic contains: @Nullable", " if (iterations <= 0) { return null; }", " run(iterations - 1);", " // BUG: Diagnostic contains: @Nullable", " return null;", " }", "}") .doTest(); } @Test public void negativeCases_doesNotRemoveNecessarySuppressWarnings() { createRefactoringTestHelper() .setArgs("-XepOpt:Nullness:RemoveSuppressWarnings=true") .addInputLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " @SuppressWarnings(\"nullness:argument\")", " public String getMessage(boolean b) {", " if (b) {", " doSomethingElse(null);", " return \"negative\";", " } else {", " return \"negative\";", " }", " }", " public void doSomethingElse(Object c) {", " return;", " }", "}") .addOutputLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class LiteralNullReturnTest {", " @SuppressWarnings(\"nullness:argument\")", " public String getMessage(boolean b) {", " if (b) {", " doSomethingElse(null);", " return \"negative\";", " } else {", " return \"negative\";", " }", " }", " public void doSomethingElse(Object c) {", " return;", " }", "}") .doTest(TEXT_MATCH); } private CompilationTestHelper createCompilationTestHelper() { return CompilationTestHelper.newInstance(ReturnMissingNullable.class, getClass()); } private CompilationTestHelper createAggressiveCompilationTestHelper() { return createCompilationTestHelper().setArgs("-XepOpt:Nullness:Conservative=false"); } private BugCheckerRefactoringTestHelper createRefactoringTestHelper() { return BugCheckerRefactoringTestHelper.newInstance(ReturnMissingNullable.class, getClass()); } }
69,738
34.027122
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/UnsafeWildcardTest.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.nullness; import com.google.errorprone.CompilationTestHelper; import com.sun.tools.javac.main.Main.Result; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class UnsafeWildcardTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnsafeWildcard.class, getClass()); @Test public void unsoundGenericMethod() { compilationHelper.addSourceFile("UnsoundGenericMethod.java").doTest(); } @Test public void positiveExpressions() { compilationHelper .addSourceLines( "Test.java", "import java.util.List;", "class Test<T> {", " static class WithBound<U extends Number> {}", " public WithBound<? super T> basic() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return null;", " }", " public WithBound<? super T> inParens() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return (null);", " }", " public WithBound<? super T> cast() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return (WithBound<? super T>) null;", " }", " public WithBound<? super T> inTernary(boolean x, WithBound<? super T> dflt) {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return x ? null : dflt;", " }", " public WithBound<? super T> allNullTernary(boolean x) {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return x ? null : null;", " }", " public WithBound<? super T> parensInTernary(boolean x) {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return x ? (null) : null;", " }", " public WithBound<? super T> parensAroundTernary(boolean x) {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return (x ? null : null);", " }", " public List<WithBound<? super T>> nestedWildcard() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return null;", " }", " public List<? extends WithBound<? super T>> extendsWildcard() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return null;", " }", " public List<? super WithBound<? super T>> superWildcard() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return null;", " }", "}") .doTest(); } @Test public void negativeReturns() { compilationHelper .addSourceLines( "Test.java", "import java.util.List;", "class Test {", " public String basic() {", " return null;", " }", " public String inParens() {", " return (null);", " }", " public String inTernary(boolean x) {", " return x ? null : \"foo\";", " }", " public String allNullTernary(boolean x) {", " return x ? null : null;", " }", " public String parensInTernary(boolean x) {", " return x ? (null) : \"foo\";", " }", " public String parensAroundTernary(boolean x) {", " return (x ? null : \"foo\");", " }", " public List<String> typearg() {", " return null;", " }", " public List<? extends String> extendsWildcard() {", " return null;", " }", " public List<? super String> superWildcardNoImplicitBound() {", " return null;", " }", "}") .doTest(); } @Test public void negativeLambdas() { compilationHelper .addSourceLines( "Test.java", "import java.util.List;", "import java.util.function.Function;", "class Test {", " public Function<String, String> basic() {", " return x -> null;", " }", " public Function<String, String> inParens() {", " return x -> (null);", " }", " public Function<Boolean, String> inTernary() {", " return x -> x ? null : \"foo\";", " }", " public Function<String, String> returnInLambda() {", " return x -> { return null; };", " }", "}") .doTest(); } @Test public void lambdasWithTypeParameters() { compilationHelper .addSourceLines( "Test.java", "import java.util.List;", "import java.util.function.Function;", "class Test {", " class WithBound<T extends Number> {}", " public Function<String, List<? super String>> contra() {", " return s -> null;", " }", " public Function<Integer, WithBound<? super Integer>> implicitOk() {", " return i -> null;", " }", " public <U> Function<U, WithBound<? super U>> implicitPositive() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return u -> null;", " }", " public <U> Function<U, WithBound<? super U>> returnInLambda() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return u -> { return null; };", " }", " public <U> Function<U, WithBound<? super U>> nestedWildcard() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return null;", " }", "}") .doTest(); } @Test public void typeParameters() { compilationHelper .addSourceLines( "Test.java", "import java.util.List;", "class Test<S> {", " static class WithBound<U extends Number> {}", " class WildcardBound<T extends WithBound<? super S>> {", " T bad() {", " // We allow this and instead check instantiations below", " return null;", " }", " }", " WildcardBound<WithBound<? super S>> diamond() {", " // BUG: Diagnostic contains: Unsafe wildcard type argument", " return new WildcardBound<>();", " }", " WildcardBound<WithBound<? super S>> create() {", " // BUG: Diagnostic contains: Unsafe wildcard type argument", " return new WildcardBound<WithBound<? super S>>();", " }", " WildcardBound<WithBound<? super S>> none() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return null;", " }", "}") .doTest(); } @Test public void variables() { compilationHelper .addSourceLines( "Test.java", "import java.util.List;", "class Test<T> {", " class WithBound<T extends Number> {}", " private String s;", " private List<String> xs = null;", " private List<? super String> ys;", " private WithBound<? super Integer> zs = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " private WithBound<? super T> initialized = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " private final WithBound<? super T> initializedFinal = null;", " // BUG: Diagnostic contains: Uninitialized field with unsafe wildcard", " private WithBound<? super T> uninitialized;", " private final WithBound<? super T> uninitializedFinal;", " Test() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " uninitializedFinal = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " uninitialized = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " initialized = null;", " }", " public void foo() {", " List<? extends String> covariant = null;", " List<? super String> contravariant = null;", " WithBound<? super Integer> inBounds = null;", " WithBound<? super T> uninitializedLocal;", " final WithBound<? super T> uninitializedFinalLocal;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " WithBound<? super T> implicitBounds = null;", " covariant = null;", " contravariant = null;", " inBounds = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " uninitializedLocal = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " uninitializedFinalLocal = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " implicitBounds = null;", " }", "}") .doTest(); } @Test public void calls() { compilationHelper .addSourceLines( "Test.java", "import java.util.List;", "class Test {", " class WithBound<T extends Number> {}", " public void foo(String s, List<String> xs, List<? super String> contra) {", " foo(null, null, null);", " }", " public void negative(WithBound<Integer> xs, WithBound<? super Integer> contra) {", " negative(null, null);", " }", " public <U> void positive(WithBound<? super U> implicit) {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " this.<U>positive(null);", " // BUG: Diagnostic contains: impossible", // Compiler uses U = Object and ? super Object doesn't intersect with upper bound Number " positive(null);", " }", "}") .doTest(); } @Test public void inferredParamType_flaggedIfProblematic() { compilationHelper .addSourceLines( "Test.java", "import java.util.List;", "class Test {", " static class WithBound<T extends Number> {}", " public <U> List<WithBound<? super U>> positive(WithBound<? super U> safe) {", " // BUG: Diagnostic contains: Unsafe wildcard in inferred type argument", " return List.of(safe,", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " null);", // implicitly upcast to WithBound<? super U> " }", " public List<WithBound<? super Integer>> negative(WithBound<Integer> safe) {", " return List.of(safe, null);", " }", "}") .doTest(); } @Test public void constructors() { compilationHelper .addSourceLines( "Test.java", "class Test<U> {", " class WithBound<T extends Number> {}", " public Test() { this(null, null); }", " public Test(WithBound<? super U> implicit) {}", " public Test(WithBound<Integer> xs, WithBound<? super Integer> contra) {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " this(null);", " }", " class Sub<S> extends Test<S> {", " Sub(WithBound<? super U> implicit) {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " super(null);", " }", " }", " static <U> Test<U> newClass() {", " new Test<U>(null, null);", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " new Test<U>(null);", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " return new Test<>(null);", " }", " static <U> Test<U> anonymous() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " new Test<U>(null) {};", " return null;", " }", " void inner() {", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " new Sub<U>(null);", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " new Sub<U>(null) {};", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " this.new Sub<U>(null) {};", " }", "}") .doTest(); } @Test public void supertypes_problematicWildcards_flagged() { compilationHelper .addSourceLines( "Test.java", "import java.io.Serializable;", "import java.util.AbstractList;", "import java.util.List;", "class Test {", " class WithBound<T extends Number> {}", " // BUG: Diagnostic contains: Unsafe wildcard type", " abstract class BadList<U> extends AbstractList<WithBound<? super U>> {}", " abstract class BadListImpl<U> implements Serializable,", " // BUG: Diagnostic contains: Unsafe wildcard type", " List<WithBound<? super U>> {}", " interface BadListItf<U> extends Serializable,", " // BUG: Diagnostic contains: Unsafe wildcard type", " List<WithBound<? super U>> {}", "}") .doTest(); } @Test public void varargs() { compilationHelper .addSourceLines( "Test.java", "class Test<T> {", " static class WithBound<T extends Number> {}", " Test(WithBound<Integer> xs, WithBound<? super T>... args) {}", " static <U> void hasVararg(WithBound<Integer> xs, WithBound<? super U>... args) {}", " static <U> void nullVarargs(WithBound<? super U> xs) {", " Test.<U>hasVararg(", " null,", // fine: target type is safe " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " null,", " xs,", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " null);", " new Test<U>(", " null,", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " null,", " xs,", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " null);", " }", "}") .doTest(); } @Test public void arrays() { compilationHelper .addSourceLines( "Test.java", "class Test {", " class WithBound<T extends Number> {}", // Generic array creation is a compilation error, and non-generic arrays are ok " Object[] simpleInitializer = { null };", " Object[][] nestedInitializer = { { null }, { null } };", " <U> void nulls() {", " String[][] stringMatrix = null;", " WithBound<? super Integer>[] implicitBound = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " WithBound<? super U>[] simpleNull = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " WithBound<? super U>[][] nestedNull = null;", " }", "}") .doTest(); } /** * Regresion test demonstrating that generic array creation is a compiler error. If it wasn't, * we'd want to check element types. */ @Test public void genericArrays_isCompilerError() { compilationHelper .addSourceLines( "Test.java", "class Test {", " class WithBound<T extends Number> {}", " // BUG: Diagnostic matches: X", " WithBound<? super Integer>[] simpleInitializer = { null };", " // BUG: Diagnostic matches: X", " WithBound<? super Integer>[][] nestedInitializer = { { null }, { null } };", " // BUG: Diagnostic matches: X", " WithBound<? super Integer>[][] emptyInitializer = {};", " void newArrays() {", " // BUG: Diagnostic matches: X", " Object[] a1 = new WithBound<? super Integer>[] {};", " // BUG: Diagnostic matches: X", " Object[] a2 = new WithBound<? super Integer>[0];", " // BUG: Diagnostic matches: X", " Object[] a3 = new WithBound<? super Integer>[][] {};", " // BUG: Diagnostic matches: X", " Object[] a4 = new WithBound<? super Integer>[0][];", " }", "}") .expectResult(Result.ERROR) .matchAllDiagnostics() .expectErrorMessage("X", msg -> msg.contains("generic array creation")) .doTest(); } @Test public void arrays_rawTypes_futureWork() { compilationHelper .addSourceLines( "Test.java", "class Test {", " class WithBound<T extends Number> {}", " <U> void problematic() {", // The following implicitly create problematic types even absent null values (though // problematic non-empty arrays containing all-null values can be created just as // easily with [N] where N > 0). The compiler issues raw and unchecked warnings here, // but we might want to flag assignments as well. " WithBound<? super U> raw = new WithBound();", " WithBound<? super U>[] array = new WithBound[0];", " WithBound<? super U>[][] nested = new WithBound[0][];", " }", "}") .doTest(); } /** * Regression test to ignore {@code null} assignment to wildcard whose lower bound is a type * variable with non-trivial upper bound. The compiler rejects potentially dangerous wildcards on * its own in this case, but simple subtype checks between lower and upper bound can fail and lead * to false positives if involved type variables' upper bounds capture another type variable. */ @Test public void boundedTypeVar_validLowerBound_isIgnored() { compilationHelper .addSourceLines( "MyIterable.java", "import java.util.List;", "interface MyIterable<E, T extends Iterable<E>> {", " static class Test<F, S extends List<F>> implements MyIterable<F, S> {", " MyIterable<F, ? super S> parent;", " public Test() {", " this.parent = null;", " }", " }", "}") .doTest(); } @Test public void boundedTypeVar_questionableLowerBound_isCompilerError() { compilationHelper .addSourceLines( "MyIterable.java", "import java.util.List;", "interface MyIterable<E, T extends List<E>> {", " // BUG: Diagnostic matches: X", " static class Test<F, S extends Iterable<F>> implements MyIterable<F, S> {", " MyIterable<F, ? super S> parent;", " public Test() {", " this.parent = null;", " }", " }", "}") .expectResult(Result.ERROR) .matchAllDiagnostics() .expectErrorMessage( "X", msg -> msg.contains("type argument S is not within bounds of type-variable T")) .doTest(); } /** * Regression test to ignore {@code null} assignment to wildcard whose lower bound is a concrete * type and whose implicit upper bound is F-bounded. The compiler rejects potentially dangerous * wildcards on its own in this case, but simple subtype checks between lower and upper bound can * fail and lead to false positives. */ @Test public void fBoundedImplicitUpperBound_validLowerBound_isIgnored() { compilationHelper .addSourceLines( "FBounded.java", "abstract class FBounded<T extends FBounded<T>> {", " public static final class Coll<E> extends FBounded<Coll<E>> {}", " public interface Listener<U extends FBounded<U>> {}", " public static <K> void shouldWork() {", " Listener<? super Coll<K>> validListener = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " Listener<? super K> invalidListener = null;", " // BUG: Diagnostic contains: Cast to wildcard type unsafe", " Iterable<Listener<? super K>> invalidListeners = java.util.List.of(null, null);", " }", "}") .doTest(); } @Test public void fBoundedImplicitUpperBound_invalidLowerBound_isCompilerError() { compilationHelper .addSourceLines( "FBounded.java", "abstract class FBounded<T extends FBounded<T>> {", " public static final class Coll<E> extends FBounded<Coll<E>> {}", " public interface Listener<U extends FBounded<U>> {}", " public static <K> void shouldWork() {", " // BUG: Diagnostic matches: X", " Listener<? super String> listener = null;", " }", "}") .expectResult(Result.ERROR) .matchAllDiagnostics() .expectErrorMessage( "X", msg -> msg.contains("String is not within bounds of type-variable U")) .doTest(); } }
23,054
39.733216
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/VoidMissingNullableTest.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.nullness; 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 VoidMissingNullable}Test */ @RunWith(JUnit4.class) public class VoidMissingNullableTest { private final CompilationTestHelper conservativeCompilationHelper = CompilationTestHelper.newInstance(VoidMissingNullable.class, getClass()); private final CompilationTestHelper aggressiveCompilationHelper = CompilationTestHelper.newInstance(VoidMissingNullable.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); private final BugCheckerRefactoringTestHelper aggressiveRefactoringHelper = BugCheckerRefactoringTestHelper.newInstance(VoidMissingNullable.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); @Test public void positive() { aggressiveCompilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "class Test {", " // BUG: Diagnostic contains: @Nullable", " Void v;", " // BUG: Diagnostic contains: @Nullable", " Void f() {", " return v;", " }", "}") .doTest(); } @Test public void declarationAnnotatedLocation() { aggressiveRefactoringHelper .addInputLines( "in/Foo.java", "import javax.annotation.Nullable;", "abstract class Foo {", " java.lang.Void v;", " final Void f() {", " return v;", " }", "}") .addOutputLines( "out/Foo.java", "import javax.annotation.Nullable;", "abstract class Foo {", " @Nullable java.lang.Void v;", " @Nullable final Void f() {", " return v;", " }", "}") .doTest(TEXT_MATCH); } @Test public void typeAnnotatedLocation() { aggressiveRefactoringHelper .addInputLines( "in/Foo.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "abstract class Foo {", " java.lang.Void v;", " final Void f() {", " return v;", " }", "}") .addOutputLines( "out/Foo.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "abstract class Foo {", " java.lang.@Nullable Void v;", " final @Nullable Void f() {", " return v;", " }", "}") .doTest(TEXT_MATCH); } @Test public void negativeAlreadyAnnotated() { aggressiveCompilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "class Test {", " @Nullable Void v;", " @Nullable Void f() {", " return v;", " }", "}") .doTest(); } @Test public void negativeNotVoid() { aggressiveCompilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "class Test {", " String s;", " String f() {", " return s;", " }", "}") .doTest(); } @Test public void positiveTypeArgument() { aggressiveCompilationHelper .addSourceLines( "Test.java", "import java.util.List;", "import org.checkerframework.checker.nullness.qual.Nullable;", "class Test {", " // BUG: Diagnostic contains: @Nullable", " List<Void> a;", " // BUG: Diagnostic contains: @Nullable", " List<? extends Void> b;", " // BUG: Diagnostic contains: @Nullable", " List<? super Void> c;", " List<?> d;", "}") .doTest(); } @Test public void positiveTypeArgumentOtherAnnotation() { aggressiveCompilationHelper .addSourceLines( "NonNull.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 NonNull {}") .addSourceLines( "Test.java", "import java.util.List;", "import org.checkerframework.checker.nullness.qual.Nullable;", "class Test {", " // BUG: Diagnostic contains: @Nullable", " List<@NonNull Void> a;", " // BUG: Diagnostic contains: @Nullable", " List<? extends @NonNull Void> b;", " // BUG: Diagnostic contains: @Nullable", " List<? super @NonNull Void> c;", " List<?> d;", "}") .doTest(); } @Test public void negativeTypeArgumentAlreadyAnnotated() { aggressiveCompilationHelper .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", "import java.util.List;", "class Test {", " List<@Nullable Void> a;", " List<? extends @Nullable Void> b;", " List<? super @Nullable Void> c;", " List<?> d;", "}") .doTest(); } @Test public void negativeTypeArgumentAlreadyAnnotatedAnonymous() { aggressiveCompilationHelper .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("Bystander.java", "public interface Bystander<T> {}") .addSourceLines( "Test.java", "class Test {", " static {", " new Bystander<@Nullable Void>() {};", " }", "}") .doTest(); } @Test public void negativeTypeArgumentNotVoid() { aggressiveCompilationHelper .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", "import java.util.List;", "class Test {", " List<String> a;", " List<? extends String> b;", " List<? super String> c;", " List<?> d;", "}") .doTest(); } @Test public void negativeTypeArgumentDeclarationNullable() { aggressiveCompilationHelper .addSourceLines( "Test.java", "import java.util.List;", "import javax.annotation.Nullable;", "class Test {", " List<Void> a;", " List<? extends Void> b;", " List<? super Void> c;", " List<?> d;", "}") .doTest(); } @Test public void positiveLambdaParameter() { aggressiveCompilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "interface Test {", " void consume(@Nullable Void v);", "", " // BUG: Diagnostic contains: @Nullable", " Test TEST = (Void v) -> {};", "}") .doTest(); } @Test public void negativeLambdaParameterNoType() { aggressiveCompilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "interface Test {", " void consume(@Nullable Void v);", "", " Test TEST = v -> {};", "}") .doTest(); } // TODO(cpovirk): Test under Java 11+ with `(var x) -> {}` lambda syntax. @Test public void negativeVar() { aggressiveCompilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "class Test {", " @Nullable Void v;", "", " void f() {", " var v = this.v;", " }", "}") .doTest(); } @Test public void negativeOtherLocalVariable() { aggressiveCompilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "class Test {", " @Nullable Void v;", "", " void f() {", " Void v = this.v;", " }", "}") .doTest(); } @Test public void positiveConservativeNullMarked() { conservativeCompilationHelper .addSourceLines( "Test.java", "import javax.annotation.Nullable;", "import org.jspecify.nullness.NullMarked;", "@NullMarked", "class Test {", " // BUG: Diagnostic contains: @Nullable", " Void v;", "}") .doTest(); } @Test public void negativeConservativeNotNullMarked() { conservativeCompilationHelper .addSourceLines( "Test.java", // "import javax.annotation.Nullable;", "class Test {", " Void v;", "}") .doTest(); } }
11,143
30.128492
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/DereferenceWithNullBranchTest.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.nullness; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link DereferenceWithNullBranch}Test */ @RunWith(JUnit4.class) public class DereferenceWithNullBranchTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(DereferenceWithNullBranch.class, getClass()); @Test public void positive() { helper .addSourceLines( "Foo.java", "import java.util.Optional;", "class Foo {", " void foo(Optional<Integer> o) {", " // BUG: Diagnostic contains: ", " o.orElse(null).intValue();", " }", "}") .doTest(); } @Test public void positiveTernary() { helper .addSourceLines( "Foo.java", "import java.util.Optional;", "class Foo {", " int foo(String s) {", " // BUG: Diagnostic contains: ", " return (s == null) ? s.length() : 0;", " }", "}") .doTest(); } @Test public void negativeNoNullBranch() { helper .addSourceLines( "Foo.java", "import java.util.Optional;", "class Foo {", " void foo() {", " Optional.of(7).get().intValue();", " }", "}") .doTest(); } @Test public void negativeVoid() { helper .addSourceLines( "Foo.java", "class Foo {", " void foo() {", " Class<?> c;", " c = Void.class;", " c = void.class;", " c = Void.TYPE;", " }", "}") .doTest(); } @Test public void noCrashOnQualifiedClass() { helper .addSourceLines( "Foo.java", // "class Foo {", " class Bar {}", " Foo.Bar bar;", "}") .doTest(); } @Test public void noCrashOnQualifiedInterface() { helper .addSourceLines( "Foo.java", "import java.util.Map;", "interface Foo {", " void foo(Map.Entry<?, ?> o);", "}") .doTest(); } @Test public void noCrashOnModule() { helper .addSourceLines( "module-info.java", // "module foo.bar {", " requires java.logging;", "}") .doTest(); } }
3,198
24.592
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsMissingNullableTest.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.nullness; 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 EqualsMissingNullable}Test */ @RunWith(JUnit4.class) public class EqualsMissingNullableTest { private final CompilationTestHelper conservativeHelper = CompilationTestHelper.newInstance(EqualsMissingNullable.class, getClass()); private final CompilationTestHelper aggressiveHelper = CompilationTestHelper.newInstance(EqualsMissingNullable.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); private final BugCheckerRefactoringTestHelper aggressiveRefactoringHelper = BugCheckerRefactoringTestHelper.newInstance(EqualsMissingNullable.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); @Test public void positive() { aggressiveHelper .addSourceLines( "Foo.java", "abstract class Foo {", " // BUG: Diagnostic contains: @Nullable", " public abstract boolean equals(Object o);", "}") .doTest(); } @Test public void declarationAnnotatedLocation() { aggressiveRefactoringHelper .addInputLines( "in/Foo.java", "import javax.annotation.Nullable;", "abstract class Foo {", " public abstract boolean equals(final Object o);", "}") .addOutputLines( "out/Foo.java", "import javax.annotation.Nullable;", "abstract class Foo {", " public abstract boolean equals(@Nullable final Object o);", "}") .doTest(TEXT_MATCH); } @Test public void typeAnnotatedLocation() { aggressiveRefactoringHelper .addInputLines( "in/Foo.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "abstract class Foo {", " public abstract boolean equals(final Object o);", "}") .addOutputLines( "out/Foo.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "abstract class Foo {", " public abstract boolean equals(final @Nullable Object o);", "}") .doTest(TEXT_MATCH); } @Test public void negativeAlreadyAnnotated() { aggressiveHelper .addSourceLines( "Foo.java", "import javax.annotation.Nullable;", "abstract class Foo {", " public abstract boolean equals(@Nullable Object o);", "}") .doTest(); } @Test public void negativeAlreadyAnnotatedWithProtobufAnnotation() { aggressiveHelper .addSourceLines( "ProtoMethodAcceptsNullParameter.java", "@interface ProtoMethodAcceptsNullParameter {}") .addSourceLines( "Foo.java", "abstract class Foo {", " public abstract boolean equals(@ProtoMethodAcceptsNullParameter Object o);", "}") .doTest(); } @Test public void negativeNotObjectEquals() { aggressiveHelper .addSourceLines( "Foo.java", "abstract class Foo {", " public abstract boolean equals(String s, int i);", "}") .doTest(); } @Test public void positiveConservativeNullMarked() { conservativeHelper .addSourceLines( "Foo.java", "import org.jspecify.nullness.NullMarked;", "@NullMarked", "abstract class Foo {", " // BUG: Diagnostic contains: @Nullable", " public abstract boolean equals(Object o);", "}") .doTest(); } @Test public void negativeConservativeNotNullMarked() { conservativeHelper .addSourceLines( "Foo.java", // "abstract class Foo {", " public abstract boolean equals(Object o);", "}") .doTest(); } }
4,801
31.445946
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/ParameterMissingNullableTest.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.nullness; 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 ParameterMissingNullable}Test */ @RunWith(JUnit4.class) public class ParameterMissingNullableTest { private final CompilationTestHelper conservativeHelper = CompilationTestHelper.newInstance(ParameterMissingNullable.class, getClass()); private final CompilationTestHelper aggressiveHelper = CompilationTestHelper.newInstance(ParameterMissingNullable.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); private final BugCheckerRefactoringTestHelper aggressiveRefactoringHelper = BugCheckerRefactoringTestHelper.newInstance(ParameterMissingNullable.class, getClass()) .setArgs("-XepOpt:Nullness:Conservative=false"); @Test public void positiveIf() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(Integer i) {", " // BUG: Diagnostic contains: @Nullable", " if (i == null) {", " i = 0;", " }", " }", "}") .doTest(); } @Test public void positiveIfWithUnrelatedThrow() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(boolean b, Integer i) {", " if (b) {", " // BUG: Diagnostic contains: @Nullable", " int val = i == null ? 0 : i;", " if (val < 0) {", " throw new RuntimeException();", " }", " }", " }", "}") .doTest(); } @Test public void positiveDespiteWhileLoop() { // TODO(cpovirk): This doesn't look "positive" to me. // TODO(cpovirk): Also, I *think* the lack of braces on the while() loop is intentional? aggressiveHelper .addSourceLines( "Foo.java", "import static com.google.common.base.Preconditions.checkArgument;", "class Foo {", " void foo(Object o) {", " while (true)", " checkArgument(o != null);", " }", "}") .doTest(); } @Test public void positiveTernary() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " int i;", " void foo(Integer i) {", " // BUG: Diagnostic contains: @Nullable", " this.i = i == null ? 0 : i;", " }", "}") .doTest(); } @Test public void positiveCallToMethod() { conservativeHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(Integer i) {}", " void bar() {", " // BUG: Diagnostic contains: @Nullable", " foo(null);", " }", "}") .doTest(); } @Test public void positiveCallToTopLevelConstructor() { conservativeHelper .addSourceLines( "Foo.java", "class Foo {", " Foo(Integer i) {}", " void bar() {", " // BUG: Diagnostic contains: @Nullable", " new Foo(null);", " }", "}") .doTest(); } @Test public void positiveCallToNestedConstructor() { conservativeHelper .addSourceLines( "Foo.java", "class Foo {", " static class Nested {", " Nested(Integer i) {}", " }", " void bar() {", " // BUG: Diagnostic contains: @Nullable", " new Foo.Nested(null);", " }", "}") .doTest(); } @Test public void negativeCallToNestedConstructor() { conservativeHelper .addSourceLines( "Foo.java", "class Foo {", " class Nested {", " Nested(Integer i) {}", " }", " void bar() {", // TODO(cpovirk): Recognize this. " new Nested(null);", " }", "}") .doTest(); } @Test public void declarationAnnotatedLocation() { aggressiveRefactoringHelper .addInputLines( "in/Foo.java", "import javax.annotation.Nullable;", "class Foo {", " void foo(java.lang.Integer i) {", " if (i == null) {", " i = 0;", " }", " }", "}") .addOutputLines( "out/Foo.java", "import javax.annotation.Nullable;", "class Foo {", " void foo(@Nullable java.lang.Integer i) {", " if (i == null) {", " i = 0;", " }", " }", "}") .doTest(TEXT_MATCH); } @Test public void typeAnnotatedLocation() { aggressiveRefactoringHelper .addInputLines( "in/Foo.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class Foo {", " void foo(java.lang.Integer i) {", " if (i == null) {", " i = 0;", " }", " }", "}") .addOutputLines( "out/Foo.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class Foo {", " void foo(java.lang.@Nullable Integer i) {", " if (i == null) {", " i = 0;", " }", " }", "}") .doTest(TEXT_MATCH); } @Test public void negativeAlreadyAnnotated() { aggressiveHelper .addSourceLines( "Foo.java", "import javax.annotation.Nullable;", "class Foo {", " void foo(@Nullable Integer i) {", " if (i == null) {", " i = 0;", " }", " }", "}") .doTest(); } @Test public void negativeCasesAlreadyTypeAnnotatedInnerClass() { aggressiveHelper .addSourceLines( "Foo.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class Foo {", " class Inner {}", " @Nullable Inner message;", " void foo(@Nullable Inner i) {", " if (i == null) {", " return;", " }", " }", "}") .doTest(); } @Test public void negativePreconditionCheckMethod() { aggressiveHelper .addSourceLines( "Foo.java", "import static com.google.common.base.Preconditions.checkArgument;", "class Foo {", " void foo(Integer i) {", " checkArgument(i != null);", " }", "}") .doTest(); } @Test public void negativeOtherCheckMethod() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " void assertNot(boolean b) {}", " void foo(Integer i) {", " assertNot(i == null);", " }", "}") .doTest(); } @Test public void negativeAssert() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(Integer i) {", " assert (i != null);", " }", "}") .doTest(); } @Test public void negativeCheckNotAgainstNull() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(Integer i) {", " if (i == 7) {", " i = 0;", " }", " }", "}") .doTest(); } @Test public void negativeCheckOfNonParameter() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(Integer i) {", " Integer j = 7;", " if (j == null) {", " i = 0;", " }", " }", "}") .doTest(); } @Test public void negativeThrow() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(Integer i) {", " if (i == null) {", " throw something();", " }", " }", " RuntimeException something() {", " return new RuntimeException();", " }", "}") .doTest(); } @Test public void negativeCreateException() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(Integer i) {", " if (i == null) {", " throwIt(new RuntimeException());", " }", " }", " void throwIt(RuntimeException x) {", " throw x;", " }", "}") .doTest(); } @Test public void negativeLambdaParameter() { aggressiveHelper .addSourceLines( "Foo.java", "interface Foo {", " Foo FOO = o -> o == null ? 0 : o;", " int toInt(Integer o);", "}") .doTest(); } @Test public void negativeDoWhileLoop() { aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " Foo next;", " void foo(Foo foo) {", " do {", " foo = foo.next;", " } while (foo != null);", " }", "}") .doTest(); } @Test public void negativeWhileLoop() { /* * It would be safe to annotate this parameter as @Nullable, but it's somewhat unclear whether * people would prefer that in most cases. We could consider adding @Nullable if people would * find it useful. */ aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " Foo next;", " void foo(Foo foo) {", " while (foo != null) {", " foo = foo.next;", " }", " }", "}") .doTest(); } @Test public void negativeForLoop() { // Similar to testNegativeWhileLoop, @Nullable would be defensible here. aggressiveHelper .addSourceLines( "Foo.java", "class Foo {", " Foo next;", " void foo(Foo foo) {", " for (; foo != null; foo = foo.next) {}", " }", "}") .doTest(); } @Test public void negativeCallArgNotNull() { conservativeHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(Integer i) {}", " void bar() {", " foo(1);", " }", "}") .doTest(); } @Test public void negativeCallAlreadyAnnotated() { conservativeHelper .addSourceLines( "Foo.java", "import javax.annotation.Nullable;", "class Foo {", " void foo(@Nullable Integer i) {}", " void bar() {", " foo(null);", " }", "}") .doTest(); } @Test public void negativeCallTypeVariable() { conservativeHelper .addSourceLines( "Foo.java", "class Foo {", " <T> void foo(T t) {}", " void bar() {", " foo(null);", " }", "}") .doTest(); } @Test public void negativeCallOtherCompilationUnit() { conservativeHelper .addSourceLines( "Foo.java", // "class Foo {", " void foo(Integer i) {}", "}") .addSourceLines( "Bar.java", // "class Bar {", " void bar(Foo foo) {", " foo.foo(null);", " }", "}") .doTest(); } @Test public void negativeCallVarargs() { conservativeHelper .addSourceLines( "Foo.java", "class Foo {", " void foo(Integer... i) {}", " void bar() {", " foo(null, 1);", " }", "}") .doTest(); } }
13,459
25.759443
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsBrokenForNullTest.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.nullness; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author bhagwani@google.com (Sumit Bhagwani) */ @RunWith(JUnit4.class) public class EqualsBrokenForNullTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(EqualsBrokenForNull.class, getClass()); @Test public void positiveCase() { compilationHelper.addSourceFile("EqualsBrokenForNullPositiveCases.java").doTest(); } @Test public void negativeCase() { compilationHelper.addSourceFile("EqualsBrokenForNullNegativeCases.java").doTest(); } @Test public void negativeGenerics() { compilationHelper .addSourceLines( "Test.java", "class Test<A, B> {", " A a;", " B b;", " public boolean equals(Object other) {", " if (!(other instanceof Test<?, ?>)) {", " return false;", " }", " Test<?, ?> that = (Test<?, ?>) other;", " return a.equals(that.a) && b.equals(that.b);", " }", "}") .doTest(); } @Test public void nullableParameter() { compilationHelper .addSourceLines( "Test.java", "import java.util.Optional;", "class Test {", " public boolean equals(Object other) {", " if (other == null) {", " return false;", " }", " if (other instanceof Test) {", " Test otherTest = (Test) other;", " Optional.empty().map(x -> otherTest.toString());", " }", " return other.equals(this);", " }", "}") .doTest(); } }
2,501
29.144578
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/FieldMissingNullableTest.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.nullness; 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 kmb@google.com (Kevin Bierhoff) */ @RunWith(JUnit4.class) public class FieldMissingNullableTest { @Test public void literalNullAssignment() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class FieldMissingNullTest {", " private String message = \"hello\";", " public void reset() {", " // BUG: Diagnostic contains: @Nullable", " message = null;", " }", "}") .doTest(); } @Test public void definiteNullAssignment() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class FieldMissingNullTest {", " private String message = \"hello\";", " public void setMessage(String message) {", " // BUG: Diagnostic contains: @Nullable", " this.message = message != null ? null : message;", " }", "}") .doTest(); } @Test public void assignmentInsideIfNull() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class FieldMissingNullTest {", " private String message;", " public void setMessage(String message) {", " if (message == null) {", " // BUG: Diagnostic contains: @Nullable", " this.message = message;", " } else {", " this.message = \"hello\";", " }", " }", "}") .doTest(); } @Test public void maybeNullAssignment() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class FieldMissingNullTest {", " private String message = \"hello\";", " public void setMessage(int x) {", " // BUG: Diagnostic contains: @Nullable", " message = x >= 0 ? null : \"negative\";", " }", "}") .doTest(); } @Test public void nullInitializer() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NullableParameterTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class NullableParameterTest {", " // BUG: Diagnostic contains: @Nullable", " public static final String MESSAGE = null;", "}") .doTest(); } @Test public void maybeNullAssignmentInLambda() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NullableParameterTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class NullableParameterTest {", " private String message = \"hello\";", " public void setMessageIfPresent(java.util.Optional<String> message) {", // Note this code is bogus: s is guaranteed non-null... " // BUG: Diagnostic contains: @Nullable", " message.ifPresent(s -> { this.message = s != null ? s : null; });", " }", "}") .doTest(); } @Test public void comparisonToNull() { createAggressiveCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class FieldMissingNullTest {", " private String message;", " public void reset() {", " // BUG: Diagnostic contains: @Nullable", " if (message != null) {", " }", " }", "}") .doTest(); } @Test public void comparisonToNullOnOtherInstance() { createAggressiveCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class FieldMissingNullTest {", " private String message;", " public void reset(FieldMissingNullTest other) {", " // BUG: Diagnostic contains: @Nullable", " if (other.message != null) {", " }", " }", "}") .doTest(); } @Test public void negativeCases_comparisonToNullConservative() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class FieldMissingNullTest {", " private String message;", " public void reset() {", " if (message != null) {", " }", " }", "}") .doTest(); } @Test public void negativeCases_alreadyAnnotated() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class FieldMissingNullTest {", " @Nullable String message;", " public void reset() {", " this.message = null;", " }", "}") .doTest(); } @Test public void negativeCases_alreadyTypeAnnotated() { createCompilationTestHelper() .addSourceLines( "com/google/anno/my/Nullable.java", "package com.google.anno.my;", "import java.lang.annotation.ElementType;", "import java.lang.annotation.Target;", "@Target({ElementType.TYPE_USE})", "public @interface Nullable {}") .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import com.google.anno.my.Nullable;", "public class FieldMissingNullTest {", " @Nullable String message;", " public void reset() {", " this.message = null;", " }", "}") .doTest(); } @Test public void negativeCases_alreadyAnnotatedMonotonic() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.MonotonicNonNull;", "public class FieldMissingNullTest {", " private @MonotonicNonNull String message;", " public void reset() {", " if (message != null) {", " }", " }", "}") .doTest(); } @Test public void negativeCases_alreadyTypeAnnotatedInnerClass() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import org.checkerframework.checker.nullness.qual.Nullable;", "public class FieldMissingNullTest {", " class Inner {}", " @Nullable Inner message;", " public void reset() {", " this.message = null;", " }", "}") .doTest(); } @Test public void negativeCases_initializeWithNonNullLiteral() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class FieldMissingNullTest {", " private final String message;", " public FieldMissingNullTest() {", " message = \"hello\";", " }", "}") .doTest(); } @Test public void negativeCases_nonNullInitializer() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class FieldMissingNullTest {", " private String message = \"hello\";", "}") .doTest(); } @Test public void negativeCases_lambdaInitializer() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import java.util.function.Predicate;", "import java.util.function.Function;", "public class FieldMissingNullTest {", " private Runnable runnable = () -> {};", " private Predicate<?> predicate1 = p -> true;", " private Predicate<?> predicate2 = (p -> true);", " private Predicate<?> predicate3 = (String p) -> { return false; };", " private Function<?, ?> function1 = p -> null;", " private Function<?, ?> function2 = (p -> null);", " private Function<?, ?> function3 = (String p) -> { return null; };", "}") .doTest(); } @Test public void negativeCases_nonNullMethod() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NonNullMethodTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class NonNullMethodTest {", " private String message = \"hello\";", " public void setMessage(int x) {", " message = String.valueOf(x);", " }", "}") .doTest(); } @Test public void negativeCases_nonNullField() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NonNullFieldTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class NonNullFieldTest {", " private String message = \"hello\";", " private String previous = \"\";", " public void save() {", " previous = message;", " }", "}") .doTest(); } @Test public void negativeCases_nonNullParameter() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NonNullParameterTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class NonNullParameterTest {", " private String message = \"hello\";", " public void setMessage(String message) {", " this.message = message;", " }", "}") .doTest(); } @Test public void negativeCases_this() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/ThisTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class ThisTest {", " private static ThisTest theInstance = new ThisTest();", " public void makeDefault() {", " this.theInstance = this;", " }", "}") .doTest(); } /** * Makes sure the check never flags methods returning a primitive. Returning null from them is a * bug, of course, but we're not trying to find those bugs in this check. */ @Test public void negativeCases_primitiveFieldType() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/PrimitiveReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "public class PrimitiveReturnTest {", " private int count = (Integer) null;", "}") .doTest(); } @Test public void negativeCases_initializeWithLambda() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NullableParameterTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public class NullableParameterTest {", " private String message = \"hello\";", " public void setMessageIfPresent(java.util.Optional<String> message) {", " message.ifPresent(s -> { this.message = s; });", " }", "}") .doTest(); } // regression test for https://github.com/google/error-prone/issues/708 @Test public void i708() { createCompilationTestHelper() .addSourceLines( "Test.java", "import java.util.regex.Pattern;", "class T {", " private static final Pattern FULLY_QUALIFIED_METHOD_NAME_PATTERN =", " Pattern.compile(\"(.+)#([^()]+?)(\\\\((.*)\\\\))?\");", "}") .doTest(); } @Test public void suggestNonJsr305Nullable() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "class T {", " @Nullable private final Object obj1 = null;", " private final Object obj2 = null;", " @interface Nullable {}", "}") .addOutputLines( "out/Test.java", "class T {", " @Nullable private final Object obj1 = null;", " @Nullable private final Object obj2 = null;", " @interface Nullable {}", "}") .doTest(TEXT_MATCH); } @Test public void annotationInsertedAfterModifiers() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " private final Object obj1 = null;", "}") .addOutputLines( "out/Test.java", "import org.checkerframework.checker.nullness.qual.Nullable;", "class T {", " private final @Nullable Object obj1 = null;", "}") .doTest(TEXT_MATCH); } @Test public void nonAnnotationNullable() { createRefactoringTestHelper() .addInputLines( "in/Test.java", "class T {", " private final Object obj2 = null;", " class Nullable {}", "}") .addOutputLines( "out/Test.java", "class T {", " private final @org.jspecify.nullness.Nullable Object obj2 = null;", " class Nullable {}", "}") .doTest(); } private CompilationTestHelper createCompilationTestHelper() { return CompilationTestHelper.newInstance(FieldMissingNullable.class, getClass()); } private CompilationTestHelper createAggressiveCompilationTestHelper() { return createCompilationTestHelper().setArgs("-XepOpt:Nullness:Conservative=false"); } private BugCheckerRefactoringTestHelper createRefactoringTestHelper() { return BugCheckerRefactoringTestHelper.newInstance(FieldMissingNullable.class, getClass()); } }
17,096
34.767782
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/testdata/UnnecessaryCheckNotNullNegativeCase.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.nullness.testdata; public class UnnecessaryCheckNotNullNegativeCase { public void go_checkNotNull() { Preconditions.checkNotNull("this is ok"); } public void go_verifyNotNull() { Verify.verifyNotNull("this is ok"); } public void go_requireNonNull() { Objects.requireNonNull("this is ok"); } private static class Preconditions { static void checkNotNull(String string) { System.out.println(string); } } private static class Verify { static void verifyNotNull(String string) { System.out.println(string); } } private static class Objects { static void requireNonNull(String string) { System.out.println(string); } } public void go() { Object testObj = null; com.google.common.base.Preconditions.checkNotNull(testObj, "this is ok"); com.google.common.base.Verify.verifyNotNull(testObj, "this is ok"); java.util.Objects.requireNonNull(testObj, "this is ok"); } }
1,615
27.350877
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/testdata/UnnecessaryCheckNotNullPrimitivePositiveCases.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.nullness.testdata; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Preconditions; public class UnnecessaryCheckNotNullPrimitivePositiveCases { private Tester field = new Tester(); public void test() { Object a = new Object(); Object b = new Object(); byte byte1 = 0; short short1 = 0; int int1 = 0, int2 = 0; long long1 = 0; float float1 = 0; double double1 = 0; boolean boolean1 = false, boolean2 = false; char char1 = 0; Tester tester = new Tester(); // Do we detect all primitive types? // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull(byte1); // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull(short1); // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull(int1); // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull(long1); // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull(float1); // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull(double1); // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull(boolean1); // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull(char1); // Do we give the right suggested fix? // BUG: Diagnostic contains: boolean1 = boolean2; boolean1 = Preconditions.checkNotNull(boolean2); // BUG: Diagnostic contains: boolean1 = int1 == int2; boolean1 = Preconditions.checkNotNull(int1 == int2); // BUG: Diagnostic contains: checkState(tester.hasId()) Preconditions.checkNotNull(tester.hasId()); // BUG: Diagnostic contains: checkState(tester.hasId(), "Must have ID!") Preconditions.checkNotNull(tester.hasId(), "Must have ID!"); // BUG: Diagnostic contains: checkState(tester.hasId(), "Must have %s!", "ID") Preconditions.checkNotNull(tester.hasId(), "Must have %s!", "ID"); // Do we handle arguments that evaluate to a primitive type? // BUG: Diagnostic contains: Preconditions.checkNotNull(a) Preconditions.checkNotNull(a != null); // BUG: Diagnostic contains: Preconditions.checkNotNull(a) Preconditions.checkNotNull(a == null); // BUG: Diagnostic contains: checkState(int1 == int2) Preconditions.checkNotNull(int1 == int2); // BUG: Diagnostic contains: checkState(int1 > int2) Preconditions.checkNotNull(int1 > int2); // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull(boolean1 ? int1 : int2); // Do we handle static imports? // BUG: Diagnostic contains: remove this line checkNotNull(byte1); // BUG: Diagnostic contains: 'checkState(tester.hasId()) checkNotNull(tester.hasId()); } public void test2(Tester arg) { Tester local = new Tester(); // Do we correctly distinguish checkArgument from checkState? // BUG: Diagnostic contains: checkArgument(arg.hasId()) checkNotNull(arg.hasId()); // BUG: Diagnostic contains: checkState(field.hasId()) checkNotNull(field.hasId()); // BUG: Diagnostic contains: checkState(local.hasId()) checkNotNull(local.hasId()); // BUG: Diagnostic contains: checkState(!local.hasId()) checkNotNull(!local.hasId()); // BUG: Diagnostic contains: checkArgument(!(arg instanceof Tester)) checkNotNull(!(arg instanceof Tester)); // BUG: Diagnostic contains: checkState(getTrue()) checkNotNull(getTrue()); // BUG: Diagnostic contains: remove this line checkNotNull(arg.getId()); // BUG: Diagnostic contains: id = arg.getId() int id = checkNotNull(arg.getId()); // BUG: Diagnostic contains: boolean b = arg.hasId(); boolean b = checkNotNull(arg.hasId()); // Do we handle long chains of method calls? // BUG: Diagnostic contains: checkArgument(arg.getTester().getTester().hasId()) checkNotNull(arg.getTester().getTester().hasId()); // BUG: Diagnostic contains: checkArgument(arg.tester.getTester().hasId()) checkNotNull(arg.tester.getTester().hasId()); } private boolean getTrue() { return true; } private static class Tester { public Tester tester; public boolean hasId() { return true; } public int getId() { return 10; } public Tester getTester() { return tester; } } }
5,025
32.731544
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/testdata/UnnecessaryCheckNotNullPositiveCase.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.nullness.testdata; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verifyNotNull; import static java.util.Objects.requireNonNull; import com.google.common.base.Preconditions; import com.google.common.base.Verify; import java.util.Objects; public class UnnecessaryCheckNotNullPositiveCase { public void error_checkNotNull() { // BUG: Diagnostic contains: remove this line Preconditions.checkNotNull("string literal"); // BUG: Diagnostic contains: remove this line checkNotNull("string literal"); String thing = null; // BUG: Diagnostic contains: (thing, checkNotNull("thing is null", thing); // BUG: Diagnostic contains: Preconditions.checkNotNull("a string literal " + "that's got two parts", thing); } public void error_verifyNotNull() { // BUG: Diagnostic contains: remove this line Verify.verifyNotNull("string literal"); // BUG: Diagnostic contains: remove this line verifyNotNull("string literal"); String thing = null; // BUG: Diagnostic contains: (thing, verifyNotNull("thing is null", thing); // BUG: Diagnostic contains: Verify.verifyNotNull("a string literal " + "that's got two parts", thing); } public void error_requireNonNull() { // BUG: Diagnostic contains: remove this line Objects.requireNonNull("string literal"); // BUG: Diagnostic contains: remove this line requireNonNull("string literal"); String thing = null; // BUG: Diagnostic contains: (thing, requireNonNull("thing is null", thing); // BUG: Diagnostic contains: Objects.requireNonNull("a string literal " + "that's got two parts", thing); } public void error_fully_qualified_import_checkNotNull() { // BUG: Diagnostic contains: remove this line com.google.common.base.Preconditions.checkNotNull("string literal"); } public void error_fully_qualified_import_verifyNotNull() { // BUG: Diagnostic contains: remove this line com.google.common.base.Verify.verifyNotNull("string literal"); } public void error_fully_qualified_import_requireNonNull() { // BUG: Diagnostic contains: remove this line java.util.Objects.requireNonNull("string literal"); } }
2,907
33.211765
84
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/testdata/EqualsBrokenForNullNegativeCases.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.nullness.testdata; /** * Negative test cases for EqualsBrokenForNull check. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class EqualsBrokenForNullNegativeCases { private class ExplicitNullCheckFirst { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!getClass().equals(obj.getClass())) { return false; } return true; } } private class CheckWithSuperFirst { @Override public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } if (!getClass().equals(obj.getClass())) { return false; } return true; } } private class NullCheckAndObjectGetClassNotEqualTo { @Override public boolean equals(Object o) { if (o == null || this.getClass() != o.getClass()) { return false; } return true; } } private class NullCheckAndObjectGetClassArgToEquals { @Override public boolean equals(Object obj) { if (obj != null && !getClass().equals(obj.getClass())) { return false; } return true; } } private class NullCheckAndObjectGetClassReceiverToEquals { @Override public boolean equals(Object obj) { if (obj != null && !obj.getClass().equals(getClass())) { return false; } return true; } } private class NullCheckAndObjectGetClassLeftOperandDoubleEquals { @Override public boolean equals(Object other) { if (other != null && other.getClass() == NullCheckAndObjectGetClassLeftOperandDoubleEquals.class) { return true; } return false; } } private class UsesInstanceOfWithNullCheck { @Override public boolean equals(Object other) { if (other != null && other instanceof UsesInstanceOfWithNullCheck) { return true; } return false; } } // https://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof private class UsesInstanceOfWithoutNullCheck { private int a; @Override public boolean equals(Object other) { if (other instanceof UsesInstanceOfWithoutNullCheck) { UsesInstanceOfWithoutNullCheck that = (UsesInstanceOfWithoutNullCheck) other; return that.a == a; } return false; } } private class IntermediateBooleanVariable { private int a; @Override public boolean equals(Object other) { boolean isEqual = other instanceof IntermediateBooleanVariable; if (isEqual) { IntermediateBooleanVariable that = (IntermediateBooleanVariable) other; return that.a == a; } return isEqual; } } private class UnsafeCastWithNullCheck { private int a; @Override public boolean equals(Object o) { if (o == null) { return false; } UnsafeCastWithNullCheck that = (UnsafeCastWithNullCheck) o; return that.a == a; } } }
3,654
24.381944
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/testdata/UnsoundGenericMethod.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.nullness.testdata; import static java.util.stream.Collectors.toList; import java.util.List; import java.util.function.Function; import java.util.stream.Stream; public class UnsoundGenericMethod { public interface Marker {} public interface Converter<T extends Marker> { List<?> convert(T input); } // error below can be avoided here with "class Impl<T extends Marker> ..." private static class Impl<T> implements Function<T, List<?>> { private final Stream<Converter<? super T>> cs; private Impl(Stream<Converter<? super T>> cs) { this.cs = cs; } @Override public List<?> apply(T input) { // BUG: Diagnostic contains: Unsafe wildcard in inferred type argument return cs.map(c -> new Wrap<>(c).handle(input)).collect(toList()); } } private static class Wrap<T extends Marker> { Wrap(Converter<? super T> unused) {} T handle(T input) { return input; } } public static void main(String... args) { // BUG: Diagnostic contains: impossible new Impl<>(Stream.of(null, null)).apply("boom"); } }
1,740
28.016667
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/testdata/EqualsBrokenForNullPositiveCases.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.nullness.testdata; /** * Positive test cases for EqualsBrokenForNull check. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class EqualsBrokenForNullPositiveCases { private class ObjectGetClassArgToEquals { @Override // BUG: Diagnostic contains: if (obj == null) { return false; } public boolean equals(Object obj) { if (!getClass().equals(obj.getClass())) { return false; } return true; } } private class ObjectGetClassArgToEqualsMultiLine { @Override // BUG: Diagnostic contains: if (obj == null) { return false; } public boolean equals(Object obj) { if (this == obj) { return true; } if (!getClass().equals(obj.getClass())) { return false; } return true; } } private class ObjectGetClassArgToIsAssignableFrom { @Override // BUG: Diagnostic contains: if (obj == null) { return false; } public boolean equals(Object obj) { if (!getClass().isAssignableFrom(obj.getClass())) { return false; } return true; } } private class ObjectGetClassArgToEquals2 { @Override // BUG: Diagnostic contains: if (obj == null) { return false; } public boolean equals(Object obj) { if (!ObjectGetClassArgToEquals2.class.equals(obj.getClass())) { return false; } return true; } } private class ObjectGetClassReceiverToEquals { @Override // BUG: Diagnostic contains: if (obj == null) { return false; } public boolean equals(Object obj) { if (!obj.getClass().equals(getClass())) { return false; } return true; } } private class ObjectGetClassReceiverToEquals2 { @Override // BUG: Diagnostic contains: if (obj == null) { return false; } public boolean equals(Object obj) { if (!obj.getClass().equals(ObjectGetClassReceiverToEquals2.class)) { return false; } return true; } } private class ObjectGetClassReceiverToIsAssignableFrom { @Override // BUG: Diagnostic contains: if (obj == null) { return false; } public boolean equals(Object obj) { if (!obj.getClass().isAssignableFrom(getClass())) { return false; } return true; } } private class ObjectGetClassLeftOperandDoubleEquals { @Override // BUG: Diagnostic contains: if (other == null) { return false; } public boolean equals(Object other) { if (other.getClass() == ObjectGetClassLeftOperandDoubleEquals.class) { return true; } return false; } } private class ObjectGetClassRightOperandDoubleEquals { @Override // BUG: Diagnostic contains: if (other == null) { return false; } public boolean equals(Object other) { if (ObjectGetClassRightOperandDoubleEquals.class == other.getClass()) { return true; } return false; } } private class ObjectGetClassLeftOperandNotEquals { @Override // BUG: Diagnostic contains: if (obj == null) { return false; } public boolean equals(Object obj) { if (obj.getClass() != ObjectGetClassLeftOperandNotEquals.class) { return false; } return true; } } private class ObjectGetClassRightOperandNotEquals { @Override // BUG: Diagnostic contains: if (obj == null) { return false; } public boolean equals(Object obj) { if (ObjectGetClassRightOperandNotEquals.class != obj.getClass()) { return false; } return true; } } private class UnusedNullCheckWithNotEqualToInLeftOperand { @Override // BUG: Diagnostic contains: if (o == null) { return false; } public boolean equals(Object o) { if (this.getClass() != o.getClass() || o == null) { return false; } return true; } } private class UnusedNullCheckWithGetClassInEqualsArg { @Override // BUG: Diagnostic contains: if (o == null) { return false; } public boolean equals(Object o) { if (this.getClass().equals(o.getClass()) || o == null) { return false; } return true; } } private class UnsafeCastAndNoNullCheck { private int a; @Override // BUG: Diagnostic contains: if (o == null) { return false; } public boolean equals(Object o) { UnsafeCastAndNoNullCheck that = (UnsafeCastAndNoNullCheck) o; return that.a == a; } } // Catch a buggy instanceof check that lets nulls through. private class VerySillyInstanceofCheck { private int a; @Override // BUG: Diagnostic contains: if (o == null) { return false; } public boolean equals(Object o) { if (o != null && !(o instanceof VerySillyInstanceofCheck)) { return false; } VerySillyInstanceofCheck that = (VerySillyInstanceofCheck) o; return that.a == a; } } }
5,502
26.792929
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/nullness/testdata/UnnecessaryCheckNotNullPrimitiveNegativeCases.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.nullness.testdata; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Preconditions; public class UnnecessaryCheckNotNullPrimitiveNegativeCases { public void test() { Object obj1 = new Object(); Preconditions.checkNotNull(obj1); checkNotNull(obj1); Preconditions.checkNotNull(obj1, "obj1 should not be null"); Preconditions.checkNotNull(obj1, "%s should not be null", "obj1"); Preconditions.checkNotNull(obj1.toString()); } }
1,153
32.941176
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/formatstring/FormatStringTest.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.formatstring; import static org.junit.Assume.assumeTrue; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link FormatString}Test */ @RunWith(JUnit4.class) public class FormatStringTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(FormatString.class, getClass()); private void testFormat(String expected, String formatString) { compilationHelper .addSourceLines( "Test.java", "import java.util.Locale;", "import java.io.PrintWriter;", "import java.io.PrintStream;", "import java.io.Console;", "class Test {", " void f() {", " // BUG: Diagnostic contains: " + expected, " " + formatString, " }", "}") .doTest(); } @Test public void duplicateFormatFlags() throws Exception { testFormat("duplicate format flags: +", "String.format(\"e = %++10.4f\", Math.E);"); } @Test public void formatFlagsConversionMismatch() throws Exception { testFormat( "format specifier '%b' is not compatible with the given flag(s): #", "String.format(\"%#b\", Math.E);"); } @Test public void illegalFormatCodePoint() throws Exception { testFormat("invalid Unicode code point: 110000", "String.format(\"%c\", 0x110000);"); } @Test public void illegalFormatConversion() throws Exception { testFormat( "illegal format conversion: 'java.lang.String' cannot be formatted using '%f'", "String.format(\"%f\", \"abcd\");"); } @Test public void illegalFormatFlags() throws Exception { testFormat("illegal format flags: -0", "String.format(\"%-010d\", 5);"); } @Test public void illegalFormatPrecision() throws Exception { testFormat("illegal format precision: 1", "String.format(\"%.1c\", 'c');"); } @Test public void illegalFormatWidth() throws Exception { testFormat("illegal format width: 1", "String.format(\"%1n\");"); } @Test public void missingFormatArgument() throws Exception { testFormat("missing argument for format specifier '%<s'", "String.format(\"%<s\", \"test\");"); } @Test public void missingFormatWidth() throws Exception { testFormat("missing format width: %-f", "String.format(\"e = %-f\", Math.E);"); } @Test public void unknownFormatConversion() throws Exception { testFormat("unknown format conversion: 'r'", "String.format(\"%r\", \"hello\");"); } @Test public void cStyleLongConversion() throws Exception { testFormat("use %d to format integral types", "String.format(\"%l\", 42);"); } @Test public void cStyleLongConversion2() throws Exception { testFormat("use %d to format integral types", "String.format(\"%ld\", 42);"); } @Test public void cStyleLongConversion3() throws Exception { testFormat("use %d to format integral types", "String.format(\"%lld\", 42);"); } @Test public void cStyleLongConversion4() throws Exception { testFormat("%f, %g or %e to format floating point types", "String.format(\"%lf\", 42);"); } @Test public void cStyleLongConversion5() throws Exception { testFormat("%f, %g or %e to format floating point types", "String.format(\"%llf\", 42);"); } @Test public void conditionalExpression() throws Exception { testFormat( "missing argument for format specifier '%s'", "String.format(true ? \"\" : \"%s\");"); } @Test public void conditionalExpression2() throws Exception { testFormat( "missing argument for format specifier '%s'", "String.format(true ? \"%s\" : \"\");"); } @Test public void conditionalExpression3() throws Exception { testFormat( "extra format arguments: used 1, provided 2", "String.format(true ? \"%s\" : \"%s\", 1, 2);"); } @Test public void conditionalExpression4() throws Exception { testFormat( "extra format arguments: used 1, provided 2", "String.format(true ? \"%s\" : \"%s\", 1, 2);"); } @Test public void conditionalExpression5() throws Exception { testFormat( "missing argument for format specifier '%s'", "String.format(true ? \"%s\" : true ? \"%s\" : \"\");"); } @Test public void missingArguments() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f() {", " // BUG: Diagnostic contains: missing argument for format specifier '%s'", " String.format(\"%s %s %s\", 42);", " // BUG: Diagnostic contains: missing argument for format specifier '%s'", " String.format(\"%s %s %s\", 42, 42);", " String.format(\"%s %s %s\", 42, 42, 42);", " }", "}") .doTest(); } @Test public void extraArguments() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f() {", " String.format(\"%s %s\", 1, 2);", " // BUG: Diagnostic contains: extra format arguments: used 2, provided 3", " String.format(\"%s %s\", 1, 2, 3);", " // BUG: Diagnostic contains: extra format arguments: used 2, provided 4", " String.format(\"%s %s\", 1, 2, 3, 4);", " // BUG: Diagnostic contains: extra format arguments: used 0, provided 1", " String.format(\"{0}\", 1);", " }", "}") .doTest(); } @Test public void negative() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f(boolean b) {", " String.format(\"%d\", 42);", " String.format(\"%d\", 42L);", " String.format(\"%f\", 42.0f);", " String.format(\"%f\", 42.0d);", " String.format(\"%s\", \"hello\");", " String.format(\"%s\", 42);", " String.format(\"%s\", (Object) null);", " String.format(\"%s\", new Object());", " String.format(\"%c\", 'c');", " String.format(b ? \"%s\" : \"%d\", 42);", " }", "}") .doTest(); } @Test public void printfMethods_stringFormat() throws Exception { testFormat("", "String.format(\"%d\", \"hello\");"); } @Test public void printfMethods_stringFormatWithLocale() throws Exception { testFormat("", "String.format(Locale.ENGLISH, \"%d\", \"hello\");"); } @Test public void printfMethods_printWriterFormat() throws Exception { testFormat("", "new PrintWriter(System.err).format(\"%d\", \"hello\");"); } @Test public void printfMethods_printWriterFormatWithLocale() throws Exception { testFormat("", "new PrintWriter(System.err).format(Locale.ENGLISH, \"%d\", \"hello\");"); } @Test public void printfMethods_printWriterPrintf() throws Exception { testFormat("", "new PrintWriter(System.err).printf(\"%d\", \"hello\");"); } @Test public void printfMethods_printWriterPrintfWithLocale() throws Exception { testFormat("", "new PrintWriter(System.err).printf(Locale.ENGLISH, \"%d\", \"hello\");"); } @Test public void printfMethods_printStreamFormat() throws Exception { testFormat("", "new PrintStream(System.err).format(\"%d\", \"hello\");"); } @Test public void printfMethods_printStreamFormatWithLocale() throws Exception { testFormat("", "new PrintStream(System.err).format(Locale.ENGLISH, \"%d\", \"hello\");"); } @Test public void printfMethods_printStreamPrintf() throws Exception { testFormat("", "new PrintStream(System.err).printf(\"%d\", \"hello\");"); } @Test public void printfMethods_printStreamPrintfWithLocale() throws Exception { testFormat("", "new PrintStream(System.err).printf(Locale.ENGLISH, \"%d\", \"hello\");"); } @Test public void printfMethods_formatterFormatWithLocale() throws Exception { testFormat( "", "new java.util.Formatter(System.err).format(Locale.ENGLISH, \"%d\", \"hello\");"); } @Test public void printfMethods_consolePrintf() throws Exception { testFormat("", "System.console().printf(\"%d\", \"hello\");"); } @Test public void printfMethods_consoleFormat() throws Exception { testFormat("", "System.console().format(\"%d\", \"hello\");"); } @Test public void printfMethods_consoleFormat_noErrorsWithEmptyArgs() throws Exception { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f() {", " System.console().readLine();", " }", "}") .doTest(); } @Test public void printfMethods_consoleReadline() throws Exception { testFormat("", "System.console().readLine(\"%d\", \"hello\");"); } @Test public void printfMethods_consoleReadPassword() throws Exception { testFormat("", "System.console().readPassword(\"%d\", \"hello\");"); } @Test public void nullArgument() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f() {", " String.format(\"%s %s\", null, null);", " }", "}") .doTest(); } @Test public void javaUtilTime() { compilationHelper .addSourceLines( "Test.java", "import java.time.*;", "class Test {", " void f() {", " System.err.printf(\"%tY\",", " LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()));", " System.err.printf(\"%tQ\", Instant.now());", " System.err.printf(\"%tZ\", ZonedDateTime.of(LocalDate.of(2018, 12, 27)," + " LocalTime.of(17, 0), ZoneId.of(\"Europe/London\")));", " }", "}") .doTest(); } @Test public void number() { compilationHelper .addSourceLines( "Test.java", "class Test {", " void f(Number n) {", " System.err.printf(\"%x\", n);", " }", "}") .doTest(); } @Test public void invalidIndex() { assumeTrue(RuntimeVersion.isAtLeast16()); compilationHelper .addSourceLines( "T.java", "class T {", " public static void main(String[] args) {", " // BUG: Diagnostic contains: Illegal format argument index", " System.err.printf(\" %0$2s) %s\", args[0], args[1]);", " }", "}") .doTest(); } @Test public void stringFormattedNegativeCase() { assumeTrue(RuntimeVersion.isAtLeast15()); compilationHelper .addSourceLines( "Test.java", "class Test {", " void f() {", " \"%s %s\".formatted(\"foo\", \"baz\");", " }", "}") .doTest(); } @Test public void stringFormattedPositiveCase() { assumeTrue(RuntimeVersion.isAtLeast15()); compilationHelper .addSourceLines( "Test.java", "class Test {", " void f() {", " // BUG: Diagnostic contains: missing argument for format specifier", " \"%s %s %s\".formatted(\"foo\", \"baz\");", " }", "}") .doTest(); } @Test public void nonConstantStringFormattedNegativeCase() { assumeTrue(RuntimeVersion.isAtLeast15()); compilationHelper .addSourceLines( "Test.java", "class Test {", " void f(String f) {", " f.formatted(\"foo\", \"baz\");", " }", "}") .doTest(); } }
12,629
29.65534
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/formatstring/InlineFormatStringTest.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.formatstring; 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 InlineFormatString}Test */ @RunWith(JUnit4.class) public class InlineFormatStringTest { private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(InlineFormatString.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InlineFormatString.class, getClass()); @Test public void refactoring() { refactoringHelper .addInputLines( "Test.java", "class Test {", " private static final String FORMAT = \"hello %s\";", " void f() {", " System.err.printf(FORMAT, 42);", " }", "}") .addOutputLines( "Test.java", "class Test {", " void f() {", " System.err.printf(\"hello %s\", 42);", " }", "}") .doTest(); } @Test public void negative_multiple() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private static final String FORMAT = \"hello %s\";", " void f() {", " System.err.printf(FORMAT, 42);", " System.err.printf(FORMAT, 43);", " }", "}") .doTest(); } @Test public void negative_otherUsers() { compilationHelper .addSourceLines( "Test.java", "class Test {", " private static final String FORMAT = \"hello %s\";", " void f() {", " System.err.printf(FORMAT, 42);", " System.err.println(FORMAT);", " }", "}") .doTest(); } @Test public void refactoring_precondition() { refactoringHelper .addInputLines( "Test.java", "import com.google.common.base.Preconditions;", "class Test {", " private static final String FORMAT = \"hello %s\";", " void f(boolean b) {", " Preconditions.checkArgument(b, FORMAT, 42);", " }", "}") .addOutputLines( "Test.java", "import com.google.common.base.Preconditions;", "class Test {", " void f(boolean b) {", " Preconditions.checkArgument(b, \"hello %s\", 42);", " }", "}") .doTest(); } @Test public void refactoring_formatMethod() { refactoringHelper .addInputLines( "Test.java", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "abstract class Test {", " @FormatMethod abstract String f(String f, Object... args);", " @FormatMethod abstract String g(boolean b, @FormatString String f, Object... args);", " private static final String FORMAT = \"hello %s\";", " private static final String FORMAT2 = \"hello %s\";", " void h(boolean b) {", " f(FORMAT, 42);", " g(b, FORMAT2, 42);", " }", "}") .addOutputLines( "Test.java", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "abstract class Test {", " @FormatMethod abstract String f(String f, Object... args);", " @FormatMethod abstract String g(boolean b, @FormatString String f, Object... args);", " void h(boolean b) {", " f(\"hello %s\", 42);", " g(b, \"hello %s\", 42);", " }", "}") .doTest(); } @Test public void suppression() { compilationHelper .addSourceLines( "Test.java", "class Test {", " @SuppressWarnings(\"InlineFormatString\")", " private static final String FORMAT = \"hello %s\";", " void f() {", " System.err.printf(FORMAT, 42);", " }", "}") .doTest(); } @Test public void suppressionClass() { compilationHelper .addSourceLines( "Test.java", "@SuppressWarnings(\"InlineFormatString\")", "class Test {", " private static final String FORMAT = \"hello %s\";", " void f() {", " System.err.printf(FORMAT, 42);", " }", "}") .doTest(); } }
5,476
31.02924
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/formatstring/FormatStringAnnotationCheckerTest.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.formatstring; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link FormatStringAnnotationChecker}Test. */ @RunWith(JUnit4.class) public class FormatStringAnnotationCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(FormatStringAnnotationChecker.class, getClass()); @Test public void matches_failsWithNonMatchingFormatArgs() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " @FormatMethod public static void log(@FormatString String s, Object... args) {}", " @FormatMethod public static void callLog(@FormatString String s, Object arg,", " Object arg2) {", " // BUG: Diagnostic contains: The number of format arguments passed with an", " log(s, \"test\");", " // BUG: Diagnostic contains: The format argument types passed with an", " log(s, \"test1\", \"test2\");", " }", "}") .doTest(); } @Test public void matches_succeedsWithMatchingFormatStringAndArgs() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " @FormatMethod public static void log(@FormatString String s, Object... args) {}", " @FormatMethod public static void callLog(@FormatString String s, Object arg) {", " log(s, arg);", " }", "}") .doTest(); } @Test public void matches_succeedsForMatchingFormatMethodWithImplicitFormatString() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " @FormatMethod public static void log(@FormatString String s, Object... args) {}", " @FormatMethod public static void callLog(String s, Object arg) {", " log(s, arg);", " }", "}") .doTest(); } @Test public void matches_failsWithMismatchedFormatString() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " @FormatMethod public static void log(@FormatString String s, Object... args) {}", " public static void callLog() {", " // BUG: Diagnostic contains: extra format arguments: used 1, provided 2", " log(\"%s\", new Object(), new Object());", " }", "}") .doTest(); } @Test public void matches_succeedsForCompileTimeConstantFormatString() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " @FormatMethod public static void log(@FormatString String s, Object... args) {}", " public static void callLog() {", " final String formatString = \"%d\";", " log(formatString, Integer.valueOf(0));", " }", "}") .doTest(); } @Test public void matches_failsWhenExpressionGivenForFormatString() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "public class FormatStringTestCase {", " @FormatMethod static void log(String s, Object... args) {}", " public static String formatString() { return \"\";}", " public static void callLog() {", " String format = \"log: \";", " // BUG: Diagnostic contains: Format strings must be either literals or", " log(format + 3);", " // BUG: Diagnostic contains: Format strings must be either literals or", " log(formatString());", " }", "}") .doTest(); } @Test public void matches_failsForInvalidMethodHeaders() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " // BUG: Diagnostic contains: A method cannot have more than one @FormatString", " @FormatMethod void log1(@FormatString String s1, @FormatString String s2) {}", " // BUG: Diagnostic contains: An @FormatMethod must contain at least one String", " @FormatMethod void log2(Object o) {}", " // BUG: Diagnostic contains: Only strings can be annotated @FormatString.", " @FormatMethod void log3(@FormatString Object o) {}", " // BUG: Diagnostic contains: A parameter can only be annotated @FormatString in a", " void log4(@FormatString Object o) {}", "}") .doTest(); } @Test public void matches_failsForIncorrectStringParameterUsedWithImplicitFormatString() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " @FormatMethod public static void log(@FormatString String s, Object... args) {}", " @FormatMethod public static void callLog1(String format, String s, Object arg) {", " // BUG: Diagnostic contains: Format strings must be compile time constants or", " log(s, arg);", " }", " @FormatMethod public static void callLog2(String s, @FormatString String format,", " Object arg) {", " // BUG: Diagnostic contains: Format strings must be compile time constants or", " log(s, arg);", " }", "}") .doTest(); } @Test public void matches_succeedsForNonParameterFinalOrEffectivelyFinalFormatStrings() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " private static final String validFormat = \"foo\";", " @FormatMethod public static void log(@FormatString String s, Object... args) {}", " public static void callLog1() {", " final String fmt1 = \"foo%s\";", " log(fmt1, new Object());", // Effectively final " String fmt2 = \"foo%s\";", " log(fmt2, new Object());", " log(validFormat);", " }", "}") .doTest(); } @Test public void matches_failsForNonFinalParametersOrNonMatchingFinalParameters() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " final String invalidFormat;", " private static final String validFormat = \"foo%s\";", " public FormatStringTestCase() {", " invalidFormat = \"foo\";", " }", " @FormatMethod public static void log(@FormatString String s, Object... args) {}", " public void callLog() {", " final String fmt1 = \"foo%s\";", " // BUG: Diagnostic contains: missing argument for format specifier '%s'", " log(fmt1);", // Effectively final " String fmt2 = \"foo%s\";", " // BUG: Diagnostic contains: missing argument for format specifier '%s'", " log(fmt2);", // Still effectively final, but multiple assignments is invalid " String fmt3;", " if (true) {", " fmt3 = \"foo%s\";", " } else {", " fmt3 = \"bar%s\";", " }", " // BUG: Diagnostic contains: must be initialized", " log(fmt3);", " String fmt4 = fmt3;", " // BUG: Diagnostic contains: Local format string variables must only be assigned", " log(fmt4);", " String fmt5 = \"foo\";", // This makes fmt5 no longer effectively final " fmt5 += 'a';", " // BUG: Diagnostic contains: All variables passed as @FormatString must be final", " log(fmt5);", " // BUG: Diagnostic contains: Variables used as format strings that are not local", " log(invalidFormat);", " // BUG: Diagnostic contains: missing argument for format specifier '%s'", " log(validFormat);", " }", "}") .doTest(); } @Test public void matches_failsForBadCallToConstructor() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " @FormatMethod public FormatStringTestCase(String s, Object... args) {}", " public static void createTestCase(String s, Object arg) {", " // BUG: Diagnostic contains: Format strings must be compile time constants or", " new FormatStringTestCase(s, arg);", " }", "}") .doTest(); } @Test public void matches_succeedsForMockitoMatchers() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import static org.mockito.ArgumentMatchers.any;", "import static org.mockito.ArgumentMatchers.eq;", "import static org.mockito.Mockito.verify;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " @FormatMethod public void log(@FormatString String s, Object... args) {}", " public void callLog(String s, Object... args) {", " verify(this).log(any(String.class), eq(args));", " }", "}") .doTest(); } @Test public void matches_succeedsForMockitoArgumentMatchers() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import static org.mockito.ArgumentMatchers.any;", "import static org.mockito.ArgumentMatchers.eq;", "import static org.mockito.Mockito.verify;", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "public class FormatStringTestCase {", " @FormatMethod public void log(@FormatString String s, Object... args) {}", " public void callLog(String s, Object... args) {", " verify(this).log(any(String.class), eq(args));", " }", "}") .doTest(); } @Test public void negative_noFormatString() { compilationHelper .addSourceLines( "test/FormatStringTestCase.java", "package test;", "import com.google.errorprone.annotations.FormatMethod;", "public class FormatStringTestCase {", " // BUG: Diagnostic contains: must contain at least one String parameter", " @FormatMethod public static void log(int x, int y) {}", " void test() { ", " log(1, 2);", " }", "}") .doTest(); } }
14,015
40.964072
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/MissingSummaryTest.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.javadoc; 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 MissingSummary} bug pattern. */ @RunWith(JUnit4.class) public final class MissingSummaryTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(MissingSummary.class, getClass()); private final CompilationTestHelper helper = CompilationTestHelper.newInstance(MissingSummary.class, getClass()); @Test public void replaceReturn() { refactoring .addInputLines( "Test.java", // "interface Test {", " /**", " * @param n foo", " * @return n", " */", " int test(int n);", "}") .addOutputLines( "Test.java", // "interface Test {", " /**", " * Returns n.", " *", " * @param n foo", " */", " int test(int n);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void replaceSee() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * @param n foo", " * @see List other impl", " */", " void test(int n);", " /**", " * @param n foo", " * @see List", " */", " void test2(int n);", "}") .addOutputLines( "Test.java", "interface Test {", " /**", " * See {@link List other impl}.", " *", " * @param n foo", " */", " void test(int n);", " /**", " * See {@link List}.", " *", " * @param n foo", " */", " void test2(int n);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void publicCase() { helper .addSourceLines( "Test.java", "// BUG: Diagnostic contains: @see", "/** @see another thing */", "public interface Test {", " // BUG: Diagnostic contains: @return", " /** @return foo */", " int test();", "}") .doTest(); } @Test public void privateCase() { helper .addSourceLines( "Test.java", // "class Test {", " /** @throws IllegalStateException */", " private void test() {}", "}") .doTest(); } @Test public void effectivelyPrivateCase() { helper .addSourceLines( "Test.java", // "class Test {", " private class Inner {", " /** @throws IllegalStateException */", " public void test() {}", " }", "}") .doTest(); } @Test public void negative() { helper .addSourceLines( "Test.java", "interface Test {", " /**", " * Summary line!", " *", " * @return n", " */", " int test();", "}") .doTest(); } @Test public void negativeAnnotations() { helper .addSourceLines( "Test.java", "class Test {", " /** @param o thing to compare */", " @Override public boolean equals(Object o) { return true; }", " /** @deprecated use something else */", " @Deprecated public void frobnicate() {}", "}") .doTest(); } @Test public void negativeConstructor() { helper .addSourceLines( "Test.java", "class Test {", " /** @param o thing to compare */", " public Test(Object o) {}", "}") .doTest(); } @Test public void negativePrivate() { helper .addSourceLines( "Test.java", "class Test {", " /** @param o thing to compare */", " private Test(Object o) {}", "}") .doTest(); } @Test public void negativeOverride() { helper .addSourceLines( "Test.java", "class Test implements java.util.function.Predicate<Object> {", " /** @param o thing to compare */", " public boolean test(Object o) { return false; }", "}") .doTest(); } @Test public void seeWithHtmlLink() { helper .addSourceLines( "Test.java", "// BUG: Diagnostic contains:", "/** @see <a href=\"foo\">bar</a> */", "public interface Test {}") .doTest(); } @Test public void emptyReturn() { helper .addSourceLines( "Test.java", // "interface Test {", " // BUG: Diagnostic contains:", " /** @return */", " int test(int n);", "}") .doTest(); } @Test public void emptyComment() { helper .addSourceLines( "Test.java", // "package test;", "/** */", "// BUG: Diagnostic contains: summary line is required", "public class Test {", "}") .doTest(); } }
6,308
25.178423
84
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/NotJavadocTest.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.javadoc; 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; @RunWith(JUnit4.class) public final class NotJavadocTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(NotJavadoc.class, getClass()); @Test public void notJavadoc() { helper .addInputLines( "Test.java", // "class Test {", " void test() {", " /** Not Javadoc. */", " }", "}") .addOutputLines( "Test.java", // "class Test {", " void test() {", " /* Not Javadoc. */", " }", "}") .doTest(TEXT_MATCH); } @Test public void doubleJavadoc() { helper .addInputLines( "Test.java", // "class Test {", // It would be nice if this were caught. " /** Not Javadoc. */", " /** Javadoc. */", " void test() {", " }", "}") .expectUnchanged() .doTest(); } @Test public void notJavadocOnLocalClass() { helper .addInputLines( "Test.java", "class Test {", " void test() {", " /** Not Javadoc. */", " class A {}", " }", "}") .addOutputLines( "Test.java", "class Test {", " void test() {", " /* Not Javadoc. */", " class A {}", " }", "}") .doTest(TEXT_MATCH); } @Test public void notJavadocWithLotsOfAsterisks() { helper .addInputLines( "Test.java", "class Test {", " void test() {", " /******** Not Javadoc. */", " class A {}", " }", "}") .addOutputLines( "Test.java", "class Test {", " void test() {", " /* Not Javadoc. */", " class A {}", " }", "}") .doTest(TEXT_MATCH); } @Test public void actuallyJavadoc() { helper .addInputLines( "Test.java", // "class Test {", " /** Not Javadoc. */", " void test() {", " }", "}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void strangeComment() { helper .addInputLines( "Test.java", // "class Test {", " void test() {", " /**/", " }", "}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void packageLevel() { helper .addInputLines( "package-info.java", // "/** Package javadoc */", "package foo;") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void moduleLevel() { helper .addInputLines( "module-info.java", // "/** Module javadoc */", "module foo {}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void suppression() { helper .addInputLines( "Test.java", // "class Test {", " @SuppressWarnings(\"NotJavadoc\")", " void test() {", " /** Not Javadoc. */", " }", "}") .expectUnchanged() .doTest(TEXT_MATCH); } }
4,382
23.903409
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/MalformedInlineTagTest.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.javadoc; 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; /** Unit tests for {@link MalformedInlineTag}. */ @RunWith(JUnit4.class) public final class MalformedInlineTagTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(MalformedInlineTag.class, getClass()); @Test public void positive_allInlineTags() { helper .addInputLines( "Test.java", "/** Here are a list of malformed tags: ", " * @{code code}", " * @{docRoot}", " * @{inheritDoc}", " * @{link Test}", " * @{linkplain Test}", " * @{literal literal}", " * @{value Test}", " */", "class Test {}") .addOutputLines( "Test.java", "/** Here are a list of malformed tags: ", " * {@code code}", " * {@docRoot}", " * {@inheritDoc}", " * {@link Test}", " * {@linkplain Test}", " * {@literal literal}", " * {@value Test}", " */", "class Test {}") .doTest(TEXT_MATCH); } @Test public void positive_withinTag() { helper .addInputLines( "Test.java", "class Test {", " /** Add one to value.", " * @param x an @{code int} value to increment", " * @return @{code x} + 1", " */", " int addOne(int x) { return x+1; }", "}") .addOutputLines( "Test.java", "class Test {", " /** Add one to value.", " * @param x an {@code int} value to increment", " * @return {@code x} + 1", " */", " int addOne(int x) { return x+1; }", "}") .doTest(TEXT_MATCH); } @Test public void positive_atLineEnd() { helper .addInputLines( "Test.java", "/** This malformed tag spans @{code", " * multiple lines}.", " */", "class Test {}") .addOutputLines( "Test.java", "/** This malformed tag spans {@code", " * multiple lines}.", " */", "class Test {}") .doTest(TEXT_MATCH); } @Test public void negative() { helper .addInputLines( "Test.java", // "/** A correct {@link Test} tag in text. */", "class Test {}") .expectUnchanged() .doTest(TEXT_MATCH); } @Test public void negative_invalidTag() { helper .addInputLines( "Test.java", // "/** This @{case} is not a known Javadoc tag. Ignore. */", "class Test {}") .expectUnchanged() .doTest(TEXT_MATCH); } }
3,713
28.47619
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidParamTest.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.javadoc; 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 org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link InvalidParam} bug pattern. */ @RunWith(JUnit4.class) public final class InvalidParamTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(InvalidParam.class, getClass()); private final CompilationTestHelper helper = CompilationTestHelper.newInstance(InvalidParam.class, getClass()); @Test public void badParameterName_positioning() { helper .addSourceLines( "Test.java", "interface Test {", " /**", " * @param <T> baz", " // BUG: Diagnostic contains: Parameter name `c` is unknown", " * @param c foo", " * @param b bar", " */", " <T> void foo(int a, int b);", "}") .doTest(); } @Test public void badParameterName() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * @param <T> baz", " * @param c foo", " * @param b bar", " */", " <T> void foo(int a, int b);", "}") .addOutputLines( "Test.java", "interface Test {", " /**", " * @param <T> baz", " * @param a foo", " * @param b bar", " */", " <T> void foo(int a, int b);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void badTypeParameterName() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * @param <S> baz", " * @param a bar", " */", " <T> void foo(int a);", "}") .addOutputLines( "Test.java", "interface Test {", " /**", " * @param <T> baz", " * @param a bar", " */", " <T> void foo(int a);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void verySimilarCodeParam() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * {@code foabar}, {@code barfoo}", " */", " void foo(int foobar);", "}") .addOutputLines( "Test.java", "interface Test {", " /**", " * {@code foobar}, {@code barfoo}", " */", " void foo(int foobar);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void verySimilarCodeParam_diagnosticMessage() { helper .addSourceLines( "Test.java", "interface Test {", " /**", " // BUG: Diagnostic contains: `foabar` is very close to the parameter `foobar`", " * {@code foabar}, {@code barfoo}", " */", " void foo(int foobar);", "}") .doTest(); } @Test public void negative() { helper .addSourceLines( "Test.java", "interface Test {", " /**", " * Frobnicates a {@code foobarbaz}.", " * @param <T> baz", " * @param a bar", " * @param b quux", " */", " <T> void foo(int a, int b, int foobarbaz);", "}") .doTest(); } @Test public void excludedName_noMatchDespiteSimilarParam() { helper .addSourceLines( "Test.java", "interface Test {", " /** Returns {@code true}. */", " boolean foo(int tree);", "}") .doTest(); } @Test public void negative_record() { assumeTrue(RuntimeVersion.isAtLeast16()); helper .addSourceLines( "Test.java", // "/**", " * @param name Name.", " */", "public record Test(String name) {}") .doTest(); } @Test public void badParameterName_record() { assumeTrue(RuntimeVersion.isAtLeast16()); helper .addSourceLines( "Test.java", "/**", " // BUG: Diagnostic contains: Parameter name `bar` is unknown", " * @param bar Foo.", " */", "public record Test(String foo) {}") .doTest(); } @Test public void multipleConstructors_record() { assumeTrue(RuntimeVersion.isAtLeast16()); helper .addSourceLines( "Test.java", "/**", " * @param foo Foo.", " * @param bar Bar.", " */", "public record Test(String foo, Integer bar) {", " public Test(Integer bar) {", " this(null, bar);", " }", "", " /**", " // BUG: Diagnostic contains: Parameter name `bar` is unknown", " * @param bar Foo.", " */", " public Test(String foo) {", " this(foo, null);", " }", "}") .doTest(); } @Test public void typeParameter_record() { assumeTrue(RuntimeVersion.isAtLeast16()); helper .addSourceLines( "Negative.java", "/**", " * @param <T> The type parameter.", " * @param contents Contents.", " * @param bar Bar.", " */", "public record Negative<T>(T contents, String bar) {}") .addSourceLines( "Positive.java", "/**", " // BUG: Diagnostic contains: Parameter name `E` is unknown", " * @param <E> The type parameter.", " * @param contents Contents.", " * @param bar Bar.", " */", "public record Positive<T>(T contents, String bar) {}") .doTest(); } @Test public void compactConstructor_record() { assumeTrue(RuntimeVersion.isAtLeast16()); helper .addSourceLines( "Test.java", "/**", " * @param name Name.", " */", "public record Test(String name) {", " public Test {}", "}") .doTest(); } @Test public void normalConstructor_record() { assumeTrue(RuntimeVersion.isAtLeast16()); helper .addSourceLines( "Test.java", "/**", " * @param name Name.", " */", "public record Test(String name) {", " /**", " // BUG: Diagnostic contains: Parameter name `foo` is unknown", " * @param foo Name.", " */", " public Test(String name) {", " this.name = name;", " }", " }") .doTest(); } }
7,980
27.102113
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidLinkTest.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.javadoc; 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; /** Unit tests for {@link InvalidLink} bug pattern. */ @RunWith(JUnit4.class) public final class InvalidLinkTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(InvalidLink.class, getClass()); private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(InvalidLink.class, getClass()); @Test public void httpLink() { refactoring .addInputLines( "Test.java", "interface Test {", " /** {@link http://foo/bar/baz} */", " void foo();", "}") .addOutputLines( "Test.java", "interface Test {", " /** <a href=\"http://foo/bar/baz\">link</a> */", " void foo();", "}") .doTest(TEXT_MATCH); } @Test public void httpLink_lineBreak() { refactoring .addInputLines( "Test.java", "interface Test {", " /** {@link http://foo/bar/baz", " * foo}", " */", " void foo();", "}") .addOutputLines( "Test.java", "interface Test {", " /** <a href=\"http://foo/bar/baz\">foo</a> */", " void foo();", "}") .doTest(TEXT_MATCH); } @Test public void badMethodLink() { helper .addSourceLines( "Test.java", "interface Test {", " // BUG: Diagnostic contains: The reference `#bar()` to a method doesn't resolve", " /** {@link #bar()} */", " void foo();", "}") .doTest(); } @Test public void badMethodLink_erasureHint() { helper .addSourceLines( "Test.java", "interface Test<T> {", " // BUG: Diagnostic contains: erasure", " /** {@link #bar(Test<String>)} */", " void foo(Test<String> foo);", "}") .doTest(); } @Test public void validLinks() { helper .addSourceLines( "Test.java", "import java.util.List;", "interface Test {", " /** {@link Test} {@link List} {@link IllegalArgumentException}", " * {@link #foo} {@link #foo()} */", " void foo();", "}") .doTest(); } @Test public void dontComplainAboutFullyQualified() { helper .addSourceLines( "Test.java", // "/** {@link i.dont.exist.B#foo} */", "interface A {}") .doTest(); } @Test public void shouldBeMethodLink() { refactoring .addInputLines( "Test.java", // "/** {@link frobnicate} */", "interface A {}") .addOutputLines( "Test.java", // "/** {@link #frobnicate} */", "interface A {}") .doTest(TEXT_MATCH); } @Test public void shouldBeParameterReference() { refactoring .addInputLines( "Test.java", "class Test {", " /** Pass in a {@link bar} */", " void foo(String bar) {}", "}") .addOutputLines( "Test.java", "class Test {", " /** Pass in a {@code bar} */", " void foo(String bar) {}", "}") .doTest(TEXT_MATCH); } @Test public void multiField() { helper .addSourceLines( "Param.java", // "@interface Param {", " String name() default \"\";", "}") .addSourceLines( "Test.java", // "@interface Test {", " /** Pass in a {@link Tuple<Object>} */", " Param extraPositionals() default @Param(name = \"\");", "}") .doTest(); } @Test public void emptyLinkTest() { helper .addSourceLines( "Test.java", // "interface Test {", " /** {@link} */", " void foo();", "}") .doTest(); } }
5,069
26.405405
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/ReturnFromVoidTest.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.javadoc; 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 ReturnFromVoid} bug pattern. */ @RunWith(JUnit4.class) public final class ReturnFromVoidTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(ReturnFromVoid.class, getClass()); @Test public void returnsVoid() { refactoring .addInputLines( "Test.java", // "interface Test {", " /**", " * @return anything", " */", " void foo();", "}") .addOutputLines( "Test.java", // "interface Test {", " /** */", " void foo();", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void negative() { CompilationTestHelper.newInstance(ReturnFromVoid.class, getClass()) .addSourceLines( "Test.java", // "interface Test {", " /**", " * @return anything", " */", " int foo();", "}") .doTest(); } }
2,007
29.424242
84
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/EmptyBlockTagTest.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.javadoc; 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 EmptyBlockTag} bug pattern. */ @RunWith(JUnit4.class) public final class EmptyBlockTagTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(EmptyBlockTag.class, getClass()); private final CompilationTestHelper compilationTestHelper = CompilationTestHelper.newInstance(EmptyBlockTag.class, getClass()); @Test public void removes_emptyParam() { refactoring .addInputLines( "Test.java", // "interface Test {", " /**", " * @param p", " */", " void foo(int p);", "}") .addOutputLines( "Test.java", // "interface Test {", " /** */", " void foo(int p);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void removes_emptyThrows() { refactoring .addInputLines( "Test.java", // "interface Test {", " /**", " * @throws Exception", " */", " void foo() throws Exception;", "}") .addOutputLines( "Test.java", // "interface Test {", " /** */", " void foo() throws Exception;", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void removes_emptyReturn() { refactoring .addInputLines( "Test.java", // "interface Test {", " /**", " * @return", " */", " int foo();", "}") .addOutputLines( "Test.java", // "interface Test {", " /** */", " int foo();", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void removes_emptyDeprecated() { refactoring .addInputLines( "Test.java", // "interface Test {", " /**", " * @deprecated", " */", " int foo();", "}") .expectUnchanged() .doTest(TestMode.TEXT_MATCH); } @Test public void removes_emptyDeprecatedOnClass() { compilationTestHelper .addSourceLines( "Test.java", // "/**", " // BUG: Diagnostic contains:", " * @deprecated", " */", "@Deprecated", "interface Test {", " void foo();", "}") .doTest(); } @Test public void removes_emptyParamOnClass() { refactoring .addInputLines( "Test.java", // "/**", " * @param <T>", " */", "interface Test<T> {", " T foo();", "}") .addOutputLines( "Test.java", // "/** */", "interface Test<T> {", " T foo();", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void removes_emptyAllTheThings() { refactoring .addInputLines( "Test.java", // "interface Test {", " /**", " * @param p", " * @return", " * @throws Exception", " */", " @Deprecated", " int foo(int p) throws Exception;", "}") .addOutputLines( "Test.java", // "interface Test {", " /** */", " @Deprecated", " int foo(int p) throws Exception;", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void keeps_paramWithDescription() { compilationTestHelper .addSourceLines( "Test.java", // "interface Test {", " /**", " * @param p is important", " */", " void foo(int p);", "}") .doTest(); } @Test public void keeps_throwsWithDescription() { compilationTestHelper .addSourceLines( "Test.java", // "interface Test {", " /**", " * @throws Exception because blah", " */", " void foo() throws Exception;", "}") .doTest(); } @Test public void keeps_returnWithDescription() { compilationTestHelper .addSourceLines( "Test.java", // "interface Test {", " /**", " * @return A value", " */", " int foo();", "}") .doTest(); } @Test public void keeps_deprecatedWithDescription() { compilationTestHelper .addSourceLines( "Test.java", // "interface Test {", " /**", " * @deprecated Very old", " */", " @Deprecated", " void foo();", "}") .doTest(); } @Test public void keeps_allTheThingsWithDescriptions() { compilationTestHelper .addSourceLines( "Test.java", // "interface Test {", " /**", " * @param p is important", " * @return a value", " * @throws Exception because", " * @deprecated Very old", " */", " @Deprecated", " int foo(int p) throws Exception;", "}") .doTest(); } @Test public void keeps_deprecatedOnClass() { compilationTestHelper .addSourceLines( "Test.java", // "/**", " * @deprecated Use other Test2 instead", " */", "@Deprecated", "interface Test {", " void foo();", "}") .doTest(); } @Test public void keeps_paramOnClass() { compilationTestHelper .addSourceLines( "Test.java", // "/**", " * @param <T> the input type param", " */", "interface Test<T> {", " T foo();", "}") .doTest(); } @Test public void keeps_whenSuppressed() { compilationTestHelper .addSourceLines( "Test.java", // "interface Test {", " /**", " * @param p", " */", " @SuppressWarnings(\"EmptyBlockTag\")", " void foo(int p);", "}") .doTest(); } }
7,435
24.819444
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InheritDocTest.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.javadoc; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link InheritDoc} bug pattern. */ @RunWith(JUnit4.class) public final class InheritDocTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(InheritDoc.class, getClass()); @Test public void nonOverridingMethod() { helper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: InheritDoc", " /** {@inheritDoc} */", " void test() {}", "}") .doTest(); } @Test public void overridingMethod() { helper .addSourceLines( "Test.java", "class Test {", " /** {@inheritDoc} */", " @Override public boolean equals(Object o) { return true; }", "}") .doTest(); } @Test public void nonOverridingClass() { helper .addSourceLines( "Test.java", "// BUG: Diagnostic contains: InheritDoc", "/** {@inheritDoc} */", "class Test {}") .doTest(); } @Test public void overridingClass() { helper .addSourceLines( "Test.java", // "/** {@inheritDoc} */", "class Test extends java.util.ArrayList {}") .doTest(); } @Test public void variable() { helper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains: InheritDoc", " /** {@inheritDoc} */", " private static final int a = 1;", "}") .doTest(); } }
2,408
26.067416
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidInlineTagTest.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.javadoc; import static org.junit.Assert.assertEquals; 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 InvalidInlineTag} bug pattern. */ @RunWith(JUnit4.class) public final class InvalidInlineTagTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(InvalidInlineTag.class, getClass()); private final CompilationTestHelper helper = CompilationTestHelper.newInstance(InvalidInlineTag.class, getClass()); @Test public void typo() { refactoring .addInputLines( "Test.java", // "interface Test {", " /** @return anything {@lnk #foo} */", " void foo();", "}") .addOutputLines( "Test.java", // "interface Test {", " /** @return anything {@link #foo} */", " void foo();", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void outsideEditDistanceLimit() { helper .addSourceLines( "Test.java", "class Test {", " // BUG: Diagnostic contains:", " /** {@SoFarOutsideEditLimit} */", " void test() {}", "}") .doTest(); } @Test public void isAType() { refactoring .addInputLines( "SomeType.java", "interface SomeType {", " /** {@SomeType} {@com.google.common.labs.ClearlyAType} */", " void foo();", "}") .addOutputLines( "SomeType.java", "interface SomeType {", " /** {@link SomeType} {@link com.google.common.labs.ClearlyAType} */", " void foo();", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void isAQualifiedType() { refactoring .addInputLines( "SomeType.java", "interface SomeType {", " /** {@SomeType.A} */", " void foo();", " interface A {}", "}") .addOutputLines( "SomeType.java", "interface SomeType {", " /** {@link SomeType.A} */", " void foo();", " interface A {}", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void parameterInlineTag() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * Provide an {@a}", " */", " void foo(int a);", "}") .addOutputLines( "Test.java", "interface Test {", " /**", " * Provide an {@code a}", " */", " void foo(int a);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void improperParam() { refactoring .addInputLines( "Test.java", "interface Test {", " /** Blah", " * {@param a}, {@param b} */", " void foo(int a);", "}") .addOutputLines( "Test.java", "interface Test {", " /** Blah", " * {@code a}, {@param b} */", " void foo(int a);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void inlineParam() { helper .addSourceLines( "Test.java", "interface Test {", " // BUG: Diagnostic contains:", " /** Frobnicates a @param foo. */", " void frobnicate(String foo);", "}") .doTest(); } @Test public void inlineParamIncorrectlyWrapped() { refactoring .addInputLines( "Test.java", "interface Test {", " /** Frobnicates a @code{foo}. */", " void frobnicate(String foo);", "}") .addOutputLines( "Test.java", "interface Test {", " /** Frobnicates a {@code foo}. */", " void frobnicate(String foo);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void parensRatherThanCurlies() { helper .addSourceLines( "Test.java", "interface Test {", " // BUG: Diagnostic contains: tags: {@code", " /** Frobnicates a (@code foo). */", " void frobnicate(String foo);", "}") .doTest(); } @Test public void parensRatherThanCurliesRefactoring() { refactoring .addInputLines( "Test.java", "interface Test {", " /** Frobnicates a (@code foo). */", " void frobnicate(String foo);", "}") .addOutputLines( "Test.java", "interface Test {", " /** Frobnicates a {@code foo}. */", " void frobnicate(String foo);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void parensRatherThanCurly_matchesBraces() { refactoring .addInputLines( "Test.java", "interface Test {", " /** Frobnicates a (@link #foo()). */", " void frobnicate(String foo);", "}") .addOutputLines( "Test.java", "interface Test {", " /** Frobnicates a {@link #foo()}. */", " void frobnicate(String foo);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void erroneousTag_doesNotMungeEntireJavadoc() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * Frobnicates a {@code foo).", " * @param foo {@link #foo}", " */", " void frobnicate(String foo);", "}") .expectUnchanged() .doTest(TestMode.TEXT_MATCH); } @Test public void invalidTagMessage() { assertEquals( "@type is not a valid tag, but is a parameter name. Use {@code type} to refer to parameter" + " names inline.", InvalidInlineTag.getMessageForInvalidTag("type")); } }
7,104
27.194444
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidThrowsTest.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.javadoc; 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; /** Unit tests for {@link InvalidThrows} bug pattern. */ @RunWith(JUnit4.class) public final class InvalidThrowsTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(InvalidThrows.class, getClass()); @Test public void positive() { refactoring .addInputLines( "Test.java", "import java.io.IOException;", "interface Test {", " /**", " * @throws IOException when failed", " */", " void foo(int a, int b);", "}") .addOutputLines( "Test.java", "import java.io.IOException;", "interface Test {", " /** */", " void foo(int a, int b);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void negative() { refactoring .addInputLines( "Test.java", "import java.io.IOException;", "interface Test {", " /**", " * @throws IOException when failed", " */", " void bar(int a, int b) throws IOException;", " /**", " * @throws IOException when failed", " */", " void baz(int a, int b) throws Exception;", "}") .expectUnchanged() .doTest(TestMode.TEXT_MATCH); } @Test public void unrecognisedException_noComplaint() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * @throws com.google.UnknownRuntimeException when failed", " */", " void bar(int a, int b);", "}") .expectUnchanged() .doTest(TestMode.TEXT_MATCH); } @Test public void throwsInvalidType() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * @throws bar when failed", " */", " void foo();", " void bar();", "}") .expectUnchanged() .doTest(TestMode.TEXT_MATCH); } }
3,070
28.528846
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/EscapedEntityTest.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.javadoc; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link EscapedEntity} bug pattern. */ @RunWith(JUnit4.class) public final class EscapedEntityTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(EscapedEntity.class, getClass()); @Test public void positive_decimalEscape() { helper .addSourceLines( "Test.java", // "// BUG: Diagnostic contains:", "/** {@code &#064;Override} */", "interface Test {}") .doTest(); } @Test public void positive_hexEscape() { helper .addSourceLines( "Test.java", // "// BUG: Diagnostic contains:", "/** {@code &#x52;Override} */", "interface Test {}") .doTest(); } @Test public void positive_characterReferemce() { helper .addSourceLines( "Test.java", // "// BUG: Diagnostic contains:", "/** {@code A &amp; B} */", "interface Test {}") .doTest(); } @Test public void negative() { helper .addSourceLines( "Test.java", // "/** <pre> &#064;Override </pre> */", "interface Test {}") .doTest(); } }
2,024
26.739726
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidThrowsLinkTest.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.javadoc; 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; /** Unit tests for {@link InvalidThrows} bug pattern. */ @RunWith(JUnit4.class) public final class InvalidThrowsLinkTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(InvalidThrowsLink.class, getClass()); @Test public void positive() { refactoring .addInputLines( "Test.java", "import java.io.IOException;", "interface Test {", " /**", " * @throws {@link IOException} when failed", " */", " void foo(int a, int b) throws IOException;", "}") .addOutputLines( "Test.java", "import java.io.IOException;", "interface Test {", " /**", " * @throws IOException when failed", " */", " void foo(int a, int b) throws IOException;", "}") .doTest(TEXT_MATCH); } @Test public void negative() { refactoring .addInputLines( "Test.java", "import java.io.IOException;", "interface Test {", " /**", " * @throws IOException when failed", " */", " void foo(int a, int b) throws IOException;", "}") .expectUnchanged() .doTest(TEXT_MATCH); } }
2,269
30.527778
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/UnescapedEntityTest.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.javadoc; import static org.junit.Assume.assumeFalse; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link UnescapedEntity} bug pattern. */ @RunWith(JUnit4.class) public final class UnescapedEntityTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(UnescapedEntity.class, getClass()); private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(UnescapedEntity.class, getClass()); @Test public void positive() { refactoring .addInputLines( "Test.java", // "/** List<Foo>, Map<Foo, Bar> */", "interface Test {}") .addOutputLines( "Test.java", // "/** {@code List<Foo>}, {@code Map<Foo, Bar>} */", "interface Test {}") .doTest(TestMode.AST_MATCH); } @Test public void negative() { helper .addSourceLines( "Test.java", // "/** {@code List<Foo>, Map<Foo, Bar>} */", "interface Test {}") .doTest(); } @Test public void unescapedEntities_off() { refactoring .addInputLines( "Test.java", // "/** Foo & bar < */", "interface Test {}") .expectUnchanged() .doTest(TestMode.TEXT_MATCH); } @Test public void withinPre() { refactoring .addInputLines( "Test.java", "/**", " * <pre>Foo</pre>", " * <pre>Use an ImmutableMap<String,Object> please</pre>", " * <pre>bar</pre>", " */", "interface Test {}") .addOutputLines( "Test.java", "/**", " * <pre>Foo</pre>", " * <pre>{@code Use an ImmutableMap<String,Object> please}</pre>", " * <pre>bar</pre>", " */", "interface Test {}") .doTest(TestMode.TEXT_MATCH); } @Test public void withinPre_singleChar() { refactoring .addInputLines( "Test.java", // "/**", " * <pre>n < 3</pre>", " */", "interface Test {}") .addOutputLines( "Test.java", // "/**", " * <pre>{@code n < 3}</pre>", " */", "interface Test {}") .doTest(TestMode.TEXT_MATCH); } @Test public void withinPre_alreadyEscaped() { assumeFalse(RuntimeVersion.isAtLeast15()); // https://bugs.openjdk.java.net/browse/JDK-8241780 refactoring .addInputLines( "Test.java", "/**", " * <pre>Use an ImmutableMap<String, Object> not a Map&lt;String, Object&gt;</pre>", " */", "interface Test {}") .addOutputLines( "Test.java", "/**", " * <pre>Use an ImmutableMap&lt;String, Object&gt; not a" + " Map&lt;String, Object&gt;</pre>", " */", "interface Test {}") .doTest(TestMode.TEXT_MATCH); } @Test public void withinPre_hasAnnotations() { assumeFalse(RuntimeVersion.isAtLeast15()); // https://bugs.openjdk.java.net/browse/JDK-8241780 refactoring .addInputLines( "Test.java", "/**", " * Foo", " *", " * <pre>", " * @Override", " * ImmutableMap<String, Object>", " * </pre>", " */", "interface Test {}") .addOutputLines( "Test.java", "/**", " * Foo", " *", " * <pre>", " * @Override", " * ImmutableMap&lt;String, Object&gt;", " * </pre>", " */", "interface Test {}") .doTest(TestMode.TEXT_MATCH); } @Test public void escapesWithoutAddingCodeBlock_withinPreBlockWithAnnotation() { assumeFalse(RuntimeVersion.isAtLeast15()); // https://bugs.openjdk.java.net/browse/JDK-8241780 refactoring .addInputLines( "Test.java", "/**", " * Foo", " *", " * <pre>", " * {@literal @}Override", " * ImmutableMap<String, Object>", " * </pre>", " */", "interface Test {}") .addOutputLines( "Test.java", "/**", " * Foo", " *", " * <pre>", " * {@literal @}Override", " * ImmutableMap&lt;String, Object&gt;", " * </pre>", " */", "interface Test {}") .doTest(TestMode.TEXT_MATCH); } @Test public void correctFindingPosition_withinPreBlock() { helper .addSourceLines( "Test.java", "/**", " * Foo", " *", " * <pre>", " * {@literal @}Override", " // BUG: Diagnostic contains: UnescapedEntity", " * ImmutableMap<String, Object>", " * </pre>", " */", "interface Test {}") .doTest(); } @Test public void withinLink() { helper .addSourceLines( "Test.java", // "/** {@link List<Foo>} */", "interface Test {}") .doTest(); } @Test public void withinSee() { helper .addSourceLines( "Test.java", // "import java.util.List;", "interface Test {", " /** @see #foo(List<Integer>) */", " void foo(List<Integer> foos);", "}") .doTest(); } @Test public void badSee() { helper .addSourceLines( "Test.java", // "import java.util.List;", "interface Test {", " /** @see <a href=\"http://google.com\">google</a> */", " void foo(List<Integer> foos);", "}") .doTest(); } @Test public void extraClosingTag() { refactoring .addInputLines( "Test.java", // "/** <pre>Foo List<Foo> bar</pre></pre> */", "interface Test {}") .addOutputLines( "Test.java", // "/** <pre>{@code Foo List<Foo> bar}</pre></pre> */", "interface Test {}") .doTest(TestMode.TEXT_MATCH); } @Test public void nestedGenericType_properlyEscaped() { refactoring .addInputLines( "Test.java", // "/** List<List<Integer>> */", "interface Test {}") .addOutputLines( "Test.java", // "/** {@code List<List<Integer>>} */", "interface Test {}") .doTest(TestMode.TEXT_MATCH); } }
7,740
27.459559
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/AlmostJavadocTest.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.javadoc; 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; /** Unit tests for {@link AlmostJavadoc} bug pattern. */ @RunWith(JUnit4.class) public final class AlmostJavadocTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(AlmostJavadoc.class, getClass()); private final CompilationTestHelper helper = CompilationTestHelper.newInstance(AlmostJavadoc.class, getClass()); @Test public void refactoring() { refactoring .addInputLines( "Test.java", // "public class Test {", " /* Foo {@link Test}. */", " void foo() {}", " /*", " * Bar.", " *", " * @param bar bar", " */", " void bar (int bar) {}", "}") .addOutputLines( "Test.java", // "public class Test {", " /** Foo {@link Test}. */", " void foo() {}", " /**", " * Bar.", " *", " * @param bar bar", " */", " void bar (int bar) {}", "}") .doTest(TEXT_MATCH); } @Test public void notJavadocButNoTag() { helper .addSourceLines( "Test.java", // "public class Test {", " /* Foo. */", " void foo() {}", "}") .doTest(); } @Test public void blockCommentWithMultilineClose() { refactoring .addInputLines( "Test.java", // "interface Test {", " // Foo. {@link Test} */", " void foo();", " // ** Bar. {@link Test} */", " void bar();", " // /** Baz. {@link Test} */", " void baz();", "}") .addOutputLines( "Test.java", // "interface Test {", " /** Foo. {@link Test} */", " void foo();", " /** Bar. {@link Test} */", " void bar();", " /** Baz. {@link Test} */", " void baz();", "}") .doTest(TEXT_MATCH); } @Test public void pathlogicalBlockCommentCases() { helper .addSourceLines( "Test.java", // "interface Test {", " // */", " void foo();", " // bar /* bar */", " void bar();", " // Baz. */", " void baz();", " // ** Foobar. */", " void foobar();", " // /** Barbaz. */", " void barbaz();", "}") .doTest(); } @Test public void suppression() { helper .addSourceLines( "Test.java", // "public class Test {", " /* Foo {@link Test}. */", " @SuppressWarnings(\"AlmostJavadoc\")", " void foo() {}", "}") .doTest(); } @Test public void alreadyHasJavadoc_noMatch() { helper .addSourceLines( "Test.java", // "public class Test {", " /** Foo. */", " /* Strange extra documentation with {@link tags}. */", " void foo() {}", "}") .doTest(); } @Test public void htmlTag() { helper .addSourceLines( "Test.java", // "public class Test {", " /* Foo <em>Test</em>. */", " // BUG: Diagnostic contains:", " void foo() {}", "}") .doTest(); } @Test public void enumConstant() { helper .addSourceLines( "Test.java", // "public enum Test {", " /* Foo <em>Test</em>. */", " // BUG: Diagnostic contains:", " FOO", "}") .doTest(); } @Test public void abstractEnumConstant() { helper .addSourceLines( "Test.java", // "public enum Test {", " /* Foo <em>Test</em>. */", " // BUG: Diagnostic contains:", " FOO {", " @Override public String toString() {", " return null;", " }", " }", "}") .doTest(); } @Test public void multiField() { helper .addSourceLines( "Test.java", // "public class Test {", " /* Foo <em>Test</em>. */", " // BUG: Diagnostic contains:", " int x = 1, y = 2;", "}") .doTest(); } }
5,521
25.805825
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/UnrecognisedJavadocTagTest.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.javadoc; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link UnrecognisedJavadocTag}. */ @RunWith(JUnit4.class) public final class UnrecognisedJavadocTagTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(UnrecognisedJavadocTag.class, getClass()); @Test public void positive() { helper .addSourceLines( "Test.java", "/**", " * // BUG: Diagnostic contains:", " * <pre>{@code", " * foo() {", " * }</pre>", " */", "class Test {}") .doTest(); } @Test public void negative() { helper .addSourceLines( "Test.java", "/**", " * <pre>{@code", " * foo() {}", " * }</pre>", " */", "class Test {}") .doTest(); } @Test public void link() { helper .addSourceLines( "Test.java", "/**", " * // BUG: Diagnostic contains:", " * {@link Test)", " */", "class Test {}") .doTest(); } @Test public void correctLink() { helper .addSourceLines( "Test.java", // "/**", " * {@link Test}, {@link Bar}", " */", "class Test {}") .doTest(); } }
2,141
24.5
82
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/UrlInSeeTest.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.javadoc; 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; /** Unit tests for {@link UrlInSee}. */ @RunWith(JUnit4.class) public final class UrlInSeeTest { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(UrlInSee.class, getClass()); @Test public void positive() { helper .addInputLines( "Test.java", // "/**", " * @see http://foo for more details", "*/", "class Test {}") .addOutputLines( "Test.java", // "/**", " * See http://foo for more details", "*/", "class Test {}") .doTest(TEXT_MATCH); } @Test public void negative() { helper .addInputLines( "Test.java", // "/**", " * @see java.util.List", "*/", "class Test {}") .expectUnchanged() .doTest(TEXT_MATCH); } }
1,819
27.888889
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidBlockTagTest.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.javadoc; 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 InvalidBlockTag} bug pattern. */ @RunWith(JUnit4.class) public final class InvalidBlockTagTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(InvalidBlockTag.class, getClass()); private final CompilationTestHelper helper = CompilationTestHelper.newInstance(InvalidBlockTag.class, getClass()); @Test public void typo() { refactoring .addInputLines( "Test.java", // "interface Test {", " /** @return anything */", " void foo();", "}") .addOutputLines( "Test.java", // "interface Test {", " /** @return anything */", " void foo();", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void veryBadTypo_noSuggestion() { refactoring .addInputLines( "Test.java", // "interface Test {", " /** @returnFnargleBlargle anything */", " void foo();", "}") .expectUnchanged() .doTest(TestMode.TEXT_MATCH); } @Test public void otherAcceptedTags() { helper .addSourceLines( "Test.java", // "class Test {", " /** @hide */", " void test() {}", "}") .doTest(); } @Test public void inHtml() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * <code>", " * @Override", " * boolean equals(Object o);", " * </code>", " * @See Test", " * <pre>", " * @Override", " * boolean equals(Object o);", " * </pre>", " */", " void bar();", "}") .addOutputLines( "Test.java", "interface Test {", " /**", " * <code>", " * {@literal @}Override", " * boolean equals(Object o);", " * </code>", " * @see Test", " * <pre>", " * {@literal @}Override", " * boolean equals(Object o);", " * </pre>", " */", " void bar();", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void parameterBlockTag() { refactoring .addInputLines( "Test.java", "interface Test {", " /**", " * @a blah", " */", " void foo(int a);", "}") .addOutputLines( "Test.java", "interface Test {", " /**", " * @param a blah", " */", " void foo(int a);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void parameterBlockTag_finding() { helper .addSourceLines( "Test.java", "interface Test {", " /**", " // BUG: Diagnostic contains: {@code a}", " * @a blah", " */", " void foo(int a);", "}") .doTest(); } @Test public void inheritDoc() { refactoring .addInputLines( "Test.java", "interface Test {", " /** @inheritDoc */", " void frobnicate(String foo);", "}") .addOutputLines( "Test.java", "interface Test {", " /** {@inheritDoc} */", " void frobnicate(String foo);", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void java8Tags() { helper .addSourceLines( "Test.java", "/**", " * @apiNote does nothing", " * @implNote not implemented", " */", "class Test {}") .doTest(); } }
4,983
26.086957
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/AssertEqualsArgumentOrderCheckerTest.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.argumentselectiondefects; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for AssertEqualsArgumentOrderChecker */ @RunWith(JUnit4.class) public class AssertEqualsArgumentOrderCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(AssertEqualsArgumentOrderChecker.class, getClass()); @Test public void assertEqualsCheck_makesNoSuggestion_withOrderExpectedActual() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " void test(Object expected, Object actual) {", " assertEquals(expected, actual);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_makesNoSuggestion_withOrderExpectedActualAndMessage() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(String message, Object expected, Object actual) {};", " void test(Object expected, Object actual) {", " assertEquals(\"\", expected, actual);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_swapsArguments_withOrderActualExpected() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " void test(Object expected, Object actual) {", " // BUG: Diagnostic contains: assertEquals(expected, actual)", " // assertEquals(/* expected= */actual, /* actual= */expected)", " assertEquals(actual, expected);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_swapsArguments_withOrderActualExpectedAndMessage() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(String message, Object expected, Object actual) {};", " void test(Object expected, Object actual) {", " // BUG: Diagnostic contains: assertEquals(\"\", expected, actual)", " assertEquals(\"\", actual, expected);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_swapsArguments_withOnlyExpectedAsPrefix() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " abstract Object get();", " void test(Object expectedValue) {", " // BUG: Diagnostic contains: assertEquals(expectedValue, get())", " assertEquals(get(), expectedValue);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_swapsArguments_withLiteralForActual() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " void test(Object other) {", " // BUG: Diagnostic contains: assertEquals(1, other)", " assertEquals(other, 1);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_doesntSwap_withLiteralForExpected() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(String message, Object expected, Object actual) {};", " void test(Object other) {", " assertEquals(\"\",1, other);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_makeNoChange_withLiteralForBoth() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " void test() {", " assertEquals(2, 1);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_makeNoChange_ifSwapCreatesDuplicateCall() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " void test(Object expected, Object actual) {", " assertEquals(expected, actual);", " assertEquals(actual, expected);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_makesNoChange_withNothingMatching() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " void test(Object other1, Object other2) {", " assertEquals(other1, other2);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_makesNoChange_whenArgumentExtendsThrowable() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " void test(Exception exception) {", " try {", " throw exception;", " } catch (Exception expected) {", " assertEquals(exception,expected);", " }", " }", "}") .doTest(); } @Test public void assertEqualsCheck_makesNoChange_whenArgumentIsEnumMember() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " enum MyEnum {", " VALUE", " }", " void test(MyEnum expected) {", " assertEquals(MyEnum.VALUE, expected);", " }", "}") .doTest(); } @Test public void assertEqualsCheck_makesNoChange_withReturnedEnum() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " enum MyEnum {}", " abstract MyEnum enumValue();", " void test(Object other) {", " assertEquals(other, enumValue());", " }", "}") .doTest(); } @Test public void assertEqualsCheck_makesNoChange_withCommentedNames() { compilationHelper .addSourceLines( "ErrorProneTest.java", "abstract class ErrorProneTest {", " static void assertEquals(Object expected, Object actual) {};", " void test(Object expected, Object actual) {", " assertEquals(/* expected= */actual, /* actual= */expected);", " }", "}") .doTest(); } }
8,299
33.156379
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/AutoValueConstructorOrderCheckerTest.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.argumentselectiondefects; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for AutoValueConstructorOrderChecker */ @RunWith(JUnit4.class) public class AutoValueConstructorOrderCheckerTest { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(AutoValueConstructorOrderChecker.class, getClass()); @Test public void autoValueChecker_detectsSwap_withExactNames() { compilationHelper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "@AutoValue", "abstract class Test {", " abstract String valueOne();", " abstract String valueTwo();", " static Test create(String valueOne, String valueTwo) {", " // BUG: Diagnostic contains: new AutoValue_Test(valueOne, valueTwo)", " return new AutoValue_Test(valueTwo, valueOne);", " }", "}", "class AutoValue_Test extends Test {", " String valueOne() { return null; }", " String valueTwo() { return null; }", " AutoValue_Test(String valueOne, String valueTwo) {}", "}") .doTest(); } @Test public void autoValueChecker_ignoresSwap_withInexactNames() { compilationHelper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "@AutoValue", "abstract class Test {", " abstract String valueOne();", " abstract String valueTwo();", " static Test create(String valueOneArg, String valueTwoArg) {", " return new AutoValue_Test(valueTwoArg, valueOneArg);", " }", "}", "class AutoValue_Test extends Test {", " String valueOne() { return null; }", " String valueTwo() { return null; }", " AutoValue_Test(String valueOne, String valueTwo) {}", "}") .doTest(); } @Test public void autoValueChecker_makesNoSuggestion_withCorrectOrder() { compilationHelper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "@AutoValue", "abstract class Test {", " abstract String valueOne();", " abstract String valueTwo();", " static Test create(String valueOne, String valueTwo) {", " return new AutoValue_Test(valueOne, valueTwo);", " }", "}", "class AutoValue_Test extends Test {", " String valueOne() { return null; }", " String valueTwo() { return null; }", " AutoValue_Test(String valueOne, String valueTwo) {}", "}") .doTest(); } }
3,575
35.489796
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristicTest.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.argumentselectiondefects; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.collect.ImmutableList; import com.google.common.collect.Streams; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodInvocationTree; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for EnclosedByReverseHeuristic * * @author andrewrice@google.com (Andrew Rice) */ @RunWith(JUnit4.class) public class CreatesDuplicateCallHeuristicTest { /** A {@link BugChecker} which runs the CreatesDuplicateCallHeuristic and prints the result */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Runs CreateDuplicateCallHeuristic and prints the result") public static class CreatesDuplicateCallHeuristicChecker extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { ImmutableList<Parameter> formal = Parameter.createListFromVarSymbols(ASTHelpers.getSymbol(tree).getParameters()); Stream<Parameter> actual = Parameter.createListFromExpressionTrees(tree.getArguments()).stream(); Changes changes = Changes.create( formal.stream().map(f -> 1.0).collect(toImmutableList()), formal.stream().map(f -> 0.0).collect(toImmutableList()), Streams.zip(formal.stream(), actual, ParameterPair::create) .collect(toImmutableList())); boolean result = !new CreatesDuplicateCallHeuristic() .isAcceptableChange(changes, tree, ASTHelpers.getSymbol(tree), state); return buildDescription(tree).setMessage(String.valueOf(result)).build(); } } @Test public void createsDuplicateCall_returnsTrue_withDuplicateCallInMethod() { CompilationTestHelper.newInstance(CreatesDuplicateCallHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object first, Object second, Object normal) {", " // BUG: Diagnostic contains: true", " target(first, second);", " // BUG: Diagnostic contains: true", " target(first, second);", " }", "}") .doTest(); } @Test public void createsDuplicateCall_returnsTrue_withDuplicateCallInField() { CompilationTestHelper.newInstance(CreatesDuplicateCallHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " // BUG: Diagnostic contains: true", " Object o1 = target(getFirst(), getSecond());", " // BUG: Diagnostic contains: true", " Object o2 = target(getFirst(), getSecond());", " abstract Object getFirst();", " abstract Object getSecond();", " abstract Object target(Object first, Object second);", "}") .doTest(); } @Test public void createsDuplicateCall_returnsTrue_withDuplicateEnclosingMethod() { CompilationTestHelper.newInstance(CreatesDuplicateCallHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " void test(Object param1, Object param2) {", " // BUG: Diagnostic contains: true", " test(param1, param2);", " }", "}") .doTest(); } @Test public void createsDuplicateCall_returnsFalse_withNoDuplicateCall() { CompilationTestHelper.newInstance(CreatesDuplicateCallHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object param1, Object param2) {", " // BUG: Diagnostic contains: false", " target(param1, param2);", " }", "}") .doTest(); } @Test public void createsDuplicateCall_returnsFalse_withCallWithDifferentConstant() { CompilationTestHelper.newInstance(CreatesDuplicateCallHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1);", " void test() {", " // BUG: Diagnostic contains: false", " target(1);", " // BUG: Diagnostic contains: false", " target(2);", " }", "}") .doTest(); } }
5,846
37.215686
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/NameInCommentHeuristicTest.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.argumentselectiondefects; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.collect.ImmutableList; import com.google.common.collect.Streams; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodInvocationTree; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for NameInCommentHeuristic * * @author andrewrice@google.com (Andrew Rice) */ @RunWith(JUnit4.class) public class NameInCommentHeuristicTest { /** A {@link BugChecker} which runs the NameInCommentHeuristic and prints the result */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Runs NameInCommentHeuristic and prints the result") public static class NameInCommentHeuristicChecker extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { ImmutableList<Parameter> formal = Parameter.createListFromVarSymbols(ASTHelpers.getSymbol(tree).getParameters()); Stream<Parameter> actual = Parameter.createListFromExpressionTrees(tree.getArguments()).stream(); Changes changes = Changes.create( formal.stream().map(f -> 1.0).collect(toImmutableList()), formal.stream().map(f -> 0.0).collect(toImmutableList()), Streams.zip(formal.stream(), actual, ParameterPair::create) .collect(toImmutableList())); boolean result = !new NameInCommentHeuristic() .isAcceptableChange(changes, tree, ASTHelpers.getSymbol(tree), state); return buildDescription(tree).setMessage(String.valueOf(result)).build(); } } @Test public void nameInCommentHeuristic_returnsTrue_whereCommentMatchesFormalParameter() { CompilationTestHelper.newInstance(NameInCommentHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first);", " void test(Object first) {", " // BUG: Diagnostic contains: true", " target(first /* first */);", " }", "}") .doTest(); } @Test public void nameInCommentHeuristic_returnsTrue_wherePreceedingCommentWithEqualsMatchesFormalParameter() { CompilationTestHelper.newInstance(NameInCommentHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first);", " void test(Object first) {", " // BUG: Diagnostic contains: true", " target(/*first= */ first);", " }", "}") .doTest(); } @Test public void nameInCommentHeuristic_returnsTrue_wherePreceedingCommentHasEqualsSpacesAndExtraText() { CompilationTestHelper.newInstance(NameInCommentHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first);", " void test(Object first) {", " // BUG: Diagnostic contains: true", " target(/*note first = */ first);", " }", "}") .doTest(); } @Test public void nameInCommentHeuristic_returnsFalse_withNoComments() { CompilationTestHelper.newInstance(NameInCommentHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first);", " void test(Object first) {", " // BUG: Diagnostic contains: false", " target(first);", " }", "}") .doTest(); } @Test public void nameInCommentHeuristic_returnsFalse_withCommentNotMatchingFormalParameter() { CompilationTestHelper.newInstance(NameInCommentHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first);", " void test(Object first) {", " // BUG: Diagnostic contains: false", " target(first /* other */);", " }", "}") .doTest(); } @Test public void nameInCommentHeuristic_returnsTrue_whereLineCommentMatchesFormalParameter() { CompilationTestHelper.newInstance(NameInCommentHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object first, Object second) {", " // BUG: Diagnostic contains: true", " target(first, // first", " second);", " }", "}") .doTest(); } }
6,090
35.692771
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/EnclosedByReverseHeuristicTest.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.argumentselectiondefects; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodInvocationTree; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for EnclosedByReverseHeuristic * * @author andrewrice@google.com (Andrew Rice) */ @RunWith(JUnit4.class) public class EnclosedByReverseHeuristicTest { /** A {@link BugChecker} which runs the EnclosedByReverseHeuristic and prints the result */ @BugPattern( name = "EnclosedByReverseHeuristic", severity = SeverityLevel.ERROR, summary = "Run the EnclosedByReverseHeuristic and print result") public static class EnclosedByReverseHeuristicChecker extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { boolean result = !new EnclosedByReverseHeuristic(ImmutableSet.of("reverse")) .isAcceptableChange(Changes.empty(), tree, ASTHelpers.getSymbol(tree), state); return buildDescription(tree).setMessage(String.valueOf(result)).build(); } } @Test public void enclosedByReverse_returnsFalse_whenNotInReverse() { CompilationTestHelper.newInstance(EnclosedByReverseHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object first, Object second) {", " // BUG: Diagnostic contains: false", " target(second, first);", " }", "}") .doTest(); } @Test public void enclosedByReverse_returnsTrue_withinReverseMethod() { CompilationTestHelper.newInstance(EnclosedByReverseHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void reverse(Object first, Object second) {", " // BUG: Diagnostic contains: true", " target(second, first);", " }", "}") .doTest(); } @Test public void enclosedByReverse_returnsTrue_nestedInReverseClass() { CompilationTestHelper.newInstance(EnclosedByReverseHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Reverse {", " abstract void target(Object first, Object second);", " void test(Object first, Object second) {", " // BUG: Diagnostic contains: true", " target(second, first);", " }", "}") .doTest(); } }
3,841
36.300971
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ParameterTest.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.argumentselectiondefects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for Parameter * * @author andrewrice@google.com (Andrew Rice) */ @RunWith(JUnit4.class) public class ParameterTest { /** * A {@link BugChecker} that prints whether the type of first argument is assignable to the type * of the second one. */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Print whether the type of the first argument is assignable to the second one") public static class IsFirstAssignableToSecond extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { ImmutableList<Parameter> arguments = Parameter.createListFromExpressionTrees(tree.getArguments()); if (arguments.size() != 2) { return Description.NO_MATCH; } return buildDescription(tree) .setMessage(String.valueOf(arguments.get(0).isAssignableTo(arguments.get(1), state))) .build(); } } @Test public void isAssignableTo_returnsTrue_assigningIntegerToInt() { CompilationTestHelper.newInstance(IsFirstAssignableToSecond.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " void target(Integer integer, int i) {", " // BUG: Diagnostic contains: true", " target(integer, i);", " }", "}") .doTest(); } @Test public void isAssignableTo_returnsFalse_assigningObjectToInteger() { CompilationTestHelper.newInstance(IsFirstAssignableToSecond.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " void target(Object obj, Integer integer) {", " // BUG: Diagnostic contains: false", " target(obj, integer);", " }", "}") .doTest(); } @Test public void isAssignableTo_returnsTrue_assigningIntegerToObject() { CompilationTestHelper.newInstance(IsFirstAssignableToSecond.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " void target(Integer integer, Object obj) {", " // BUG: Diagnostic contains: true", " target(integer, obj);", " }", "}") .doTest(); } /** A {@link BugChecker} that prints the name extracted for the first argument */ @BugPattern(severity = SeverityLevel.ERROR, summary = "Print the name of the first argument") public static class PrintNameOfFirstArgument extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { List<? extends ExpressionTree> arguments = tree.getArguments(); if (arguments.isEmpty()) { return Description.NO_MATCH; } ExpressionTree argument = Iterables.getFirst(arguments, null); return buildDescription(tree).setMessage(Parameter.getArgumentName(argument)).build(); } } @Test public void getName_usesEnclosingClass_withThisPointer() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object o);", " void test() {", " // BUG: Diagnostic contains: Test", " target(this);", " }", "}") .doTest(); } @Test public void getName_usesConstructedClass_withNewClass() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object o);", " void test() {", " // BUG: Diagnostic contains: String", " target(new String());", " }", "}") .doTest(); } @Test public void getName_stripsPrefix_fromMethodWithGetPrefix() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract Object getValue();", " abstract void target(Object o);", " void test() {", " // BUG: Diagnostic contains: Value", " target(getValue());", " }", "}") .doTest(); } @Test public void getName_usesEnclosingClass_fromMethodOnlyContainingGetWithNoReceiver() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract Object get();", " abstract void target(Object o);", " void test() {", " // BUG: Diagnostic contains: Test", " target(get());", " }", "}") .doTest(); } @Test public void getName_usesReceiver_fromMethodOnlyContainingGet() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Other {", " abstract Object get();", "}", "abstract class Test {", " abstract void target(Object o);", " void test(Other otherObject) {", " // BUG: Diagnostic contains: otherObject", " target(otherObject.get());", " }", "}") .doTest(); } @Test public void getName_usesOwner_fromAnonymousClass() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Other {", " abstract Object get();", "}", "abstract class Test {", " abstract void target(Object o);", " void test() {", " // BUG: Diagnostic contains: Object", " target(new Object() {});", " }", "}") .doTest(); } @Test public void getName_usesOwner_fromThisInAnonymousClass() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Other {", " abstract Object get();", "}", "abstract class Test {", " abstract void target(Object o);", " void test() {", " new Object() {", " void test() {", " // BUG: Diagnostic contains: Object", " target(this);", " }", " };", " }", "}") .doTest(); } @Test public void getName_usesOwner_fromGetMethodInAnonymousClass() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Other {", " abstract Object get();", "}", "abstract class Test {", " abstract void target(Object o);", " void test() {", " new Object() {", " Integer get() {", " return 1;", " }", " void test() {", " // BUG: Diagnostic contains: Object", " target(get());", " }", " };", " }", "}") .doTest(); } @Test public void getName_returnsNull_withNullLiteral() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object o);", " void test() {", " // BUG: Diagnostic contains: " + Parameter.NAME_NULL, " target(null);", " }", "}") .doTest(); } @Test public void getName_returnsUnknown_withTerneryIf() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object o);", " void test(boolean flag) {", " // BUG: Diagnostic contains: " + Parameter.NAME_NOT_PRESENT, " target(flag ? 1 : 0);", " }", "}") .doTest(); } /** A {@link BugChecker} that prints whether the first argument is constant */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Print whether the first argument is constant") public static class PrintIsConstantFirstArgument extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { List<? extends ExpressionTree> arguments = tree.getArguments(); if (arguments.isEmpty()) { return Description.NO_MATCH; } ImmutableList<Parameter> parameters = Parameter.createListFromExpressionTrees(arguments); Parameter first = Iterables.getFirst(parameters, null); return buildDescription(tree).setMessage(String.valueOf(first.constant())).build(); } } @Test public void getName_returnsConstant_withConstant() { CompilationTestHelper.newInstance(PrintIsConstantFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object o);", " void test() {", " // BUG: Diagnostic contains: true", " target(1);", " }", "}") .doTest(); } @Test public void getName_returnsConstant_withConstantFromOtherClass() { CompilationTestHelper.newInstance(PrintIsConstantFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object o);", " void test() {", " // BUG: Diagnostic contains: true", " target(Double.MAX_VALUE);", " }", "}") .doTest(); } @Test public void getName_returnsNotConstant_withVariable() { CompilationTestHelper.newInstance(PrintIsConstantFirstArgument.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object o);", " void test(Object o) {", " // BUG: Diagnostic contains: false", " target(o);", " }", "}") .doTest(); } }
12,298
32.881543
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ArgumentSelectionDefectCheckerTest.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.argumentselectiondefects; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodInvocationTree; import java.util.function.Function; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link ArgumentSelectionDefectChecker}. * * @author andrewrice@google.com (Andrew Rice) */ @RunWith(JUnit4.class) public class ArgumentSelectionDefectCheckerTest { /** * A {@link BugChecker} which runs the ArgumentSelectionDefectChecker checker using string * equality for edit distance */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Run the ArgumentSelectionDefectChecker checker using string equality for edit distance") public static class ArgumentSelectionDefectWithStringEquality extends ArgumentSelectionDefectChecker { public ArgumentSelectionDefectWithStringEquality() { super(ArgumentChangeFinder.builder().setDistanceFunction(buildEqualityFunction()).build()); } } @Test public void argumentSelectionDefectChecker_findsSwap_withSwappedMatchingPair() { CompilationTestHelper.newInstance(ArgumentSelectionDefectWithStringEquality.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object first, Object second) {", " // BUG: Diagnostic contains: target(first, second)", " // target(/* first= */second, /* second= */first)", " target(second, first);", " }", "}") .doTest(); } @Test public void argumentSelectionDefectChecker_findsSwap_withSwappedMatchingPairWithMethod() { CompilationTestHelper.newInstance(ArgumentSelectionDefectWithStringEquality.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " abstract Object getSecond();", " void test(Object first) {", " // BUG: Diagnostic contains: target(first, getSecond())", " // target(/* first= */getSecond(), /* second= */first)", " target(getSecond(), first);", " }", "}") .doTest(); } @Test public void argumentSelectionDefectChecker_findsSwap_withOneNullArgument() { CompilationTestHelper.newInstance(ArgumentSelectionDefectWithStringEquality.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object second) {", " // BUG: Diagnostic contains: target(null, second)", " // target(/* first= */second, /* second= */null)", " target(second, null);", " }", "}") .doTest(); } @Test public void argumentSelectionDefectChecker_rejectsSwap_withNoAssignableAlternatives() { CompilationTestHelper.newInstance(ArgumentSelectionDefectWithStringEquality.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(String first, Integer second);", " void test(Integer first, String second) {", " target(second, first);", " }", "}") .doTest(); } @Test public void argumentSelectionDefectChecker_commentsOnlyOnSwappedPair_withThreeArguments() { CompilationTestHelper.newInstance(ArgumentSelectionDefectWithStringEquality.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second, Object third);", " void test(Object first, Object second, Object third) {", " // BUG: Diagnostic contains: target(first, second, third)", " // target(/* first= */second, /* second= */first, third)", " target(second, first, third);", " }", "}") .doTest(); } /** * A {@link BugChecker} which runs the ArgumentSelectionDefectChecker checker using string * equality for edit distance and ignores formal parameters called 'ignore'. */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Run the ArgumentSelectionDefectChecker checker with a heuristic that ignores formal " + "parameters") public static class ArgumentSelectionDefectWithIgnoredFormalsHeuristic extends ArgumentSelectionDefectChecker { public ArgumentSelectionDefectWithIgnoredFormalsHeuristic() { super( ArgumentChangeFinder.builder() .setDistanceFunction(buildEqualityFunction()) .addHeuristic(new LowInformationNameHeuristic(ImmutableSet.of("ignore"))) .build()); } } @Test public void argumentSelectionDefectChecker_rejectsSwap_withIgnoredFormalParameter() { CompilationTestHelper.newInstance( ArgumentSelectionDefectWithIgnoredFormalsHeuristic.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object ignore, Object second);", " void test(Object ignore, Object second) {", " target(second, ignore);", " }", "}") .doTest(); } @Test public void argumentSelectionDefectChecker_makesSwap_withNullArgument() { CompilationTestHelper.newInstance(ArgumentSelectionDefectChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object second) {", " target(second, null);", " }", "}") .doTest(); } @Test public void argumentSelectionDefectChecker_rejectsSwap_withArgumentWithoutName() { CompilationTestHelper.newInstance(ArgumentSelectionDefectChecker.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object second) {", " target(second, 1);", " }", "}") .doTest(); } /** * A {@link BugChecker} which runs the ArgumentSelectionDefectChecker checker using string * equality for edit distance and a penaltyThreshold of 0.9 */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Run the ArgumentSelectionDefectChecker checker with the penalty threshold heuristic") public static class ArgumentSelectionDefectWithPenaltyThreshold extends ArgumentSelectionDefectChecker { public ArgumentSelectionDefectWithPenaltyThreshold() { super( ArgumentChangeFinder.builder() .setDistanceFunction(buildEqualityFunction()) .addHeuristic(new PenaltyThresholdHeuristic(0.9)) .build()); } } @Test public void argumentSelectionDefectCheckerWithPenalty_findsSwap_withSwappedMatchingPair() { CompilationTestHelper.newInstance(ArgumentSelectionDefectWithPenaltyThreshold.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object first, Object second) {", " // BUG: Diagnostic contains: target(first, second)", " // target(/* first= */second, /* second= */first)", " target(second, first);", " }", "}") .doTest(); } @Test public void argumentSelectionDefectCheckerWithPenalty_makesNoChange_withAlmostMatchingSet() { CompilationTestHelper.newInstance(ArgumentSelectionDefectWithPenaltyThreshold.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second, Object third, Object fourth);", " void test(Object first, Object second, Object third, Object different) {", " target(different, third, second, first);", " }", "}") .doTest(); } /** * A {@link BugChecker} which runs the ArgumentSelectionDefectChecker checker using string * equality for edit distance and name in comments heuristic */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Run the ArgumentSelectionDefectChecker checker using string equality for edit distance") public static class ArgumentSelectionDefectWithNameInCommentsHeuristic extends ArgumentSelectionDefectChecker { public ArgumentSelectionDefectWithNameInCommentsHeuristic() { super( ArgumentChangeFinder.builder() .setDistanceFunction(buildEqualityFunction()) .addHeuristic(new NameInCommentHeuristic()) .build()); } } @Test public void argumentSelectionDefectCheckerWithPenalty_noSwap_withNamedPair() { CompilationTestHelper.newInstance( ArgumentSelectionDefectWithNameInCommentsHeuristic.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object first, Object second) {", " target(/* first= */second, /* second= */first);", " }", "}") .doTest(); } private static Function<ParameterPair, Double> buildEqualityFunction() { return new Function<ParameterPair, Double>() { @Override public Double apply(ParameterPair parameterPair) { return parameterPair.formal().name().equals(parameterPair.actual().name()) ? 0.0 : 1.0; } }; } /** A {@link BugChecker} which returns true if parameter names are available */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Returns true if parameter names are available on a method call") public static class ParameterNamesAvailableChecker extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return buildDescription(tree) .setMessage( String.valueOf( ASTHelpers.getSymbol(tree).getParameters().stream() .noneMatch(p -> p.getSimpleName().toString().matches("arg[0-9]")))) .build(); } } @Test public void parameterNamesAvailable_returnsTree_onMethodNotInCompilationUnit() { CompilationTestHelper.newInstance(ParameterNamesAvailableChecker.class, getClass()) .addSourceLines( "Test.java", String.format("import %s;", CompilationTestHelper.class.getName()), String.format("import %s;", BugChecker.class.getName()), "class Test {", " void test() {", " // BUG: Diagnostic contains: true", " CompilationTestHelper.newInstance((Class<BugChecker>)null, getClass());", " }", "}") .doTest(); } @Test public void description() { CompilationTestHelper.newInstance(ArgumentSelectionDefectWithStringEquality.class, getClass()) .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object first, Object second);", " void test(Object first, Object second) {", " // BUG: Diagnostic contains: The following arguments may have been swapped:" + " 'second' for formal parameter 'first', 'first' for formal parameter 'second'." + " Either add clarifying `/* paramName= */` comments, or swap the arguments if" + " that is what was intended", " target(second, first);", " }", "}") .doTest(); } }
13,319
37.608696
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsPositiveCasesCoveringOnlyOnFirst.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ public class UngroupedOverloadsPositiveCasesCoveringOnlyOnFirst { // BUG: Diagnostic contains: Constructors and methods with the same name should appear public void foo(int x) { System.out.println(x); } public void bar() { foo(); } public void baz() { bar(); } public void bar(int x) { foo(x); } private void quux() { norf(); } private void norf() { quux(); } public void quux(int x) { bar(x); } public void foo() { foo(42); } }
1,226
20.526316
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/AssertFalseNegativeCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author sebastian.h.monte@gmail.com (Sebastian Monte) */ public class AssertFalseNegativeCases { public void assertTrue() { assert true; } public void assertFalseFromCondition() { assert 0 == 1; } }
887
26.75
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UnnecessaryLongToIntConversionNegativeCases.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.primitives.Ints; /** Negative cases for {@link com.google.errorprone.bugpatterns.UnnecessaryLongToIntConversion}. */ public class UnnecessaryLongToIntConversionNegativeCases { static void acceptsLong(long value) {} static void acceptsInt(int value) {} static void acceptsMultipleParams(int intValue, long longValue) {} // Converting from a long or Long to an Integer type requires first converting to an int. This is // out of scope. public void longToIntegerForLongParam() { long x = 1; acceptsLong(Integer.valueOf((int) x)); } public void longObjectToIntegerForLongParam() { Long x = Long.valueOf(1); acceptsLong(Integer.valueOf(x.intValue())); } public void longParameterAndLongArgument() { long x = 1; acceptsLong(x); } public void longParameterAndIntArgument() { int i = 1; acceptsLong(i); } public void longParameterAndIntegerArgument() { Integer i = Integer.valueOf(1); acceptsLong(i); } public void castIntToLong() { int i = 1; acceptsLong((long) i); } public void castLongToIntForIntParameter() { long x = 1; acceptsInt((int) x); } public void longValueOfLongObject() { Long x = Long.valueOf(1); acceptsLong(x.longValue()); } public void longValueOfInteger() { Integer i = Integer.valueOf(1); acceptsLong(i.longValue()); } public void intValueOfInteger() { Integer i = Integer.valueOf(1); acceptsLong(i.intValue()); } public void intValueForIntParameter() { Long x = Long.valueOf(1); acceptsInt(x.intValue()); } public void checkedCastOnInt() { int i = 1; acceptsLong(Ints.checkedCast(i)); } public void checkedCastOnInteger() { Integer i = Integer.valueOf(1); acceptsLong(Ints.checkedCast(i)); } public void checkedCastForIntParameter() { long x = 1; acceptsInt(Ints.checkedCast(x)); } public void checkedCastMultipleArgs() { long x = 1; // The method expects an int for the first parameter and a long for the second paremeter. acceptsMultipleParams(Ints.checkedCast(x), x); } public void toIntExactOnInt() { int i = 1; acceptsLong(Math.toIntExact(i)); } public void toIntExactOnInteger() { Integer i = Integer.valueOf(1); acceptsLong(Math.toIntExact(i)); } public void toIntExactForIntParameter() { long x = 1; acceptsInt(Math.toIntExact(x)); } }
3,097
24.186992
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ComparisonOutOfRangePositiveCases.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.IOException; import java.io.Reader; import java.util.function.Supplier; /** * @author Bill Pugh (bill.pugh@gmail.com) */ class ComparisonOutOfRangePositiveCases { private static final int NOT_A_BYTE = 255; void byteEquality() { boolean result; byte b = 0; byte[] barr = {1, 2, 3}; // BUG: Diagnostic contains: b == -1 result = b == 255; // BUG: Diagnostic contains: b == 1 result = b == -255; // BUG: Diagnostic contains: b == -128 result = b == 128; // BUG: Diagnostic contains: b != -1 result = b != 255; // BUG: Diagnostic contains: barr[0] == -1 result = barr[0] == 255; // BUG: Diagnostic contains: result = barr[0] == 128; // BUG: Diagnostic contains: bytes result = barr[0] == -255; // BUG: Diagnostic contains: b == -1 result = b == NOT_A_BYTE; Byte boxed = 0; // BUG: Diagnostic contains: result = boxed == 255; Supplier<? extends Byte> bSupplier = null; // BUG: Diagnostic contains: result = bSupplier.get() == 255; } void charEquality() throws IOException { boolean result; char c = 'A'; Reader reader = null; // BUG: Diagnostic contains: false result = c == -1; // BUG: Diagnostic contains: true result = c != -1; char d; // BUG: Diagnostic contains: chars result = (d = (char) reader.read()) == -1; } void shorts(short s) { boolean result; // BUG: Diagnostic contains: false result = s == Short.MAX_VALUE + 1; // BUG: Diagnostic contains: false result = s == Short.MIN_VALUE - 1; // BUG: Diagnostic contains: true result = s != Short.MAX_VALUE + 1; // BUG: Diagnostic contains: true result = s != Short.MIN_VALUE - 1; // BUG: Diagnostic contains: false result = s > Short.MAX_VALUE; // BUG: Diagnostic contains: true result = s > Short.MIN_VALUE - 1; // BUG: Diagnostic contains: false result = s >= Short.MAX_VALUE + 1; // BUG: Diagnostic contains: true result = s >= Short.MIN_VALUE; // BUG: Diagnostic contains: false result = s < Short.MIN_VALUE; // BUG: Diagnostic contains: true result = s < Short.MAX_VALUE + 1; // BUG: Diagnostic contains: false result = s <= Short.MIN_VALUE - 1; // BUG: Diagnostic contains: true result = s <= Short.MAX_VALUE; } void shortsReversed(short s) { boolean result; // BUG: Diagnostic contains: false result = Short.MAX_VALUE < s; // BUG: Diagnostic contains: true result = Short.MIN_VALUE - 1 < s; // BUG: Diagnostic contains: false result = Short.MAX_VALUE + 1 <= s; // BUG: Diagnostic contains: true result = Short.MIN_VALUE <= s; // BUG: Diagnostic contains: false result = Short.MIN_VALUE > s; // BUG: Diagnostic contains: true result = Short.MAX_VALUE + 1 > s; // BUG: Diagnostic contains: false result = Short.MIN_VALUE - 1 >= s; // BUG: Diagnostic contains: true result = Short.MAX_VALUE >= s; } void ints(int i) { boolean result; // BUG: Diagnostic contains: false result = i == Integer.MAX_VALUE + 1L; } void longs(long l) { boolean result; // BUG: Diagnostic contains: false result = l == Long.MIN_VALUE * 2.0; } }
3,938
25.614865
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SuppressWarningsDeprecatedNegativeCases.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * Negative cases for {@link SuppressWarningsDeprecated}. * * @author sjnickerson@google.com (Simon Nickerson) */ public class SuppressWarningsDeprecatedNegativeCases { @SuppressWarnings({"deprecation"}) public static void negativeCase1() {} @SuppressWarnings("deprecation") public static void negativeCase2() {} public static void negativeCase3() { @SuppressWarnings({"deprecation"}) int a = 3; } public static void negativeCase4() { @SuppressWarnings("deprecation") int a = 3; } public static void negativeCase5() { @SuppressWarnings({"deprecation"}) class Foo {} Foo a = null; } public static void negativeCase6() { @SuppressWarnings("deprecation") class Bar {} Bar b = null; } }
1,421
25.830189
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FloatingPointAssertionWithinEpsilonNegativeCases.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; /** * Negative test cases for FloatingPointAssertionWithinEpsilon check. * * @author ghm@google.com (Graeme Morgan) */ final class FloatingPointAssertionWithinEpsilonNegativeCases { private static final float TOLERANCE = 1e-5f; private static final double TOLERANCE2 = 1e-10f; private static final float VALUE = 1; public void testFloat() { String test = Boolean.TRUE.toString(); assertThat(1.0f).isWithin(1e-5f).of(1.0f); assertThat(1f).isWithin(TOLERANCE).of(VALUE); assertThat(1f).isWithin(1).of(1); assertThat(1f).isNotWithin(0).of(2f); assertThat(1f).isNotWithin(.5f).of(2f); assertEquals(1f, 1f, TOLERANCE); } public void testDouble() { String test = Boolean.TRUE.toString(); assertThat(1.0).isWithin(1e-10).of(1.0); assertThat(1.0).isWithin(TOLERANCE2).of(1f); assertThat(1.0).isWithin(TOLERANCE2).of(1); assertEquals(1.0, 1.0, TOLERANCE); } public void testZeroCases() { assertThat(1.0).isWithin(0.0).of(1.0); assertThat(1f).isWithin(0f).of(1f); assertThat(1f).isWithin(0).of(1f); assertEquals(1f, 1f, 0f); } }
1,878
28.825397
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FloatingPointAssertionWithinEpsilonPositiveCases_expected.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; /** * Expected refactoring output for FloatingPointAssertionWithinEpsilon bugpattern. * * @author ghm@google.com (Graeme Morgan) */ final class FloatingPointAssertionWithinEpsilonPositiveCases { private static final float TOLERANCE = 1e-10f; private static final double TOLERANCE2 = 1e-20f; private static final float VALUE = 1; public void testFloat() { assertThat(1.0f).isEqualTo(1.0f); assertThat(1f).isEqualTo(VALUE); assertThat(1e10f).isEqualTo(1e10f); assertThat(1f).isNotEqualTo(2f); assertEquals(1f, 1f, 0); assertEquals("equal!", 1f, 1f, 0); } public void testDouble() { assertThat(1.0).isEqualTo(1.0); assertThat(1.0).isEqualTo(1.0); assertThat(1.0).isEqualTo(1d); assertThat(1e20).isEqualTo(1e20); assertThat(0.1).isNotEqualTo((double) 0.1f); assertEquals(1.0, 1.0, 0); assertEquals("equal!", 1.0, 1.0, 0); } }
1,659
30.923077
82
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ByteBufferBackingArrayPositiveCases.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.errorprone.bugpatterns.ByteBufferBackingArrayTest; import java.nio.ByteBuffer; /** Positive cases for {@link ByteBufferBackingArrayTest}. */ public class ByteBufferBackingArrayPositiveCases { public void array_notPrecededByOffsetNorValidInitializer_asLocalVariable_isFlagged() { ByteBuffer buff = null; // BUG: Diagnostic contains: ByteBuffer.array() buff.array(); } class A { ByteBuffer buff = null; void array_notPrecededByOffsetNorValidInitializer_asField_isFlagged() { // BUG: Diagnostic contains: ByteBuffer.array() buff.array(); } } class ArrayCalledInFieldNotPrecededByOffsetNorValidInitializerAsFieldIsFlagged { ByteBuffer buffer = null; // BUG: Diagnostic contains: ByteBuffer.array() byte[] array = buffer.array(); } void array_notPrecededByOffsetNorValidInitializer_asMethodParameter_isFlagged(ByteBuffer buffer) { // BUG: Diagnostic contains: ByteBuffer.array() buffer.array(); } void array_followedByWrap_isFlagged() { ByteBuffer buff = null; // BUG: Diagnostic contains: ByteBuffer.array() buff.array(); buff = ByteBuffer.wrap(new byte[] {1}); } void array_followedByAllocate_isFlagged() { ByteBuffer buff = null; // BUG: Diagnostic contains: ByteBuffer.array() buff.array(); buff = ByteBuffer.allocate(1); } void array_precededByAllocateDirect_isFlagged() { ByteBuffer buff = null; buff = ByteBuffer.allocateDirect(1); // BUG: Diagnostic contains: ByteBuffer.array() buff.array(); } void array_precededByAllocateOnAnotherBuffer_isFlagged() { ByteBuffer otherBuff = ByteBuffer.allocate(1); ByteBuffer buff = null; otherBuff.arrayOffset(); // BUG: Diagnostic contains: ByteBuffer.array() buff.array(); } void array_precededByNotAValidMethod_isFlagged() { ByteBuffer buff = null; buff.position(); // BUG: Diagnostic contains: ByteBuffer.array() buff.array(); } }
2,643
29.045455
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MissingFailNegativeCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.HashMap; import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.mockito.Mockito; /** Test cases for missing fail */ public class MissingFailNegativeCases extends TestCase { private static final Logger logger = new Logger(); private static final Logger log = new Logger(); private static final Logger thingThatLogs = new Logger(); private boolean foo = true; public void expectedException_withFail() { try { dummyMethod(); Assert.fail(); } catch (Exception expected) { } } @SuppressWarnings("deprecation") // Need to recognize a framework call but don't want a warning. public void expectedException_withFrameworkFail() { try { dummyMethod(); junit.framework.Assert.fail(); } catch (Exception expected) { } } public void expectedException_withStaticFail() { try { dummyMethod(); fail(); } catch (Exception expected) { } } public void expectedException_returnInTry() { try { dummyMethod(); return; } catch (Exception expected) { } } public void expectedException_returnInCatch() { try { dummyMethod(); } catch (Exception expected) { return; } } public void expectedException_returnAfterCatch() { try { dummyMethod(); } catch (Exception expected) { } return; } public void expectedException_throwInCatch() throws Exception { try { dummyMethod(); } catch (Exception expected) { throw new Exception(); } } public void expectedException_throwInTry() throws Exception { boolean foo = false; try { if (foo) { throw new Exception(); } dummyMethod(); } catch (Exception expected) { } } public void expectedException_throwSynonymInCatch() throws Exception { try { dummyMethod(); } catch (Exception expected) { Assert.assertFalse(true); } } public void assertInCatch_testCaseThrowSynonymInCatch() throws Exception { try { dummyMethod(); } catch (Exception e) { assertFalse(true); } } public void expectedException_throwSynonymInTry() throws Exception { boolean foo = false; try { if (foo) { Assert.assertFalse(true); } dummyMethod(); } catch (Exception expected) { } } public void expectedException_assertTrueFalse() throws Exception { try { dummyMethod(); } catch (Exception expected) { Assert.assertTrue(false); } } public void expectedException_assertTrueFalseWithMessage() throws Exception { try { dummyMethod(); } catch (Exception expected) { Assert.assertTrue("This should never happen", false); } } public void expectedException_testCaseAssertTrueFalseWithMessage() throws Exception { try { dummyMethod(); } catch (Exception expected) { assertTrue("This should never happen", false); } } public void assertInCatch_assertTrueFalseWithMessage() throws Exception { try { dummyMethod(); } catch (Exception e) { Assert.assertTrue("This should never happen", false); } } public void expectedException_assertBoxedTrueFalse() throws Exception { try { dummyMethod(); } catch (Exception expected) { Assert.assertTrue(Boolean.FALSE); } } public void expectedException_assertUnequal() throws Exception { try { dummyMethod(); } catch (Exception expected) { Assert.assertEquals(1, 2); } } public void expectedException_testCaseAssertUnequal() throws Exception { try { dummyMethod(); } catch (Exception expected) { assertEquals(1, 2); } } public void expectedException_assertFalse() throws Exception { try { dummyMethod(); } catch (Exception expected) { assert (false); } } @Before public void expectedException_beforeAnnotation() throws Exception { try { dummyMethod(); } catch (Exception expected) { } } @After public void expectedException_afterAnnotation() throws Exception { try { dummyMethod(); } catch (Exception expected) { } } // Don't match setUp methods. public void setUp() throws Exception { try { dummyMethod(); } catch (Exception expected) { } } // Don't match tearDown methods. public void tearDown() throws Exception { try { dummyMethod(); } catch (Exception expected) { } } // Don't match main methods. public static void main(String[] args) throws Exception { try { dummyMethod(); } catch (Exception expected) { } } // Don't match suite methods. public static Test suite() throws Exception { try { dummyMethod(); } catch (Exception expected) { } int x; // Don't return right after catch so as not to trigger that exclusion. return null; } public void expectedException_interruptedException() throws Exception { try { dummyMethod(); } catch (InterruptedException expected) { } } public void expectedException_assertionError() throws Exception { try { dummyMethod(); } catch (AssertionError expected) { } } public void expectedException_assertionFailedError() throws Exception { try { dummyMethod(); } catch (AssertionFailedError expected) { } } public void expectedException_throwable() throws Exception { try { dummyMethod(); } catch (Throwable expected) { } } public void testExpectedException_loopInTestMethod() throws Exception { for (int i = 0; i < 2; i++) { try { dummyMethod(); } catch (Exception expected) { } } } public void expectedException_loopInHelperMethod() throws Exception { for (int i = 0; i < 2; i++) { try { dummyMethod(); } catch (Exception expected) { } } } public static Map<String, String> assertInCatch_loopInHelperMethod(String... strings) { Map<String, String> map = new HashMap<>(); for (String s : strings) { try { map.put(s, s); } catch (Exception e) { Assert.assertTrue(s.contains("foo")); } } return map; } // prefixed with "test" but private - not a test method. private void testExpectedException_loopInPrivateTestHelperMethod() throws Exception { for (int i = 0; i < 2; i++) { try { dummyMethod(); } catch (Exception expected) { } } } // prefixed with "test" but returns - not a test method. public String testExpectedException_loopInReturningTestHelperMethod() throws Exception { for (int i = 0; i < 2; i++) { try { dummyMethod(); } catch (Exception expected) { } } return ""; } // Prefixed with "test" to not trigger loop in helper method exclusion. public void testExpectedException_continueInCatch() throws Exception { for (int i = 0; i < 2; i++) { try { dummyMethod(); } catch (Exception expected) { continue; } } } // Prefixed with "test" to not trigger loop in helper method exclusion. public void testExpectedException_continueInTry() throws Exception { for (int i = 0; i < 2; i++) { try { dummyMethod(); continue; } catch (Exception expected) { } } } public void expectedException_finally() { try { dummyMethod(); } catch (Exception expected) { } finally { } } public void expectedException_logInCatch() { try { dummyMethod(); } catch (Exception expected) { thingThatLogs.log(); } } public void expectedException_loggerCallInCatch() { try { dummyMethod(); } catch (Exception expected) { logger.info(); } } public void expectedException_logCallInCatch() { try { dummyMethod(); } catch (Exception expected) { log.info(); } } public void assertInCatch_assertLastCallInTry() { try { dummyMethod(); assertDummy(); } catch (Exception e) { assertDummy(); } } public void assertInCatch_fieldAssignmentInCatch() { try { dummyMethod(); } catch (Exception e) { assertDummy(); foo = true; } } public void assertInCatch_assertOnFieldInCatch() { try { dummyMethod(); } catch (Exception e) { Assert.assertTrue(foo); } } public void assertInCatch_assertOnVariableInCatch() { boolean bar = false; try { dummyMethod(); } catch (Exception e) { Assert.assertTrue(bar); } } public void assertInCatch_verifyBeforeCatch() { try { dummyMethod(); Mockito.verify(new Dummy()).dummy(); } catch (Exception e) { assertDummy(); } } public void assertInCatch_noopAssertInCatch() { try { dummyMethod(); } catch (Exception e) { assertTrue(true); } } public void expectedException_failInCatch() { try { dummyMethod(); } catch (Exception expected) { Assert.fail(); } } public void expectedException_whileTrue() { try { while (true) { dummyMethod(); } } catch (Exception expected) { } } public void expectedException_customFail() { try { dummyMethod(); specialFail(); } catch (Exception expected) { } } private static void dummyMethod() throws InterruptedException {} private static void assertDummy() {} private static void specialFail() {} private static class Logger { void log() {} ; void info() {} ; } private static class Dummy { String dummy() { return ""; } } }
10,536
20.997912
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EqualsIncompatibleTypeNegativeCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.util.List; import java.util.Set; /** * @author avenet@google.com (Arnaud J. Venet) */ public class EqualsIncompatibleTypeNegativeCases { class A { public boolean equals(Object o) { if (o instanceof A) { return true; } return false; } } class B1 extends A {} class B2 extends A {} class B3 extends B2 {} void checkEqualsAB1B2B3(A a, B1 b1, B2 b2, B3 b3) { a.equals(a); a.equals(b1); a.equals(b2); a.equals(b3); a.equals(null); b1.equals(a); b1.equals(b1); b1.equals(b2); b1.equals(b3); b1.equals(null); b2.equals(a); b2.equals(b1); b2.equals(b2); b2.equals(b3); b2.equals(null); b3.equals(a); b3.equals(b1); b3.equals(b2); b3.equals(b3); b3.equals(null); } void checks(Object o, boolean[] bools, boolean bool) { o.equals(bool); o.equals(bools[0]); } void checkJUnit(B1 b1, B2 b2) { org.junit.Assert.assertFalse(b1.equals(b2)); } void checkStaticEquals(A a, B1 b1, B2 b2, B3 b3) { java.util.Objects.equals(a, a); java.util.Objects.equals(a, b1); java.util.Objects.equals(a, b2); java.util.Objects.equals(a, b3); java.util.Objects.equals(a, null); java.util.Objects.equals(b1, b3); java.util.Objects.equals(b2, b3); java.util.Objects.equals(b3, b3); java.util.Objects.equals(null, b3); } void checkGuavaStaticEquals(A a, B1 b1, B2 b2, B3 b3) { com.google.common.base.Objects.equal(a, a); com.google.common.base.Objects.equal(a, b1); com.google.common.base.Objects.equal(a, b2); com.google.common.base.Objects.equal(a, b3); com.google.common.base.Objects.equal(a, null); com.google.common.base.Objects.equal(b1, b3); com.google.common.base.Objects.equal(b2, b3); com.google.common.base.Objects.equal(b3, b3); com.google.common.base.Objects.equal(null, b3); } class C {} abstract class C1 extends C { public abstract boolean equals(Object o); } abstract class C2 extends C1 {} abstract class C3 extends C1 {} void checkEqualsC1C2C3(C1 c1, C2 c2, C3 c3) { c1.equals(c1); c1.equals(c2); c1.equals(c3); c1.equals(null); c2.equals(c1); c2.equals(c2); c2.equals(c3); c2.equals(null); c3.equals(c1); c3.equals(c2); c3.equals(c3); c3.equals(null); } interface I { boolean equals(Object o); } class E1 implements I {} class E2 implements I {} class E3 extends E2 {} void checkEqualsIE1E2E3( I e, E1 e1, E2 e2, E3 e3, List<I> eList, List<E1> e1List, List<E2> e2List) { e.equals(e); e.equals(e1); e.equals(e2); e.equals(e3); e.equals(null); e1.equals(e); e1.equals(e1); e1.equals(e2); e1.equals(e3); e1.equals(null); e2.equals(e); e2.equals(e1); e2.equals(e2); e2.equals(e3); e2.equals(null); e3.equals(e); e3.equals(e1); e3.equals(e2); e3.equals(e3); e3.equals(null); eList.equals(e1List); eList.equals(e2List); eList.equals(null); e1List.equals(eList); e1List.equals(e2List); e1List.equals(null); e2List.equals(eList); e2List.equals(e1List); e2List.equals(null); } void collectionStuff( List rawList, List<String> stringList, Set<String> stringSet, ImmutableSet<String> immutableStringSet, ImmutableList<String> immutableStringList) { // With raw types, we can't be sure. So... /shrug rawList.equals(stringList); stringSet.equals(immutableStringSet); stringList.equals(immutableStringList); } interface J {} class F1 implements J {} abstract class F2 { public abstract boolean equals(J o); } void checkOtherEquals(F1 f1, F2 f2) { f2.equals(f1); } }
4,550
21.092233
82
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BadShiftAmountPositiveCases.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author Bill Pugh (bill.pugh@gmail.com) */ public class BadShiftAmountPositiveCases { public void foo() { int x = 0; long result = 0; // BUG: Diagnostic contains: (long) x >> 32 result += x >> 32; // BUG: Diagnostic contains: (long) x << 32 result += x << 32; // BUG: Diagnostic contains: (long) x >>> 32 result += x >>> 32; // BUG: Diagnostic contains: (long) x >> 40 result += x >> 40; // BUG: Diagnostic contains: (long) (x & 255) >> 40 result += (x & 255) >> 40; // BUG: Diagnostic contains: 1L << 48 result += 1 << 48; // BUG: Diagnostic contains: x >> 4 result += x >> 100; // BUG: Diagnostic contains: x >> 31 result += x >> -1; byte b = 0; char c = 'a'; // BUG: Diagnostic contains: (long) b >> 32 result += b >> 32; // BUG: Diagnostic contains: (long) b << 32 result += b << 32; // BUG: Diagnostic contains: (long) c >> 32 result += c >> 32; // BUG: Diagnostic contains: (long) c >>> 32 result += c >>> 32; } }
1,712
27.55
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/RxReturnValueIgnoredPositiveCases.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.errorprone.annotations.CanIgnoreReturnValue; import io.reactivex.Flowable; import io.reactivex.Maybe; import io.reactivex.Observable; import io.reactivex.Single; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @author friedj@google.com (Jake Fried) */ public class RxReturnValueIgnoredPositiveCases { private static Observable getObservable() { return null; } private static Single getSingle() { return null; } private static Flowable getFlowable() { return null; } private static Maybe getMaybe() { return null; } { new Observable(); new Single(); new Flowable(); new Maybe(); // BUG: Diagnostic contains: Rx objects must be checked. getObservable(); // BUG: Diagnostic contains: Rx objects must be checked. getSingle(); // BUG: Diagnostic contains: Rx objects must be checked. getFlowable(); // BUG: Diagnostic contains: Rx objects must be checked. getMaybe(); // BUG: Diagnostic contains: Rx objects must be checked. Arrays.asList(1, 2, 3).forEach(n -> getObservable()); // BUG: Diagnostic contains: Rx objects must be checked. Arrays.asList(1, 2, 3).forEach(n -> getSingle()); // BUG: Diagnostic contains: Rx objects must be checked. Arrays.asList(1, 2, 3).forEach(n -> getFlowable()); // BUG: Diagnostic contains: Rx objects must be checked. Arrays.asList(1, 2, 3).forEach(n -> getMaybe()); } private abstract static class IgnoringParent<T> { @CanIgnoreReturnValue abstract T ignoringFunction(); } private class NonIgnoringObservableChild extends IgnoringParent<Observable<Integer>> { @Override Observable<Integer> ignoringFunction() { return null; } } private class NonIgnoringSingleChild extends IgnoringParent<Single<Integer>> { @Override Single<Integer> ignoringFunction() { return null; } } private class NonIgnoringFlowableChild extends IgnoringParent<Flowable<Integer>> { @Override Flowable<Integer> ignoringFunction() { return null; } } private class NonIgnoringMaybeChild extends IgnoringParent<Maybe<Integer>> { @Override Maybe<Integer> ignoringFunction() { return null; } } public void inheritanceTest() { NonIgnoringObservableChild observableChild = new NonIgnoringObservableChild(); NonIgnoringSingleChild singleChild = new NonIgnoringSingleChild(); NonIgnoringFlowableChild flowableChild = new NonIgnoringFlowableChild(); NonIgnoringMaybeChild maybeChild = new NonIgnoringMaybeChild(); // BUG: Diagnostic contains: Rx objects must be checked. observableChild.ignoringFunction(); // BUG: Diagnostic contains: Rx objects must be checked. singleChild.ignoringFunction(); // BUG: Diagnostic contains: Rx objects must be checked. flowableChild.ignoringFunction(); // BUG: Diagnostic contains: Rx objects must be checked. maybeChild.ignoringFunction(); } public void conditional() { if (false) { // BUG: Diagnostic contains: Rx objects must be checked. getObservable(); // BUG: Diagnostic contains: Rx objects must be checked. getSingle(); // BUG: Diagnostic contains: Rx objects must be checked. getFlowable(); // BUG: Diagnostic contains: Rx objects must be checked. getMaybe(); } return; } static void getFromMap() { Map<Object, Observable> map1 = new HashMap<>(); Map<Object, Single> map2 = new HashMap<>(); Map<Object, Flowable> map3 = new HashMap<>(); Map<Object, Maybe> map4 = new HashMap<>(); // BUG: Diagnostic contains: Rx objects must be checked. map1.get(null); // BUG: Diagnostic contains: Rx objects must be checked. map2.get(null); // BUG: Diagnostic contains: Rx objects must be checked. map3.get(null); // BUG: Diagnostic contains: Rx objects must be checked. map4.get(null); } }
4,625
29.235294
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/RethrowReflectiveOperationExceptionAsLinkageErrorPositiveCases.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; public class RethrowReflectiveOperationExceptionAsLinkageErrorPositiveCases { void assertionErrorExceptionConstructor() { try { throw new ReflectiveOperationException(); } catch (ReflectiveOperationException e) { // BUG: Diagnostic contains: throw new LinkageError(e.getMessage(), e); throw new AssertionError(e); } } void assertionErrorStringConstructor() { try { throw new ReflectiveOperationException(); } catch (ReflectiveOperationException e) { // BUG: Diagnostic contains: throw new LinkageError("Test", e); throw new AssertionError("Test", e); } } void assertionErrorStringFormatConstructor() { try { throw new ReflectiveOperationException(); } catch (ReflectiveOperationException e) { // BUG: Diagnostic contains: throw new LinkageError(String.format("Test"), e); throw new AssertionError(String.format("Test"), e); } } void multiLineCatchBlock() { try { throw new ReflectiveOperationException(); } catch (ReflectiveOperationException e1) { int a = 100; if (a < 100) { try { throw new ReflectiveOperationException(); } catch (ReflectiveOperationException e2) { // BUG: Diagnostic contains: throw new LinkageError(e2.getMessage(), e2); throw new AssertionError(e2); } } // BUG: Diagnostic contains: throw new LinkageError(e1.getMessage(), e1); throw new AssertionError(e1); } } }
2,160
32.246154
84
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SwigMemoryLeakPositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author irogers@google.com (Ian Rogers) */ public class SwigMemoryLeakPositiveCases { private long swigCPtr; protected boolean swigCMemOwn; public SwigMemoryLeakPositiveCases(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; // BUG: Diagnostic contains: SWIG generated code that can't call a C++ destructor will leak // memory throw new UnsupportedOperationException("C++ destructor does not have public access"); } swigCPtr = 0; } } }
1,311
29.511628
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/RestrictedApiMethods.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.errorprone.annotations.RestrictedApi; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** Example for {@link com.google.errorprone.bugpatterns.RestrictedApiCheckerTest}. */ public class RestrictedApiMethods implements IFaceWithRestriction { public int normalMethod() { return 0; } @RestrictedApi( explanation = "lorem", allowlistAnnotations = {Allowlist.class}, allowlistWithWarningAnnotations = {AllowlistWithWarning.class}, link = "") public RestrictedApiMethods() {} @RestrictedApi( explanation = "lorem", allowlistAnnotations = {Allowlist.class}, allowlistWithWarningAnnotations = {AllowlistWithWarning.class}, link = "") public RestrictedApiMethods(int restricted) {} @RestrictedApi( explanation = "lorem", allowlistAnnotations = {Allowlist.class}, allowlistWithWarningAnnotations = {AllowlistWithWarning.class}, link = "", allowedOnPath = ".*testsuite/.*") public int restrictedMethod() { return 1; } @RestrictedApi( explanation = "lorem", allowlistAnnotations = {Allowlist.class}, allowlistWithWarningAnnotations = {AllowlistWithWarning.class}, link = "") public static int restrictedStaticMethod() { return 2; } @Override public void dontCallMe() {} public static class Subclass extends RestrictedApiMethods { @Allowlist public Subclass(int restricted) { super(restricted); } @Override public int restrictedMethod() { return 42; } } public static void accept(Runnable r) {} } interface IFaceWithRestriction { @RestrictedApi(explanation = "ipsum", link = "nothing") void dontCallMe(); } @Target({ElementType.METHOD, ElementType.CONSTRUCTOR}) @interface AllowlistWithWarning {}
2,493
27.340909
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EmptyIfStatementNegativeCases.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class EmptyIfStatementNegativeCases { // just a normal use of if public static void negativeCase1() { int i = 10; if (i == 10) { System.out.println("foo"); } i++; } // empty then part but nonempty else public static void negativeCase2() { int i = 0; if (i == 10) ; else System.out.println("not 10"); } // multipart if with non-empty else public static void negativeCase3() { int i = 0; if (i == 10) ; else if (i == 11) ; else if (i == 12) ; else System.out.println("not 10, 11, or 12"); } }
1,315
24.307692
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ClassCanBeStaticPositiveCase3.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author alexloh@google.com (Alex Loh) */ public class ClassCanBeStaticPositiveCase3 { static int outerVar; // Nested non-static inner class inside a static inner class static class NonStaticOuter { int nonStaticVar = outerVar; // BUG: Diagnostic contains: public static class Inner3 public class Inner3 {} } }
1,002
29.393939
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayEqualsPositiveCases.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.base.Objects; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class ArrayEqualsPositiveCases { public void intArray() { int[] a = {1, 2, 3}; int[] b = {1, 2, 3}; // BUG: Diagnostic contains: Arrays.equals(a, b) if (a.equals(b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } // BUG: Diagnostic contains: Arrays.equals(a, b) if (Objects.equal(a, b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } } public void objectArray() { Object[] a = new Object[3]; Object[] b = new Object[3]; // BUG: Diagnostic contains: Arrays.equals(a, b) if (a.equals(b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } // BUG: Diagnostic contains: Arrays.equals(a, b) if (Objects.equal(a, b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } } public void firstMethodCall() { String s = "hello"; char[] b = new char[3]; // BUG: Diagnostic contains: Arrays.equals(s.toCharArray(), b) if (s.toCharArray().equals(b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } } public void secondMethodCall() { char[] a = new char[3]; String s = "hello"; // BUG: Diagnostic contains: Arrays.equals(a, s.toCharArray()) if (a.equals(s.toCharArray())) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } } public void bothMethodCalls() { String s1 = "hello"; String s2 = "world"; // BUG: Diagnostic contains: Arrays.equals(s1.toCharArray(), s2.toCharArray()) if (s1.toCharArray().equals(s2.toCharArray())) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } } }
2,744
26.45
82
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ErroneousThreadPoolConstructorCheckerNegativeCases.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.Collection; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; /** * Negative test cases for {@link * com.google.errorprone.bugpatterns.ErroneousThreadPoolConstructorChecker} bug pattern. */ final class ErroneousThreadPoolConstructorCheckerNegativeCases { private static final int CORE_POOL_SIZE = 10; private static final int MAXIMUM_POOL_SIZE = 20; private static final long KEEP_ALIVE_TIME = 60; private void createThreadPoolWithUnboundedQueue() { new ThreadPoolExecutor( MAXIMUM_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new LinkedBlockingQueue<>()); } private void createThreadPoolWithUnboundedQueueAndEmptyPool() { new ThreadPoolExecutor(0, 1, KEEP_ALIVE_TIME, SECONDS, new LinkedBlockingQueue<>()); } private void createThreadPoolWithBoundedArrayBlockingQueue( int initialCapacity, boolean fair, Collection<Runnable> initialTasks) { new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new ArrayBlockingQueue<>(initialCapacity)); new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new ArrayBlockingQueue<>(initialCapacity, fair)); new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new ArrayBlockingQueue<>(initialCapacity, fair, initialTasks)); } private void createThreadPoolWithBoundedLinkedBlockingQueue(int capacity) { new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new LinkedBlockingQueue<>(capacity)); } private void createThreadPoolWithBoundedLinkedBlockingDeque(int capacity) { new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new LinkedBlockingDeque<>(capacity)); } private void createThreadPoolWithBoundedSynchronousQueue() { new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new SynchronousQueue<>()); } }
3,097
31.270833
95
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SizeGreaterThanOrEqualsZeroNegativeCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author glorioso@google.com (Nick Glorioso) */ public class SizeGreaterThanOrEqualsZeroNegativeCases { private List<Integer> intList = new ArrayList<>(); private Set<Integer> intSet = new HashSet<>(); private Collection<Integer> intCollection = intList; public boolean testEquality() { boolean foo; foo = intList.size() > 0; foo = intSet.size() >= 1; foo = intCollection.size() <= 0; foo = intCollection.size() == 0; foo = intCollection.size() < 0; if (new ArrayList<Integer>().size() > 0) {} CollectionContainer baz = new CollectionContainer(); if (baz.intList.size() >= 1) {} if (baz.getIntList().size() >= 1) {} // These are incorrect comparisons, but we've chosen to not attempt to find these issues foo = (((((new HasASizeMethod()))))).size() >= 0; foo = new HasASizeMethod().length >= 0; return foo; } private static int[] staticIntArray; private int[] intArray; private boolean[][] twoDarray; public boolean arrayLength() { int zero = 0; boolean foo = intArray.length > 0; foo = twoDarray.length >= 1; foo = staticIntArray.length >= -1; foo = twoDarray[0].length > 0; foo = (((((twoDarray))))).length > zero; return foo; } public void protoCount(TestProtoMessage msg) { int zero = 0; boolean foo; foo = msg.getMultiFieldCount() > 0; foo = 0 < msg.getMultiFieldCount(); foo = 0 > msg.getMultiFieldCount(); foo = msg.getMultiFieldCount() >= 1; foo = msg.getMultiFieldCount() >= -1; foo = msg.getMultiFieldCount() < 0; foo = (((((msg))))).getMultiFieldCount() > zero; foo = msg.getTestFieldNamedCount() >= 0; // Not a repeated field, just name ending in `count` } private static class CollectionContainer { List<Integer> intList; List<Integer> getIntList() { return intList; } } private static class HasASizeMethod { public int length = 0; public int size() { return length; } } }
2,865
27.66
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ThrowIfUncheckedKnownCheckedTestNegativeCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.base.Throwables.propagateIfPossible; import static com.google.common.base.Throwables.throwIfUnchecked; import java.io.IOException; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; /** * @author cpovirk@google.com (Chris Povirk) */ public class ThrowIfUncheckedKnownCheckedTestNegativeCases { void exception(Exception e) { throwIfUnchecked(e); } void throwable(Throwable e) { throwIfUnchecked(e); } void runtime(RuntimeException e) { // Better written as "throw e," but comes up too rarely to justify a compile error. throwIfUnchecked(e); } void error(Error e) { // Better written as "throw e," but comes up too rarely to justify a compile error. throwIfUnchecked(e); } void multiarg(IOException e) throws IOException { propagateIfPossible(e, IOException.class); } void union() { try { foo(); } catch (IOException | ExecutionException | CancellationException e) { throwIfUnchecked(e); } } <E extends RuntimeException> void genericUnchecked(E e) { throwIfUnchecked(e); } <E extends Exception> void genericMaybeUnchecked(E e) { throwIfUnchecked(e); } <E extends T, T extends Exception> void genericUpperBoundDifferentFromErasure(E e) { throwIfUnchecked(e); } void foo() throws IOException, ExecutionException {} /* * I don't care whether these are flagged or not, since it won't come up in practice. I just want * to make sure that we don't blow up when running against the tests of Throwables. */ void nullException() { throwIfUnchecked(null); // throws NPE propagateIfPossible(null); // no-op } }
2,373
28.308642
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/WaitNotInLoopPositiveCases.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class WaitNotInLoopPositiveCases { boolean flag = false; public void testIfInsteadOfLoop() { synchronized (this) { if (!flag) { try { // BUG: Diagnostic contains: wait() must always be called in a loop // Did you mean 'while (!flag) {'? wait(); } catch (InterruptedException e) { } } } } public void testWaitLong() throws InterruptedException { // BUG: Diagnostic contains: wait(long) must always be called in a loop wait(1000); } public void testWaitLongInt() throws Exception { // BUG: Diagnostic contains: wait(long,int) must always be called in a loop wait(1000, 1000); } public void testAwait(Condition cond) throws Exception { // BUG: Diagnostic contains: await() must always be called in a loop cond.await(); } public void testAwaitWithFix(Condition cond) throws Exception { synchronized (this) { if (!flag) { try { // BUG: Diagnostic contains: await() must always be called in a loop // Did you mean 'while (!flag) {'? cond.await(); } catch (InterruptedException e) { } } } } public void testAwaitLongTimeUnit(Condition cond) throws Exception { // BUG: Diagnostic contains: // await(long,java.util.concurrent.TimeUnit) must always be called in a loop cond.await(1, TimeUnit.SECONDS); } public void testAwaitNanos(Condition cond) throws Exception { // BUG: Diagnostic contains: awaitNanos(long) must always be called in a loop cond.awaitNanos(1000000); } public void testAwaitUninterruptibly(Condition cond) throws Exception { // BUG: Diagnostic contains: awaitUninterruptibly() must always be called in a loop cond.awaitUninterruptibly(); } public void testAwaitUntil(Condition cond) throws Exception { // BUG: Diagnostic contains: awaitUntil(java.util.Date) must always be called in a loop cond.awaitUntil(new Date()); } }
2,821
29.673913
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MultipleParallelOrSequentialCallsNegativeCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.List; /** Created by mariasam on 7/6/17. */ public class MultipleParallelOrSequentialCallsNegativeCases { public void basicCase(List<String> list) { list.stream().parallel(); } public void basicCaseSequential(List<String> list) { list.stream().sequential(); } public void basicCaseNotLast(List<String> list) { list.stream().parallel().findFirst(); } public void middleParallel(List<String> list) { list.stream().map(m -> m).parallel().filter(m -> m.isEmpty()); } public void otherMethod() { SomeObject someObject = new SomeObject(); someObject.parallel().parallel(); } public void otherMethodNotParallel(List<String> list) { list.stream().filter(m -> m.isEmpty()).findFirst(); } public void streamWithinAStreamImmediatelyAfter(List<String> list) { list.stream().map(m -> list.stream().parallel()).parallel(); } public void streamWithinAStreamImmediatelyAfterOtherParallelBothFirstAndWithin( List<String> list) { list.stream().parallel().map(m -> list.stream().parallel()); } public void streamWithinAStreamImmediatelyAfterOtherParallelBoth(List<String> list) { list.stream().sequential().map(m -> list.stream().parallel()).parallel(); } class SomeObject { public SomeObject parallel() { return null; } } }
1,995
28.791045
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TestNotRunPositiveCase1.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class JUnit4TestNotRunPositiveCase1 { // BUG: Diagnostic contains: @Test public void testThisIsATest() {} // BUG: Diagnostic contains: @Test public static void testThisIsAStaticTest() {} }
1,014
29.757576
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BanJNDIPositiveCases.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.IOException; import java.util.Hashtable; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnector; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.sql.rowset.spi.SyncFactory; import javax.sql.rowset.spi.SyncFactoryException; /** * {@link BanJNDITest} * * @author tshadwell@google.com (Thomas Shadwell) */ class BanJNDIPositiveCases { private static DirContext FakeDirContext = ((DirContext) new Object()); private void callsModifyAttributes() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.modifyAttributes(((Name) new Object()), 0, ((Attributes) new Object())); } private void callsGetAttributes() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.getAttributes(((Name) new Object())); } private void callsSearch() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.search(((Name) new Object()), ((Attributes) new Object())); } private void callsGetSchema() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.getSchema(((Name) new Object())); } private void callsGetSchemaClassDefinition() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.getSchemaClassDefinition(((Name) new Object())); } private static Context FakeContext = ((Context) new Object()); private void callsLookup() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeContext.lookup("hello"); } private void callsSubclassLookup() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.lookup("hello"); } private void callsBind() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeContext.bind(((Name) new Object()), new Object()); } private void subclassCallsBind() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.bind(((Name) new Object()), new Object()); } private void callsRebind() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeContext.rebind(((Name) new Object()), new Object()); } private void subclassCallsRebind() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.rebind(((Name) new Object()), new Object()); } private void callsCreateSubcontext() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeContext.createSubcontext((Name) new Object()); } private void subclassCallsCreateSubcontext() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.createSubcontext((Name) new Object()); } RMIConnector fakeRMIConnector = ((RMIConnector) new Object()); private void callsRMIConnect() throws IOException { // BUG: Diagnostic contains: BanJNDI fakeRMIConnector.connect(); } private void callsEnumerateBindings() throws SyncFactoryException { // BUG: Diagnostic contains: BanJNDI SyncFactory.getInstance("fear is the little-death"); } // unable to load javax.jdo for testing (must be some super optional pkg?) private void callsJMXConnectorFactoryConnect() throws IOException { // BUG: Diagnostic contains: BanJNDI JMXConnectorFactory.connect(((JMXServiceURL) new Object())); } private void callsDoLookup() throws NamingException { // BUG: Diagnostic contains: BanJNDI InitialContext.doLookup(((Name) new Object())); } private static boolean callToJMXConnectorFactoryConnect() throws java.net.MalformedURLException, java.io.IOException { JMXConnector connector = // BUG: Diagnostic contains: BanJNDI JMXConnectorFactory.connect( new JMXServiceURL("service:jmx:rmi:///jndi/rmi:// fake data 123 ")); connector.connect(); return false; } private Object subclassesJavaNamingcontext() throws NamingException { InitialContext c = new InitialContext(new Hashtable(0)); // BUG: Diagnostic contains: BanJNDI return c.lookup("hello"); } }
4,993
32.293333
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ObjectToStringNegativeCases.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import org.joda.time.Duration; /** * @author bhagwani@google.com (Sumit Bhagwani) */ public class ObjectToStringNegativeCases { public static final class FinalObjectClassWithoutToString {} public static class NonFinalObjectClassWithoutToString {} public static final class FinalObjectClassWithToString { @Override public String toString() { return "hakuna"; } } public static class NonFinalObjectClassWithToString { @Override public String toString() { return "matata"; } } public void log(Object o) { System.out.println(o.toString()); } void directToStringCalls() { NonFinalObjectClassWithoutToString nonFinalObjectClassWithoutToString = new NonFinalObjectClassWithoutToString(); System.out.println(nonFinalObjectClassWithoutToString.toString()); FinalObjectClassWithToString finalObjectClassWithToString = new FinalObjectClassWithToString(); System.out.println(finalObjectClassWithToString.toString()); NonFinalObjectClassWithToString nonFinalObjectClassWithToString = new NonFinalObjectClassWithToString(); System.out.println(nonFinalObjectClassWithToString.toString()); } void callsTologMethod() { FinalObjectClassWithoutToString finalObjectClassWithoutToString = new FinalObjectClassWithoutToString(); log(finalObjectClassWithoutToString); NonFinalObjectClassWithoutToString nonFinalObjectClassWithoutToString = new NonFinalObjectClassWithoutToString(); log(nonFinalObjectClassWithoutToString); FinalObjectClassWithToString finalObjectClassWithToString = new FinalObjectClassWithToString(); log(finalObjectClassWithToString); NonFinalObjectClassWithToString nonFinalObjectClassWithToString = new NonFinalObjectClassWithToString(); log(nonFinalObjectClassWithToString); } public void overridePresentInAbstractClassInHierarchy(Duration durationArg) { String unusedString = Duration.standardSeconds(86400).toString(); System.out.println("test joda string " + Duration.standardSeconds(86400)); unusedString = durationArg.toString(); System.out.println("test joda string " + durationArg); } }
2,854
31.443182
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ComparisonOutOfRangeNegativeCases.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.IOException; import java.io.Reader; /** * @author Bill Pugh (bill.pugh@gmail.com) */ class ComparisonOutOfRangeNegativeCases { void byteEquality() { boolean result; byte b = 0; byte[] barr = {1, 2, 3}; result = b == 1; result = b == -2; result = b == 127; result = b != 1; result = b == (byte) 255; result = b == 'a'; // char result = b == 1L; // long result = b == 1.123f; // float result = b == 1.123; // double result = barr[0] == 1; result = barr[0] == -2; result = barr[0] == -128; } void charEquality() throws IOException { boolean result; char c = 'A'; Reader reader = null; result = c == 0; result = c == 0xffff; result = c == 1L; // long result = c == 1.123f; // float result = c == 1.123; // double int d; result = (d = reader.read()) == -1; } void shorts(short s) { boolean result; result = s == Short.MAX_VALUE; result = s == Short.MIN_VALUE; result = s != Short.MAX_VALUE; result = s != Short.MIN_VALUE; result = s > Short.MAX_VALUE - 1; result = s > Short.MIN_VALUE; result = s >= Short.MAX_VALUE; result = s >= Short.MIN_VALUE + 1; result = s < Short.MIN_VALUE + 1; result = s < Short.MAX_VALUE; result = s <= Short.MIN_VALUE; result = s <= Short.MAX_VALUE - 1; } void shortsReversed(short s) { boolean result; result = Short.MAX_VALUE - 1 < s; result = Short.MIN_VALUE < s; result = Short.MAX_VALUE <= s; result = Short.MIN_VALUE + 1 <= s; result = Short.MIN_VALUE + 1 > s; result = Short.MAX_VALUE > s; result = Short.MIN_VALUE >= s; result = Short.MAX_VALUE - 1 >= s; } void ints(int i) { boolean result; result = i == (long) Integer.MAX_VALUE; } void longs(long l) { boolean result; result = l == (double) Long.MIN_VALUE; } String binaryTreeMixingByteWithNonNumeric(byte b) { return "value is: " + b; } }
2,666
21.411765
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FunctionalInterfaceMethodChangedNegativeCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.concurrent.Callable; public class FunctionalInterfaceMethodChangedNegativeCases { @FunctionalInterface interface SuperFI { void superSam(); } @FunctionalInterface interface OtherSuperFI { void otherSuperSam(); } @FunctionalInterface interface SubFI extends SuperFI { void subSam(); @Override default void superSam() { subSam(); } } @FunctionalInterface interface MultipleInheritanceSubFI extends SuperFI, OtherSuperFI { void subSam(); @Override default void superSam() { subSam(); } @Override default void otherSuperSam() { subSam(); } } @FunctionalInterface interface ValueReturningSuperFI { String superSam(); } @FunctionalInterface interface ValueReturningSubFI extends ValueReturningSuperFI { String subSam(); @Override default String superSam() { return subSam(); } } // Regression test for b/68075767 @FunctionalInterface public interface VoidCallable extends Callable<Void> { void voidCall() throws Exception; @Override default Void call() throws Exception { voidCall(); return null; } } }
1,857
20.858824
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MissingFailPositiveCases3.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import junit.framework.TestCase; /** Examples of an inner test case. */ public class MissingFailPositiveCases3 { /** Sample inner class. */ public static class Inner extends TestCase { public void expectedException_emptyCatch() { try { // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception expected) { } } public void catchAssert() { try { // BUG: Diagnostic contains: fail() dummyMethod(); } catch (Exception e) { assertDummy(); } } } private static void dummyMethod() {} private static void assertDummy() {} }
1,298
25.510204
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/CollectionToArraySafeParameterPositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * @author mariasam@google.com (Maria Sam) on 6/27/17. */ public class CollectionToArraySafeParameterPositiveCases<T> { private static void basicCase() { Collection<String> collection = new ArrayList<String>(); // BUG: Diagnostic contains: array parameter Integer[] intArray = collection.toArray(new Integer[collection.size()]); Integer[] arrayOfInts = new Integer[10]; // BUG: Diagnostic contains: array parameter Integer[] wrongArray = collection.toArray(arrayOfInts); Set<Integer> integerSet = new HashSet<Integer>(); // BUG: Diagnostic contains: array parameter Long[] longArray = integerSet.toArray(new Long[10]); Set<Long> longSet = new HashSet<Long>(); // BUG: Diagnostic contains: array parameter Integer[] integerArray = longSet.toArray(new Integer[10]); } void test(Foo<Integer> foo) { // BUG: Diagnostic contains: array parameter String[] things = foo.toArray(new String[] {}); } void test(FooBar<Integer> foo) { // BUG: Diagnostic contains: array parameter Integer[] things = foo.toArray(new Integer[] {}); } class FooBar<T> extends HashSet<String> {} class Foo<T> extends HashSet<T> {} }
1,961
31.7
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/StringBuilderInitWithCharPositiveCases.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author lowasser@google.com (Louis Wasserman) */ public class StringBuilderInitWithCharPositiveCases { { // BUG: Diagnostic contains: new StringBuilder("a") new StringBuilder('a'); // BUG: Diagnostic contains: new StringBuilder("\"") new StringBuilder('"'); char c = 'c'; // BUG: Diagnostic contains: new StringBuilder().append(c) new StringBuilder(c); } }
1,059
31.121212
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayEqualsPositiveCases2.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.Objects; /** * Tests that only run with Java 7 and above. * * @author eaftan@google.com (Eddie Aftandilian) */ public class ArrayEqualsPositiveCases2 { public void intArray() { int[] a = {1, 2, 3}; int[] b = {1, 2, 3}; // BUG: Diagnostic contains: Arrays.equals(a, b) if (Objects.equals(a, b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } } public void objectArray() { Object[] a = new Object[3]; Object[] b = new Object[3]; // BUG: Diagnostic contains: Arrays.equals(a, b) if (Objects.equals(a, b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } } }
1,425
26.423077
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/DeadExceptionTestingNegativeCases.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import junit.framework.TestCase; import org.junit.Test; /** * @author alexeagle@google.com (Alex Eagle) */ public class DeadExceptionTestingNegativeCases extends TestCase { public void testShouldAllowTestingOfExceptionConstructorSideEffects() { try { new IllegalArgumentException((Throwable) null); fail(); } catch (NullPointerException e) { // expected } } @Test public void shouldAllowTestingOfExceptionConstructorSideEffects() { try { new IllegalArgumentException((Throwable) null); fail(); } catch (NullPointerException e) { // expected } } }
1,284
26.934783
75
java