Fix error prone warns (#2320)

* Adds `@SuppressWarnings("NarrowingCompoundAssignment")`

* Adds `@SuppressWarnings("TypeParameterUnusedInFormals")`

* Adds `@SuppressWarnings("JavaUtilDate")`

* Adds a limit to `String.split()`

* Add `error_prone_annotations` to the `pom.xml`

* Adds `@InlineMe(...)` to deprecated methods

* Adds `@SuppressWarnings("ImmutableEnumChecker")`

* Adds `@SuppressWarnings("ModifiedButNotUsed")`

* Adds `@SuppressWarnings("MixedMutabilityReturnType")`

* Removes an unused import

* Adds `requires` to `module-info.java`

* Adds ErrorProne `link` into `pom.xml`

* Remove unused imports

Removed from:
- ParseBenchmark

* Adds `@SuppressWarnings("EqualsGetClass")`

* Excludes from `proto` just the generated code.

Replaces `.*proto.*` with `.*/generated-test-sources/protobuf/.*` in such way will be excluded just the generated code and not the whole `proto` directory

* Removes an unused variable

Removes the `descriptor` variable because is unused.

* Fixes the `BadImport` warn into `ProtosWithAnnotationsTest`

* Fixes the `BadImport` warns into `ProtosWithAnnotationsTest`

* Enables ErrorProne in `gson/src/test.*`

Removes the `gson/src/test.*` path from the `-XepExcludedPaths` parameter of the ErrorProne plugin

* Fixes `UnusedVariable` warns

This commit fix all `UnusedVariable` warns given by ErrorProne in the `gson/src/test.*` path.

Some field is annotated with `@Keep` that means is used by reflection.
In some other case the record is annotated with `@SuppressWarnings("unused")`

* Fixes `JavaUtilDate` warns

This commit fix all `JavaUtilDate` warns given by ErrorProne in the `gson/src/test.*` path.

Classes/Methods are annotated with `@SuppressWarnings("JavaUtilDate")` because it's not possible use differente Date API.

* Fixes `EqualsGetClass` warns

This commit fix all `EqualsGetClass` warns given by ErrorProne in the `gson/src/test.*` path.

I have rewrite the `equals()` methods to use `instanceof`

* Replaces pattern matching for instanceof with casts

* Fixes `JdkObsolete` warns

This commit fix all `JdkObsolete` warns given by ErrorProne in the `gson/src/test.*` path.

In some cases I have replaced the obsolete JDK classes with the newest alternatives.  In other cases, I have added the `@SuppressWarnings("JdkObsolete")`

* Fixes `ClassCanBeStatic` warns

This commit fix all `ClassCanBeStatic` warns given by ErrorProne in the `gson/src/test.*` path.

I have added the `static` keyword, or I have added `@SuppressWarnings("ClassCanBeStatic")`

* Fixes `UndefinedEquals` warns

This commit fix all `UndefinedEquals` warns given by ErrorProne in the `gson/src/test.*` path.

I have added `@SuppressWarnings("UndefinedEquals")` or fixed the asserts

Note: In this commit I have also renamed a test from `testRawCollectionDeserializationNotAlllowed` to `testRawCollectionDeserializationNotAllowed`

* Fixes `GetClassOnEnum` warns

This commit fix all `GetClassOnEnum` warns given by ErrorProne in the `gson/src/test.*` path.

I have replaced the `.getClass()` with `.getDeclaringClass()`

* Fixes `ImmutableEnumChecker` warns

This commit fix all `ImmutableEnumChecker` warns given by ErrorProne in the `gson/src/test.*` path.

I have added the `final` keyword, or I have added the `@SuppressWarnings("ImmutableEnumChecker")` annotation

* Fixes `StaticAssignmentOfThrowable` warns

This commit fix all `StaticAssignmentOfThrowable` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `AssertionFailureIgnored` warns

This commit fix all `AssertionFailureIgnored` warns given by ErrorProne in the `gson/src/test.*` path.

I have added the `@SuppressWarnings("AssertionFailureIgnored")` annotation

* Fixes `ModifiedButNotUsed` warns

This commit fix all `ModifiedButNotUsed` warns given by ErrorProne in the `gson/src/test.*` path.

I have added the `@SuppressWarnings("ModifiedButNotUsed")` annotation

* Fixes `MissingSummary` warns

This commit fix all `MissingSummary` warns given by ErrorProne in the `gson/src/test.*` path.

I have remove the Javadoc `@author`

* Fixes `FloatingPointLiteralPrecision` warns

This commit fix all `FloatingPointLiteralPrecision` warns given by ErrorProne in the `gson/src/test.*` path.

I have added the `@SuppressWarnings("FloatingPointLiteralPrecision")` annotation

* Fixes `StringSplitter` warns

This commit fix all `StringSplitter` warns given by ErrorProne in the `gson/src/test.*` path.

I have replaced the `String.split(...)` with `Splitter`

* Fixes `EmptyCatch` warns

This commit fix all `EmptyCatch` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `UnicodeEscape` warns

This commit fix all `UnicodeEscape` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `EmptyBlockTag` warns

This commit fix all `EmptyBlockTag` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `LongFloatConversion` warns

This commit fix all `LongFloatConversion` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `LongDoubleConversion` warns

This commit fix all `LongDoubleConversion` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `TruthAssertExpected` warns

This commit fix all `TruthAssertExpected` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `UnusedMethod` warns

This commit fix all `UnusedMethod` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `UnusedTypeParameter` warns

This commit fix all `UnusedTypeParameter` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `CatchFail` warns

This commit fix all `CatchFail` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `MathAbsoluteNegative` warns

This commit fix all `MathAbsoluteNegative` warns given by ErrorProne in the `gson/src/test.*` path.

* Fixes `LoopOverCharArray` warns

This commit fix all `LoopOverCharArray` warns given by ErrorProne in the `gson/src/test.*` path.

`toCharArray` allocates a new array, using `charAt` is more efficient

* Fixes `HidingField` warns

This commit fix all `HidingField` warns given by ErrorProne in the `gson/src/test.*` path.

* Implements code review feedback

* Implements code review feedback

This commit implements some other code review feedback

* Enable ErrorProne in `extra`

Thi commit removes the `.*extras/src/test.*` path from the `-XepExcludedPaths` parameter of ErrorProne.

* Fix the `JavaUtilDate` warns

This commit fix all `JavaUtilDate` warns given by ErrorProne in the `extras/src/test.*` path.

* Implements code review feedback

* Removes redundant new-line

* Implements code review feedback

* Adds `JDK11` to run test with `--release 11`

* Revert "Adds `JDK11` to run test with `--release 11`"

This reverts commit a7cca386098ae847a10a31c09c3ab9b11eee5920.
This commit is contained in:
Maicol 2023-03-01 23:23:27 +01:00 committed by GitHub
parent bfbbd0dde8
commit dc20b7561a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
60 changed files with 225 additions and 193 deletions

View File

@ -29,6 +29,7 @@ import java.util.Locale;
import java.util.TimeZone;
import org.junit.Test;
@SuppressWarnings("JavaUtilDate")
public final class UtcDateTypeAdapterTest {
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new UtcDateTypeAdapter())

View File

@ -55,6 +55,12 @@
<version>31.1-jre</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
<version>2.18.0</version>
<optional>true</optional>
</dependency>
</dependencies>
<build>

View File

@ -1011,7 +1011,7 @@ public final class Gson {
* @see #fromJson(String, Class)
* @see #fromJson(String, TypeToken)
*/
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
public <T> T fromJson(String json, Type typeOfT) throws JsonSyntaxException {
return (T) fromJson(json, TypeToken.get(typeOfT));
}
@ -1104,7 +1104,7 @@ public final class Gson {
* @see #fromJson(Reader, Class)
* @see #fromJson(Reader, TypeToken)
*/
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
public <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException {
return (T) fromJson(json, TypeToken.get(typeOfT));
}
@ -1183,7 +1183,7 @@ public final class Gson {
* @see #fromJson(Reader, Type)
* @see #fromJson(JsonReader, TypeToken)
*/
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException {
return (T) fromJson(reader, TypeToken.get(typeOfT));
}
@ -1297,7 +1297,7 @@ public final class Gson {
* @see #fromJson(JsonElement, Class)
* @see #fromJson(JsonElement, TypeToken)
*/
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
public <T> T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException {
return (T) fromJson(json, TypeToken.get(typeOfT));
}

View File

@ -40,5 +40,6 @@ public interface JsonDeserializationContext {
* @return An object of type typeOfT.
* @throws JsonParseException if the parse tree does not contain expected data.
*/
@SuppressWarnings("TypeParameterUnusedInFormals")
public <T> T deserialize(JsonElement json, Type typeOfT) throws JsonParseException;
}

View File

@ -15,6 +15,7 @@
*/
package com.google.gson;
import com.google.errorprone.annotations.InlineMe;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
@ -111,18 +112,21 @@ public final class JsonParser {
/** @deprecated Use {@link JsonParser#parseString} */
@Deprecated
@InlineMe(replacement = "JsonParser.parseString(json)", imports = "com.google.gson.JsonParser")
public JsonElement parse(String json) throws JsonSyntaxException {
return parseString(json);
}
/** @deprecated Use {@link JsonParser#parseReader(Reader)} */
@Deprecated
@InlineMe(replacement = "JsonParser.parseReader(json)", imports = "com.google.gson.JsonParser")
public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException {
return parseReader(json);
}
/** @deprecated Use {@link JsonParser#parseReader(JsonReader)} */
@Deprecated
@InlineMe(replacement = "JsonParser.parseReader(json)", imports = "com.google.gson.JsonParser")
public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException {
return parseReader(json);
}

View File

@ -45,7 +45,7 @@ public final class JavaVersion {
// Parses both legacy 1.8 style and newer 9.0.4 style
private static int parseDotted(String javaVersion) {
try {
String[] parts = javaVersion.split("[._]");
String[] parts = javaVersion.split("[._]", 3);
int firstVer = Integer.parseInt(parts[0]);
if (firstVer == 1 && parts.length > 1) {
return Integer.parseInt(parts[1]);

View File

@ -81,6 +81,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
}
/** first element holds the default name */
@SuppressWarnings("MixedMutabilityReturnType")
private List<String> getFieldNames(Field f) {
SerializedName annotation = f.getAnnotation(SerializedName.class);
if (annotation == null) {

View File

@ -174,8 +174,9 @@ public final class TreeTypeAdapter<T> extends SerializationDelegatingTypeAdapter
@Override public JsonElement serialize(Object src, Type typeOfSrc) {
return gson.toJsonTree(src, typeOfSrc);
}
@SuppressWarnings("unchecked")
@Override public <R> R deserialize(JsonElement json, Type typeOfT) throws JsonParseException {
@Override
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
public <R> R deserialize(JsonElement json, Type typeOfT) throws JsonParseException {
return gson.fromJson(json, typeOfT);
}
}

View File

@ -36,6 +36,7 @@ import java.util.Date;
* this class state. DateFormat isn't thread safe either, so this class has
* to synchronize its read and write methods.
*/
@SuppressWarnings("JavaUtilDate")
final class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> {
static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
@SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal

View File

@ -37,6 +37,7 @@ import java.util.Date;
* this class state. DateFormat isn't thread safe either, so this class has
* to synchronize its read and write methods.
*/
@SuppressWarnings("JavaUtilDate")
final class SqlTimeTypeAdapter extends TypeAdapter<Time> {
static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
@SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal

View File

@ -27,6 +27,7 @@ import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
@SuppressWarnings("JavaUtilDate")
class SqlTimestampTypeAdapter extends TypeAdapter<Timestamp> {
static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
@SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal

View File

@ -33,6 +33,7 @@ import com.google.gson.internal.bind.DefaultDateTypeAdapter.DateType;
* it is {@code false} all other constants will be {@code null} and
* there will be no support for {@code java.sql} types.
*/
@SuppressWarnings("JavaUtilDate")
public final class SqlTypesSupport {
/**
* {@code true} if {@code java.sql} types are supported,

View File

@ -1603,7 +1603,7 @@ public class JsonReader implements Closeable {
throw syntaxError("Unterminated escape sequence");
}
// Equivalent to Integer.parseInt(stringPool.get(buffer, pos, 4), 16);
char result = 0;
int result = 0;
for (int i = pos, end = i + 4; i < end; i++) {
char c = buffer[i];
result <<= 4;
@ -1618,7 +1618,7 @@ public class JsonReader implements Closeable {
}
}
pos += 4;
return result;
return (char) result;
case 't':
return '\t';

View File

@ -24,6 +24,9 @@ module com.google.gson {
exports com.google.gson.reflect;
exports com.google.gson.stream;
// Dependency on Error Prone Annotations
requires static com.google.errorprone.annotations;
// Optional dependency on java.sql
requires static java.sql;

View File

@ -23,6 +23,8 @@ import java.util.List;
import org.junit.Test;
/**
* Tests that by default Gson accepts several forms of comments.
*
* @author Jesse Wilson
*/
public final class CommentsTest {

View File

@ -56,6 +56,7 @@ public class InnerClassExclusionStrategyTest {
assertThat(excluder.excludeField(f, true)).isFalse();
}
@SuppressWarnings("ClassCanBeStatic")
class InnerClass {
}

View File

@ -26,6 +26,8 @@ import java.math.BigInteger;
import org.junit.Test;
/**
* Tests handling of JSON arrays.
*
* @author Jesse Wilson
*/
public final class JsonArrayTest {

View File

@ -22,6 +22,8 @@ import com.google.gson.common.MoreAsserts;
import org.junit.Test;
/**
* Tests handling of JSON nulls.
*
* @author Jesse Wilson
*/
public final class JsonNullTest {

View File

@ -111,7 +111,7 @@ public final class ObjectTypeAdapterTest {
assertThat(actualTimes).isEqualTo(times);
}
@SuppressWarnings("unused")
@SuppressWarnings({"unused", "ClassCanBeStatic"})
private class RuntimeType {
Object a = 5;
Object b = Arrays.asList(1, 2, null);

View File

@ -25,6 +25,8 @@ import java.util.Locale;
import org.junit.Test;
/**
* Tests handling of Core Type Adapters
*
* @author Jesse Wilson
*/
public class OverrideCoreTypeAdaptersTest {

View File

@ -16,6 +16,7 @@
package com.google.gson;
import com.google.common.base.Objects;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.internal.Primitives;
@ -35,7 +36,7 @@ import java.lang.reflect.Type;
*/
public class ParameterizedTypeFixtures {
public static class MyParameterizedType<T> {
public static final class MyParameterizedType<T> {
public final T value;
public MyParameterizedType(T value) {
this.value = value;
@ -80,27 +81,16 @@ public class ParameterizedTypeFixtures {
return value == null ? 0 : value.hashCode();
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
if (!(obj instanceof MyParameterizedType<?>)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MyParameterizedType<T> other = (MyParameterizedType<T>) obj;
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
MyParameterizedType<?> that = (MyParameterizedType<?>) obj;
return Objects.equal(getValue(), that.getValue());
}
}
@ -112,8 +102,6 @@ public class ParameterizedTypeFixtures {
* This means that the fields of the same objects will be overwritten by Gson.
* This is usually fine in tests since there we deserialize just once, but quite
* dangerous in practice.
*
* @param instanceOfT
*/
public MyParameterizedTypeInstanceCreator(T instanceOfT) {
this.instanceOfT = instanceOfT;

View File

@ -18,6 +18,7 @@ package com.google.gson;
import static com.google.common.truth.Truth.assertThat;
import com.google.errorprone.annotations.Keep;
import com.google.gson.annotations.Since;
import com.google.gson.annotations.Until;
import com.google.gson.internal.Excluder;
@ -75,6 +76,7 @@ public class VersionExclusionStrategyTest {
private static class MockClassSince {
@Since(VERSION)
@Keep
public final int someField = 0;
}
@ -82,6 +84,7 @@ public class VersionExclusionStrategyTest {
private static class MockClassUntil {
@Until(VERSION)
@Keep
public final int someField = 0;
}
@ -91,6 +94,7 @@ public class VersionExclusionStrategyTest {
@Since(VERSION)
@Until(VERSION + 2)
@Keep
public final int someField = 0;
}
}

View File

@ -16,6 +16,7 @@
package com.google.gson.common;
import com.google.common.base.Objects;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
@ -146,26 +147,18 @@ public class TestTypes {
}
@Override
public boolean equals(Object obj) {
if (this == obj)
public boolean equals(Object o) {
if (this == o) {
return true;
if (obj == null)
}
if (!(o instanceof BagOfPrimitives)) {
return false;
if (getClass() != obj.getClass())
return false;
BagOfPrimitives other = (BagOfPrimitives) obj;
if (booleanValue != other.booleanValue)
return false;
if (intValue != other.intValue)
return false;
if (longValue != other.longValue)
return false;
if (stringValue == null) {
if (other.stringValue != null)
return false;
} else if (!stringValue.equals(other.stringValue))
return false;
return true;
}
BagOfPrimitives that = (BagOfPrimitives) o;
return longValue == that.longValue
&& getIntValue() == that.getIntValue()
&& booleanValue == that.booleanValue
&& Objects.equal(stringValue, that.stringValue);
}
@Override
@ -233,7 +226,7 @@ public class TestTypes {
// Nothing here..
@Override
public boolean equals(Object other) {
return other.getClass() == ClassWithNoFields.class;
return other instanceof ClassWithNoFields;
}
}

View File

@ -93,6 +93,7 @@ public class CollectionTest {
}
@Test
@SuppressWarnings("JdkObsolete")
public void testLinkedListSerialization() {
List<String> list = new LinkedList<>();
list.add("a1");
@ -113,6 +114,7 @@ public class CollectionTest {
}
@Test
@SuppressWarnings("JdkObsolete")
public void testQueueSerialization() {
Queue<String> queue = new LinkedList<>();
queue.add("a1");
@ -266,11 +268,11 @@ public class CollectionTest {
}
@Test
public void testRawCollectionDeserializationNotAlllowed() {
public void testRawCollectionDeserializationNotAllowed() {
String json = "[0,1,2,3,4,5,6,7,8,9]";
Collection<?> integers = gson.fromJson(json, Collection.class);
// JsonReader converts numbers to double by default so we need a floating point comparison
assertThat(integers).isEqualTo(Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0));
assertThat(integers).containsExactly(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0).inOrder();
json = "[\"Hello\", \"World\"]";
Collection<?> strings = gson.fromJson(json, Collection.class);
@ -416,9 +418,9 @@ public class CollectionTest {
}
}
private class BigClass { private Map<String, ? extends List<SmallClass>> inBig; }
private static class BigClass { private Map<String, ? extends List<SmallClass>> inBig; }
private class SmallClass { private String inSmall; }
private static class SmallClass { private String inSmall; }
@Test
public void testIssue1107() {

View File

@ -130,6 +130,7 @@ public class CustomDeserializerTest {
static final String TYPE_ACCESS = "__type__";
}
@SuppressWarnings("ImmutableEnumChecker")
private enum SubTypes {
SUB_TYPE1(SubType1.class),
SUB_TYPE2(SubType2.class);

View File

@ -17,6 +17,7 @@ package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Splitter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
@ -35,6 +36,7 @@ import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
@ -291,9 +293,9 @@ public class CustomTypeAdaptersTest {
String part2;
public StringHolder(String string) {
String[] parts = string.split(":");
part1 = parts[0];
part2 = parts[1];
List<String> parts = Splitter.on(':').splitToList(string);
part1 = parts.get(0);
part2 = parts.get(1);
}
public StringHolder(String part1, String part2) {
this.part1 = part1;
@ -425,6 +427,7 @@ public class CustomTypeAdaptersTest {
// Test created from Issue 352
@Test
@SuppressWarnings({"JavaUtilDate", "UndefinedEquals"})
public void testRegisterHierarchyAdapterForDate() {
Gson gson = new GsonBuilder()
.registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter())
@ -473,6 +476,7 @@ public class CustomTypeAdaptersTest {
}
}
@SuppressWarnings("JavaUtilDate")
private static class DateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {

View File

@ -68,6 +68,7 @@ import org.junit.Test;
* @author Inderjeet Singh
* @author Joel Leitch
*/
@SuppressWarnings("JavaUtilDate")
public class DefaultTypeAdaptersTest {
private Gson gson;
private TimeZone oldTimeZone;
@ -700,6 +701,7 @@ public class DefaultTypeAdaptersTest {
}
@Test
@SuppressWarnings("JdkObsolete")
public void testStringBufferSerialization() {
StringBuffer sb = new StringBuffer("abc");
String json = gson.toJson(sb);

View File

@ -56,7 +56,7 @@ public class DelegateTypeAdapterTest {
bags.add(new BagOfPrimitives(i, i, i % 2 == 0, String.valueOf(i)));
}
String json = gson.toJson(bags);
bags = gson.fromJson(json, new TypeToken<List<BagOfPrimitives>>(){}.getType());
gson.fromJson(json, new TypeToken<List<BagOfPrimitives>>(){}.getType());
// 11: 1 list object, and 10 entries. stats invoked on all 5 fields
assertThat(stats.numReads).isEqualTo(51);
assertThat(stats.numWrites).isEqualTo(51);
@ -66,7 +66,7 @@ public class DelegateTypeAdapterTest {
public void testDelegateInvokedOnStrings() {
String[] bags = {"1", "2", "3", "4"};
String json = gson.toJson(bags);
bags = gson.fromJson(json, String[].class);
gson.fromJson(json, String[].class);
// 1 array object with 4 elements.
assertThat(stats.numReads).isEqualTo(5);
assertThat(stats.numWrites).isEqualTo(5);

View File

@ -120,8 +120,9 @@ public class EnumTest {
* Test for issue 226.
*/
@Test
@SuppressWarnings("GetClassOnEnum")
public void testEnumSubclass() {
assertThat(Roshambo.ROCK.getClass()).isAssignableTo(Roshambo.class);
assertThat(Roshambo.ROCK.getClass()).isNotEqualTo(Roshambo.class);
assertThat(gson.toJson(Roshambo.ROCK)).isEqualTo("\"ROCK\"");
assertThat(gson.toJson(EnumSet.allOf(Roshambo.class))).isEqualTo("[\"ROCK\",\"PAPER\",\"SCISSORS\"]");
assertThat(gson.fromJson("\"ROCK\"", Roshambo.class)).isEqualTo(Roshambo.ROCK);
@ -131,11 +132,12 @@ public class EnumTest {
}
@Test
@SuppressWarnings("GetClassOnEnum")
public void testEnumSubclassWithRegisteredTypeAdapter() {
gson = new GsonBuilder()
.registerTypeHierarchyAdapter(Roshambo.class, new MyEnumTypeAdapter())
.create();
assertThat(Roshambo.ROCK.getClass()).isAssignableTo(Roshambo.class);
assertThat(Roshambo.ROCK.getClass()).isNotEqualTo(Roshambo.class);
assertThat(gson.toJson(Roshambo.ROCK)).isEqualTo("\"123ROCK\"");
assertThat(gson.toJson(EnumSet.allOf(Roshambo.class))).isEqualTo("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]");
assertThat(gson.fromJson("\"123ROCK\"", Roshambo.class)).isEqualTo(Roshambo.ROCK);
@ -207,6 +209,7 @@ public class EnumTest {
}
};
@SuppressWarnings("unused")
abstract Roshambo defeats();
}
@ -239,8 +242,8 @@ public class EnumTest {
private enum Color {
RED("red", 1), BLUE("blue", 2), GREEN("green", 3);
String value;
int index;
final String value;
final int index;
private Color(String value, int index) {
this.value = value;
this.index = index;

View File

@ -70,7 +70,7 @@ public class EscapingTest {
assertThat(jsonRepresentation).contains("\\\"");
BagOfPrimitives expectedObject = gson.fromJson(jsonRepresentation, BagOfPrimitives.class);
assertThat(expectedObject.getExpectedJson()).isEqualTo(objWithPrimitives.getExpectedJson());
assertThat(objWithPrimitives.getExpectedJson()).isEqualTo(expectedObject.getExpectedJson());
}
@Test

View File

@ -18,6 +18,7 @@ package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import com.google.errorprone.annotations.Keep;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
@ -121,9 +122,14 @@ public class ExposeFieldsTest {
private static class ClassWithExposedFields {
@Expose private final Integer a;
private final Integer b;
@Expose(serialize = false) final long c;
@Expose(deserialize = false) final double d;
@Expose(serialize = false, deserialize = false) final char e;
@Expose(serialize = false)
@Keep
final long c;
@Expose(deserialize = false)
final double d;
@Expose(serialize = false, deserialize = false)
@Keep
final char e;
public ClassWithExposedFields(Integer a, Integer b) {
this(a, b, 1L, 2.0, 'a');

View File

@ -75,6 +75,8 @@ public class FieldExclusionTest {
}
private static class Outer {
@SuppressWarnings("ClassCanBeStatic")
private class Inner extends NestedClass {
public Inner(String value) {
super(value);

View File

@ -16,14 +16,13 @@
package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertThrows;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.regex.Pattern;
import org.junit.Before;
import org.junit.Test;
@ -46,7 +45,7 @@ public class GsonVersionDiagnosticsTest {
@Override public void write(JsonWriter out, TestType value) {
throw new AssertionError("Expected during serialization");
}
@Override public TestType read(JsonReader in) throws IOException {
@Override public TestType read(JsonReader in) {
throw new AssertionError("Expected during deserialization");
}
}).create();
@ -60,22 +59,16 @@ public class GsonVersionDiagnosticsTest {
@Test
public void testAssertionErrorInSerializationPrintsVersion() {
try {
gson.toJson(new TestType());
fail();
} catch (AssertionError expected) {
ensureAssertionErrorPrintsGsonVersion(expected);
}
AssertionError e = assertThrows(AssertionError.class, () -> gson.toJson(new TestType()));
ensureAssertionErrorPrintsGsonVersion(e);
}
@Test
public void testAssertionErrorInDeserializationPrintsVersion() {
try {
gson.fromJson("{'a':'abc'}", TestType.class);
fail();
} catch (AssertionError expected) {
ensureAssertionErrorPrintsGsonVersion(expected);
}
AssertionError e = assertThrows(AssertionError.class,
() -> gson.fromJson("{'a':'abc'}", TestType.class));
ensureAssertionErrorPrintsGsonVersion(e);
}
private void ensureAssertionErrorPrintsGsonVersion(AssertionError expected) {

View File

@ -162,6 +162,7 @@ public class InheritanceTest {
}
@Test
@SuppressWarnings("JdkObsolete")
public void testSubInterfacesOfCollectionSerialization() {
List<Integer> list = new LinkedList<>();
list.add(0);

View File

@ -72,6 +72,7 @@ public final class Java17RecordTest {
.isEqualTo("v3");
}
@SuppressWarnings("unused")
private record RecordWithCustomNames(
@SerializedName("name") String a,
@SerializedName(value = "name1", alternate = {"name2", "name3"}) String b) {}
@ -135,6 +136,7 @@ public final class Java17RecordTest {
/** Tests behavior when the canonical constructor throws an exception */
@Test
@SuppressWarnings("StaticAssignmentOfThrowable")
public void testThrowingConstructor() {
record LocalRecord(String s) {
static final RuntimeException thrownException = new RuntimeException("Custom exception");
@ -171,6 +173,7 @@ public final class Java17RecordTest {
/** Tests behavior when a record accessor method throws an exception */
@Test
@SuppressWarnings("StaticAssignmentOfThrowable")
public void testThrowingAccessor() {
record LocalRecord(String s) {
static final RuntimeException thrownException = new RuntimeException("Custom exception");
@ -253,6 +256,7 @@ public final class Java17RecordTest {
.isEqualTo("null is not allowed as value for record component 'aByte' of primitive type; at path $.aByte");
}
@SuppressWarnings("unused")
private record RecordWithPrimitives(
String aString, byte aByte, short aShort, int anInt, long aLong, float aFloat, double aDouble, char aChar, boolean aBoolean) {}
@ -406,7 +410,9 @@ public final class Java17RecordTest {
assertThat(gson.fromJson("{\"i\":2}", PublicRecord.class)).isEqualTo(new PublicRecord(2));
}
@SuppressWarnings("unused")
private record PrivateRecord(int i) {}
@SuppressWarnings("unused")
public record PublicRecord(int i) {}
/**

View File

@ -19,6 +19,7 @@ package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.base.Splitter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
@ -36,6 +37,7 @@ import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
@ -226,9 +228,9 @@ public final class JsonAdapterAnnotationOnClassesTest {
// implement read: split name into firstName and lastName
in.beginObject();
in.nextName();
String[] nameParts = in.nextString().split(" ");
List<String> nameParts = Splitter.on(" ").splitToList(in.nextString());
in.endObject();
return new User(nameParts[0], nameParts[1]);
return new User(nameParts.get(0), nameParts.get(1));
}
}

View File

@ -18,6 +18,7 @@ package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import com.google.errorprone.annotations.Keep;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
@ -47,9 +48,15 @@ public final class JsonAdapterSerializerDeserializerTest {
}
private static final class Computer {
@JsonAdapter(UserSerializer.class) final User user1;
@JsonAdapter(UserDeserializer.class) final User user2;
@JsonAdapter(UserSerializerDeserializer.class) final User user3;
@JsonAdapter(UserSerializer.class)
@Keep
final User user1;
@JsonAdapter(UserDeserializer.class)
@Keep
final User user2;
@JsonAdapter(UserSerializerDeserializer.class)
@Keep
final User user3;
Computer(User user1, User user2, User user3) {
this.user1 = user1;
this.user2 = user2;
@ -137,8 +144,12 @@ public final class JsonAdapterSerializerDeserializerTest {
}
private static final class Container {
@JsonAdapter(BaseStringAdapter.class) Base<String> a;
@JsonAdapter(BaseIntegerAdapter.class) Base<Integer> b;
@JsonAdapter(BaseStringAdapter.class)
@Keep
Base<String> a;
@JsonAdapter(BaseIntegerAdapter.class)
@Keep
Base<Integer> b;
Container(String a, int b) {
this.a = new Base<>(a);
this.b = new Base<>(b);

View File

@ -161,7 +161,7 @@ public class ObjectTest {
private static class Subclass extends Superclass1 {
}
private static class Superclass1 extends Superclass2 {
@SuppressWarnings("unused")
@SuppressWarnings({"unused", "HidingField"})
String s;
}
private static class Superclass2 {
@ -414,6 +414,8 @@ public class ObjectTest {
private static class Parent {
@SuppressWarnings("unused")
int value1 = 1;
@SuppressWarnings("ClassCanBeStatic")
private class Child {
int value2 = 2;
}
@ -562,6 +564,7 @@ public class ObjectTest {
// http://code.google.com/p/google-gson/issues/detail?id=270
@Test
@SuppressWarnings("JavaUtilDate")
public void testDateAsMapObjectField() {
HasObjectMap a = new HasObjectMap();
a.map.put("date", new Date(0));
@ -654,6 +657,7 @@ public class ObjectTest {
}
}
@SuppressWarnings("StaticAssignmentOfThrowable")
static class ClassWithThrowingConstructor {
static final RuntimeException thrownException = new RuntimeException("Custom exception");

View File

@ -18,6 +18,7 @@ package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Objects;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
@ -399,7 +400,7 @@ public class ParameterizedTypesTest {
}
}
private static class MultiParameters<A, B, C, D, E> {
private static final class MultiParameters<A, B, C, D, E> {
A a;
B b;
C c;
@ -429,54 +430,19 @@ public class ParameterizedTypesTest {
return result;
}
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object obj) {
if (this == obj) {
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (obj == null) {
if (!(o instanceof MultiParameters<?, ?, ?, ?, ?>)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MultiParameters<A, B, C, D, E> other = (MultiParameters<A, B, C, D, E>) obj;
if (a == null) {
if (other.a != null) {
return false;
}
} else if (!a.equals(other.a)) {
return false;
}
if (b == null) {
if (other.b != null) {
return false;
}
} else if (!b.equals(other.b)) {
return false;
}
if (c == null) {
if (other.c != null) {
return false;
}
} else if (!c.equals(other.c)) {
return false;
}
if (d == null) {
if (other.d != null) {
return false;
}
} else if (!d.equals(other.d)) {
return false;
}
if (e == null) {
if (other.e != null) {
return false;
}
} else if (!e.equals(other.e)) {
return false;
}
return true;
MultiParameters<?, ?, ?, ?, ?> that = (MultiParameters<?, ?, ?, ?, ?>) o;
return Objects.equal(a, that.a)
&& Objects.equal(b, that.b)
&& Objects.equal(c, that.c)
&& Objects.equal(d, that.d)
&& Objects.equal(e, that.e);
}
}

View File

@ -23,6 +23,7 @@ import com.google.gson.common.TestTypes.ArrayOfObjects;
import com.google.gson.common.TestTypes.BagOfPrimitives;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
@ -51,7 +52,7 @@ public class PrettyPrintingTest {
@Test
public void testPrettyPrintList() {
BagOfPrimitives b = new BagOfPrimitives();
List<BagOfPrimitives> listOfB = new LinkedList<>();
List<BagOfPrimitives> listOfB = new ArrayList<>();
for (int i = 0; i < 15; ++i) {
listOfB.add(b);
}

View File

@ -192,7 +192,7 @@ public class PrimitiveTest {
// Should perform widening conversion
assertThat(gson.toJson((byte) 1, Float.class)).isEqualTo("1.0");
// (This widening conversion is actually lossy)
assertThat(gson.toJson(Long.MAX_VALUE - 10L, Float.class)).isEqualTo(Float.toString(Long.MAX_VALUE - 10L));
assertThat(gson.toJson(Long.MAX_VALUE - 10L, Float.class)).isEqualTo(Float.toString((float) (Long.MAX_VALUE - 10L)));
// Should perform narrowing conversion
gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
assertThat(gson.toJson(Double.MAX_VALUE, Float.class)).isEqualTo("Infinity");
@ -207,7 +207,7 @@ public class PrimitiveTest {
// Should perform widening conversion
assertThat(gson.toJson((byte) 1, Double.class)).isEqualTo("1.0");
// (This widening conversion is actually lossy)
assertThat(gson.toJson(Long.MAX_VALUE - 10L, Double.class)).isEqualTo(Double.toString(Long.MAX_VALUE - 10L));
assertThat(gson.toJson(Long.MAX_VALUE - 10L, Double.class)).isEqualTo(Double.toString((double) (Long.MAX_VALUE - 10L)));
}
@Test

View File

@ -78,6 +78,7 @@ public class PrintFormattingTest {
assertThat(json).contains("field2");
}
@SuppressWarnings("LoopOverCharArray")
private static void assertContainsNoWhiteSpace(String str) {
for (char c : str.toCharArray()) {
assertThat(Character.isWhitespace(c)).isFalse();

View File

@ -130,7 +130,7 @@ public class ReflectionAccessTest {
gson.fromJson("[]", internalClass);
fail("Missing exception; test has to be run with `--illegal-access=deny`");
} catch (JsonSyntaxException e) {
fail("Unexpected exception; test has to be run with `--illegal-access=deny`");
throw new AssertionError("Unexpected exception; test has to be run with `--illegal-access=deny`", e);
} catch (JsonIOException expected) {
assertThat(expected).hasMessageThat().startsWith("Failed making constructor 'java.util.Collections$EmptyList()' accessible;"
+ " either increase its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: ");

View File

@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.base.Splitter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
@ -172,8 +173,8 @@ public final class StreamingTypeAdaptersTest {
public void testNullSafe() {
TypeAdapter<Person> typeAdapter = new TypeAdapter<Person>() {
@Override public Person read(JsonReader in) throws IOException {
String[] values = in.nextString().split(",");
return new Person(values[0], Integer.parseInt(values[1]));
List<String> values = Splitter.on(',').splitToList(in.nextString());
return new Person(values.get(0), Integer.parseInt(values.get(1)));
}
@Override public void write(JsonWriter out, Person person) throws IOException {
out.value(person.name + "," + person.age);

View File

@ -154,7 +154,7 @@ public class StringTest {
String value = gson.fromJson(json, String.class);
assertThat(value).isEqualTo("abc=");
json = "'abc\u003d'";
json = "'abc\\u003d'";
value = gson.fromJson(json, String.class);
assertThat(value).isEqualTo("abc=");
}

View File

@ -29,7 +29,6 @@ import com.google.gson.stream.JsonReader;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
@ -103,16 +102,12 @@ public class ToNumberPolicyFunctionalTest {
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create();
List<Object> expected = new LinkedList<>();
expected.add(null);
expected.add(10L);
expected.add(10.0);
Type objectCollectionType = new TypeToken<Collection<Object>>() { }.getType();
Collection<Object> objects = gson.fromJson("[null,10,10.0]", objectCollectionType);
assertThat(objects).isEqualTo(expected);
assertThat(objects).containsExactly(null, 10L, 10.0).inOrder();
Type numberCollectionType = new TypeToken<Collection<Number>>() { }.getType();
Collection<Object> numbers = gson.fromJson("[null,10,10.0]", numberCollectionType);
assertThat(numbers).isEqualTo(expected);
assertThat(numbers).containsExactly(null, 10L, 10.0).inOrder();
}
@Test

View File

@ -79,6 +79,7 @@ public class TreeTypeAdaptersTest {
assertThat(target.getId().getValue()).isEqualTo("1");
}
@SuppressWarnings("UnusedTypeParameter")
private static final class Id<R> {
final String value;
@SuppressWarnings("unused")

View File

@ -61,6 +61,7 @@ public final class LinkedTreeMapTest {
}
@Test
@SuppressWarnings("ModifiedButNotUsed")
public void testPutNullKeyFails() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
try {
@ -71,6 +72,7 @@ public final class LinkedTreeMapTest {
}
@Test
@SuppressWarnings("ModifiedButNotUsed")
public void testPutNonComparableKeyFails() {
LinkedTreeMap<Object, String> map = new LinkedTreeMap<>();
try {
@ -174,12 +176,12 @@ public final class LinkedTreeMapTest {
}
@Test
public void testLargeSetOfRandomKeys() throws Exception {
public void testLargeSetOfRandomKeys() {
Random random = new Random(1367593214724L);
LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
String[] keys = new String[1000];
for (int i = 0; i < keys.length; i++) {
keys[i] = Integer.toString(Math.abs(random.nextInt()), 36) + "-" + i;
keys[i] = Integer.toString(random.nextInt(), 36) + "-" + i;
map.put(keys[i], "" + i);
}

View File

@ -16,7 +16,7 @@
package com.google.gson.internal;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertThrows;
import org.junit.Test;
@ -40,13 +40,11 @@ public final class UnsafeAllocatorInstantiationTest {
* to instantiate an interface
*/
@Test
public void testInterfaceInstantiation() throws Exception {
try {
UnsafeAllocator.INSTANCE.newInstance(Interface.class);
fail();
} catch (AssertionError e) {
assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type");
}
public void testInterfaceInstantiation() {
AssertionError e = assertThrows(AssertionError.class,
() -> UnsafeAllocator.INSTANCE.newInstance(Interface.class));
assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type");
}
/**
@ -54,13 +52,11 @@ public final class UnsafeAllocatorInstantiationTest {
* to instantiate an abstract class
*/
@Test
public void testAbstractClassInstantiation() throws Exception {
try {
UnsafeAllocator.INSTANCE.newInstance(AbstractClass.class);
fail();
} catch (AssertionError e) {
assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type");
}
public void testAbstractClassInstantiation() {
AssertionError e = assertThrows(AssertionError.class,
() -> UnsafeAllocator.INSTANCE.newInstance(AbstractClass.class));
assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type");
}
/**

View File

@ -39,6 +39,7 @@ import org.junit.Test;
*
* @author Joel Leitch
*/
@SuppressWarnings("JavaUtilDate")
public class DefaultDateTypeAdapterTest {
@Test
@ -226,6 +227,7 @@ public class DefaultDateTypeAdapterTest {
assertThat(adapter.toJson(new Date(0))).isEqualTo(toLiteral(formatted));
}
@SuppressWarnings("UndefinedEquals")
private static void assertParsed(String date, TypeAdapterFactory adapterFactory) throws IOException {
TypeAdapter<Date> adapter = dateAdapter(adapterFactory);
assertWithMessage(date).that(adapter.fromJson(toLiteral(date))).isEqualTo(new Date(0));

View File

@ -57,6 +57,7 @@ public class ISO8601UtilsTest {
}
@Test
@SuppressWarnings("JavaUtilDate")
public void testDateFormatWithMilliseconds() {
long time = 1530209176870L;
Date date = new Date(time);
@ -66,6 +67,7 @@ public class ISO8601UtilsTest {
}
@Test
@SuppressWarnings("JavaUtilDate")
public void testDateFormatWithTimezone() {
long time = 1530209176870L;
Date date = new Date(time);
@ -75,6 +77,7 @@ public class ISO8601UtilsTest {
}
@Test
@SuppressWarnings("UndefinedEquals")
public void testDateParseWithDefaultTimezone() throws ParseException {
String dateStr = "2018-06-25";
Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));
@ -103,6 +106,7 @@ public class ISO8601UtilsTest {
}
@Test
@SuppressWarnings("UndefinedEquals")
public void testDateParseWithTimezone() throws ParseException {
String dateStr = "2018-06-25T00:00:00-03:00";
Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));
@ -113,6 +117,7 @@ public class ISO8601UtilsTest {
}
@Test
@SuppressWarnings("UndefinedEquals")
public void testDateParseSpecialTimezone() throws ParseException {
String dateStr = "2018-06-25T00:02:00-02:58";
Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));

View File

@ -29,6 +29,8 @@ import java.util.Set;
import org.junit.Test;
/**
* Tests for {@link TypeToken}.
*
* @author Jesse Wilson
*/
public final class TypeTokenTest {

View File

@ -18,6 +18,7 @@ package com.google.gson.regression;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.base.Splitter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
@ -41,7 +42,7 @@ public class OSGiTest {
Manifest mf = findManifest("com.google.gson");
String importPkg = mf.getMainAttributes().getValue("Import-Package");
assertWithMessage("Import-Package statement is there").that(importPkg).isNotNull();
for (String dep : importPkg.split(",")) {
for (String dep : Splitter.on(',').split(importPkg)) {
if (dep.contains("sun.misc")) {
assertSubstring("sun.misc import is optional", dep, "resolution:=optional");
return;

View File

@ -642,6 +642,7 @@ public final class JsonReaderTest {
strictReader.nextDouble();
fail("Should have failed reading " + s + " as double");
} catch (MalformedJsonException e) {
assertThat(e).hasMessageThat().startsWith("Use JsonReader.setLenient(true) to accept malformed JSON");
}
}
@ -705,7 +706,6 @@ public final class JsonReaderTest {
/**
* Issue 1053, negative zero.
* @throws Exception
*/
@Test
public void testNegativeZero() throws Exception {
@ -741,6 +741,8 @@ public final class JsonReaderTest {
@Test
@Ignore
public void disabled_testPeekLargerThanLongMinValue() throws IOException {
@SuppressWarnings("FloatingPointLiteralPrecision")
double d = -9223372036854775809d;
JsonReader reader = new JsonReader(reader("[-9223372036854775809]"));
reader.setLenient(true);
reader.beginArray();
@ -750,7 +752,7 @@ public final class JsonReaderTest {
fail();
} catch (NumberFormatException expected) {
}
assertThat(reader.nextDouble()).isEqualTo(-9223372036854775809d);
assertThat(reader.nextDouble()).isEqualTo(d);
}
/**
@ -769,6 +771,8 @@ public final class JsonReaderTest {
@Test
public void testPeekMuchLargerThanLongMinValue() throws IOException {
@SuppressWarnings("FloatingPointLiteralPrecision")
double d = -92233720368547758080d;
JsonReader reader = new JsonReader(reader("[-92233720368547758080]"));
reader.setLenient(true);
reader.beginArray();
@ -778,12 +782,12 @@ public final class JsonReaderTest {
fail();
} catch (NumberFormatException expected) {
}
assertThat(reader.nextDouble()).isEqualTo(-92233720368547758080d);
assertThat(reader.nextDouble()).isEqualTo(d);
}
@Test
public void testQuotedNumberWithEscape() throws IOException {
JsonReader reader = new JsonReader(reader("[\"12\u00334\"]"));
JsonReader reader = new JsonReader(reader("[\"12\\u00334\"]"));
reader.setLenient(true);
reader.beginArray();
assertThat(reader.peek()).isEqualTo(STRING);
@ -2005,6 +2009,7 @@ public final class JsonReaderTest {
reader.peek();
fail();
} catch (IOException expected) {
// OK: Should fail
}
} else {
throw new AssertionError();

View File

@ -15,6 +15,8 @@
*/
package com.google.gson.metrics;
import com.google.common.base.Objects;
/**
* Class with a bunch of primitive fields
*
@ -63,19 +65,18 @@ public class BagOfPrimitives {
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
BagOfPrimitives other = (BagOfPrimitives) obj;
if (booleanValue != other.booleanValue) return false;
if (intValue != other.intValue) return false;
if (longValue != other.longValue) return false;
if (stringValue == null) {
return other.stringValue == null;
} else {
return stringValue.equals(other.stringValue);
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BagOfPrimitives)) {
return false;
}
BagOfPrimitives that = (BagOfPrimitives) o;
return longValue == that.longValue
&& intValue == that.intValue
&& booleanValue == that.booleanValue
&& Objects.equal(stringValue, that.stringValue);
}
@Override

View File

@ -64,6 +64,7 @@ public class CollectionsDeserializationBenchmark {
/**
* Benchmark to measure deserializing objects by hand
*/
@SuppressWarnings("ModifiedButNotUsed")
public void timeCollectionsStreaming(int reps) throws IOException {
for (int i=0; i<reps; ++i) {
StringReader reader = new StringReader(json);
@ -102,6 +103,7 @@ public class CollectionsDeserializationBenchmark {
* setting object values by reflection. We should strive to reduce the discrepancy between this
* and {@link #timeCollectionsDefault(int)} .
*/
@SuppressWarnings("ModifiedButNotUsed")
public void timeCollectionsReflectionStreaming(int reps) throws Exception {
for (int i=0; i<reps; ++i) {
StringReader reader = new StringReader(json);

View File

@ -38,7 +38,6 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
@ -64,7 +63,9 @@ public final class ParseBenchmark {
READER_SHORT(new TypeToken<Feed>() {}, new TypeReference<Feed>() {}),
READER_LONG(new TypeToken<Feed>() {}, new TypeReference<Feed>() {});
@SuppressWarnings("ImmutableEnumChecker")
private final TypeToken<?> gsonType;
@SuppressWarnings("ImmutableEnumChecker")
private final TypeReference<?> jacksonType;
private Document(TypeToken<?> typeToken, TypeReference<?> typeReference) {

View File

@ -99,7 +99,7 @@
<compilerArgs>
<!-- Args related to Error Prone, see: https://errorprone.info/docs/installation#maven -->
<arg>-XDcompilePolicy=simple</arg>
<arg>-Xplugin:ErrorProne -XepExcludedPaths:.*gson/src/test.*|.*extras/src/test.*|.*proto.*</arg>
<arg>-Xplugin:ErrorProne -XepExcludedPaths:.*/generated-test-sources/protobuf/.*</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg>
@ -144,6 +144,7 @@
<detectJavaApiLink>false</detectJavaApiLink>
<links>
<link>https://docs.oracle.com/en/java/javase/11/docs/api/</link>
<link>https://errorprone.info/api/latest/</link>
</links>
<!-- Disable detection of offline links between Maven modules:
(1) Only `gson` module is published, so for other modules Javadoc links don't

View File

@ -28,8 +28,6 @@ import com.google.gson.protobuf.generated.Annotations;
import com.google.gson.protobuf.generated.Bag.OuterMessage;
import com.google.gson.protobuf.generated.Bag.ProtoWithAnnotations;
import com.google.gson.protobuf.generated.Bag.ProtoWithAnnotations.InnerMessage;
import com.google.gson.protobuf.generated.Bag.ProtoWithAnnotations.InnerMessage.Data;
import com.google.gson.protobuf.generated.Bag.ProtoWithAnnotations.InnerMessage.Type;
import com.google.protobuf.GeneratedMessageV3;
import org.junit.Before;
import org.junit.Test;
@ -111,11 +109,11 @@ public class ProtosWithAnnotationsTest {
assertThat(proto.hasInnerMessage1()).isFalse();
assertThat(proto.getInnerMessage2()).isEqualTo(InnerMessage.newBuilder()
.setNIdCt(98798465)
.setContent(Type.TEXT)
.addData(Data.newBuilder()
.setContent(InnerMessage.Type.TEXT)
.addData(InnerMessage.Data.newBuilder()
.setData("OFIN8e9fhwoeh8((⁹8efywoih")
.setHeight(665))
.addData(Data.newBuilder()
.addData(InnerMessage.Data.newBuilder()
.setData("65")
.setWidth(-56684))
.build());
@ -149,7 +147,7 @@ public class ProtosWithAnnotationsTest {
+ " \"content\":\"UNKNOWN\"%n"
+ "}");
InnerMessage proto = gson.fromJson(json, InnerMessage.class);
assertThat(proto.getContent()).isEqualTo(Type.UNKNOWN);
assertThat(proto.getContent()).isEqualTo(InnerMessage.Type.UNKNOWN);
}
@Test
@ -171,7 +169,7 @@ public class ProtosWithAnnotationsTest {
+ " \"content\":\"0\"%n"
+ "}");
InnerMessage proto = gsonWithEnumNumbers.fromJson(json, InnerMessage.class);
assertThat(proto.getContent()).isEqualTo(Type.UNKNOWN);
assertThat(proto.getContent()).isEqualTo(InnerMessage.Type.UNKNOWN);
String rebuilt = gsonWithEnumNumbers.toJson(proto);
assertThat(rebuilt).isEqualTo("{\"content\":0}");
@ -179,7 +177,7 @@ public class ProtosWithAnnotationsTest {
+ " \"content\":\"2\"%n"
+ "}");
proto = gsonWithEnumNumbers.fromJson(json, InnerMessage.class);
assertThat(proto.getContent()).isEqualTo(Type.IMAGE);
assertThat(proto.getContent()).isEqualTo(InnerMessage.Type.IMAGE);
rebuilt = gsonWithEnumNumbers.toJson(proto);
assertThat(rebuilt).isEqualTo("{\"content\":2}");
}
@ -194,11 +192,11 @@ public class ProtosWithAnnotationsTest {
.setLongTimestamp(468406876880768L))
.setInnerMessage1(InnerMessage.newBuilder()
.setNIdCt(12)
.setContent(Type.IMAGE)
.addData(Data.newBuilder()
.setContent(InnerMessage.Type.IMAGE)
.addData(InnerMessage.Data.newBuilder()
.setData("data$$")
.setWidth(200))
.addData(Data.newBuilder()
.addData(InnerMessage.Data.newBuilder()
.setHeight(56)))
.build();

View File

@ -57,7 +57,6 @@ public class ProtosWithPrimitiveTypesTest {
@Test
public void testSerializeProto() {
Descriptor descriptor = SimpleProto.getDescriptor();
SimpleProto proto = SimpleProto.newBuilder()
.setCount(3)
.setMsg("foo")