gson-comments/gson/src/test/java/com/google/gson/MixedStreamTest.java
Éamonn McManus b3dce2dc17
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437)
* Strict mode for JSON parsing (#2323)

* Feat #6: Add strict flag to Gson and GsonBuilder

* Test #2: Add failing tests for capitalized keywords

* Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used

* Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode

* Test #3: Simplify test cases by removing unnecessary array

* Feat #3: Improve error by including the illegal character

* Feat #5: JsonReader does not allow unespaced control flow characters in strict mode

* Test #5: Test unespaced control flow characters in strict mode

* Feat #4: Disallow espaced newline character in strict mode

* Test #4: Add tests for (dis)allowing newline character depensding on strictness

* Test #5: Test case for unescaped control char in non-strict mode

* Test #2: Simplify test cases

* Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder

* Feat #15: Change JsonWriter API to also use Strictness

* Test #15: Test Strictness in JsonWriter API

* Doc #15: Add and update documentation for Strictness in JsonWriter API

* refactor #12: Fixed typos and empty catch brackets in tests

* refactor #12: Resolved importing wildcards, made some lines adhere to Google java style

* #5 Add test case for unescaped control characters

* Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions.

* Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions.

* Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue

* Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue

---------

Co-authored-by: LMC117 <2295699210@qq.com>
Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com>

* Doc #17: Add and change javadoc of public methods

* Doc #17: Update JavaDoc in JsonReader and Strictness

* Doc #17: Update JavaDoc in Gson and GsonBuilder

* Test #34: Add tests for setting strictness through GsonBuilder

* Fix: Add Fix broken test

* Fix: Invalid JavaDoc in Gson.java

* Doc #17: update outdated javadoc

* #37: Resolve more PR feedback 

* Fix #37: Resolve various PR comments

* Fix #37: Resolve various PR comments

* Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39)

* Doc #40: Update JavaDoc based on PR feedback

* Doc #40: Update old RFC in GsonBuilder documentation

* Doc #40: Fix formatting error in JavaDoc

* Doc #40: Add tests for setting strictness and lenient to JsonReaderTest

* Test #43: Changed tests to make use of assertThrows

* test #43: Changed tests to make use of assertThrows as per feedback

* Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows

* Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows

* test #43: Resolve PR recommendations

* Test #43: Mini change to TC

* Test #43: Mini change to TC

---------

Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com>

* doc #46: Resolved comments in main PR

* Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict

* Fix #45: Small type

* Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Fix #45: Resolve various comments by Marcono1234

* Update gson/src/main/java/com/google/gson/GsonBuilder.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Fix #45: Resolve various comments by Marcono1234

* Fix #45: Resolve various comments by eamonmcmanus

* Strictness mode follow-up

* Update Troubleshooting.md and Gson default lenient mode documentation

* Always use GSON strictness when set.

* Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT

* Update JavaDoc with new strictness functionality

* Replace default with legacy strict for JsonReader javadoc

* Add JSONReader test cases for U2028 and U2029

* Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion

* Deprecate setLenient in favor of setStrictness

---------

Co-authored-by: Carl Peterson <unknown>
Co-authored-by: Gustaf Johansson <gustajoh@kth.se>
Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com>
Co-authored-by: LMC117 <2295699210@qq.com>
Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Strictness follow-up (#2408)

* Strictness mode follow-up

- Remove mentions of `null` Gson strictness; this is an implementation detail
- Fix incorrect / outdated documentation
- Reduce links to RFC; if there is already a link to it in a previous sentence
  don't link to it again
- Extend and update tests
- Minor punctuation changes in documentation for consistency

* Deprecate `setLenient` methods

* `strictness2` fixes & improvements (#2456)

* Adjust ProGuard default rules and shrinking tests (#2420)

* Adjust ProGuard default rules and shrinking tests

* Adjust comment

* Add shrinking test for class without no-args constructor; improve docs

* Improve Unsafe mention in Troubleshooting Guide

* Improve comment for `-if class *`

* Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444)

Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre.
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

---
updated-dependencies:
- dependency-name: com.google.guava:guava
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443)

Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre.
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

---
updated-dependencies:
- dependency-name: com.google.guava:guava-testlib
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447)

This partially restores the behavior before a589ef2008,
except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)`
was created, whereas now a `TypeToken(Class)` is created instead.

* Fixed Typo in GsonBuilder.java (#2449)

* Make date-formatting tests less fragile with regular expressions. (#2450)

* Make date-formatting tests less fragile with regular expressions.

This is not great. We should really ensure that formatted dates are the same
regardless of JDK version. There is code that attempts to do that but it is not
really effective. So for now we fudge around the differences by using regular
expressions to paper over the differences.

* Temporarily add test-debugging code.

* Another attempt at debugging a test failure.

* Fix pattern in assertion.

* Modification in test cases (#2454)

* Fixed Typo in GsonBuilder.java

* Suggestions on Test cases

* Modified test cases using assertThrows method (JUnit)

* Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/GsonTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/TypeAdapterTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/TypeAdapterTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

---------

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>

* Minor follow-up changes

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: elevne <97422844+elevne@users.noreply.github.com>
Co-authored-by: Éamonn McManus <emcmanus@google.com>
Co-authored-by: Wonil <cwi5525@naver.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Marten <martenvoorberg@gmail.com>
Co-authored-by: Gustaf Johansson <gustajoh@kth.se>
Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com>
Co-authored-by: LMC117 <2295699210@qq.com>
Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: elevne <97422844+elevne@users.noreply.github.com>
Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 09:20:32 -07:00

259 lines
7.8 KiB
Java

/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public final class MixedStreamTest {
private static final Car BLUE_MUSTANG = new Car("mustang", 0x0000FF);
private static final Car BLACK_BMW = new Car("bmw", 0x000000);
private static final Car RED_MIATA = new Car("miata", 0xFF0000);
private static final String CARS_JSON = "[\n"
+ " {\n"
+ " \"name\": \"mustang\",\n"
+ " \"color\": 255\n"
+ " },\n"
+ " {\n"
+ " \"name\": \"bmw\",\n"
+ " \"color\": 0\n"
+ " },\n"
+ " {\n"
+ " \"name\": \"miata\",\n"
+ " \"color\": 16711680\n"
+ " }\n"
+ "]";
@Test
public void testWriteMixedStreamed() throws IOException {
Gson gson = new Gson();
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.setIndent(" ");
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
gson.toJson(BLACK_BMW, Car.class, jsonWriter);
gson.toJson(RED_MIATA, Car.class, jsonWriter);
jsonWriter.endArray();
assertThat(stringWriter.toString()).isEqualTo(CARS_JSON);
}
@Test
public void testReadMixedStreamed() throws IOException {
Gson gson = new Gson();
StringReader stringReader = new StringReader(CARS_JSON);
JsonReader jsonReader = new JsonReader(stringReader);
jsonReader.beginArray();
// actual and expected object are inverted in the test.
// gson.fromJson(jsonReader, Car.class) as arg of assertThat() cause an ambiguous method call
assertThat(BLUE_MUSTANG).isEqualTo(gson.fromJson(jsonReader, Car.class));
assertThat(BLACK_BMW).isEqualTo(gson.fromJson(jsonReader, Car.class));
assertThat(RED_MIATA).isEqualTo(gson.fromJson(jsonReader, Car.class));
jsonReader.endArray();
}
@SuppressWarnings("deprecation") // for JsonReader.setLenient
@Test
public void testReaderDoesNotMutateState() throws IOException {
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
jsonReader.beginArray();
jsonReader.setLenient(false);
Car unused1 = gson.fromJson(jsonReader, Car.class);
assertThat(jsonReader.isLenient()).isFalse();
jsonReader.setLenient(true);
Car unused2 = gson.fromJson(jsonReader, Car.class);
assertThat(jsonReader.isLenient()).isTrue();
}
@SuppressWarnings("deprecation") // for JsonWriter.setLenient
@Test
public void testWriteDoesNotMutateState() throws IOException {
Gson gson = new Gson();
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
jsonWriter.beginArray();
jsonWriter.setHtmlSafe(true);
jsonWriter.setLenient(true);
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
assertThat(jsonWriter.isHtmlSafe()).isTrue();
assertThat(jsonWriter.isLenient()).isTrue();
jsonWriter.setHtmlSafe(false);
jsonWriter.setLenient(false);
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
assertThat(jsonWriter.isHtmlSafe()).isFalse();
assertThat(jsonWriter.isLenient()).isFalse();
}
@Test
public void testReadInvalidState() throws IOException {
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
jsonReader.beginArray();
jsonReader.beginObject();
try {
gson.fromJson(jsonReader, String.class);
fail();
} catch (JsonParseException expected) {
}
}
@Test
public void testReadClosed() throws IOException {
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
jsonReader.close();
try {
gson.fromJson(jsonReader, new TypeToken<List<Car>>() {}.getType());
fail();
} catch (JsonParseException expected) {
}
}
@Test
public void testWriteInvalidState() throws IOException {
Gson gson = new Gson();
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
jsonWriter.beginObject();
try {
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
fail();
} catch (IllegalStateException expected) {
}
}
@Test
public void testWriteClosed() throws IOException {
Gson gson = new Gson();
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
jsonWriter.beginArray();
jsonWriter.endArray();
jsonWriter.close();
try {
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
fail();
} catch (IllegalStateException expected) {
}
}
@Test
public void testWriteNulls() {
Gson gson = new Gson();
try {
gson.toJson(new JsonPrimitive("hello"), (JsonWriter) null);
fail();
} catch (NullPointerException expected) {
}
StringWriter stringWriter = new StringWriter();
gson.toJson(null, new JsonWriter(stringWriter));
assertThat(stringWriter.toString()).isEqualTo("null");
}
@Test
public void testReadNulls() {
Gson gson = new Gson();
try {
gson.fromJson((JsonReader) null, Integer.class);
fail();
} catch (NullPointerException expected) {
}
try {
gson.fromJson(new JsonReader(new StringReader("true")), (Type) null);
fail();
} catch (NullPointerException expected) {
}
}
@Test
public void testWriteHtmlSafe() {
List<String> contents = Arrays.asList("<", ">", "&", "=", "'");
Type type = new TypeToken<List<String>>() {}.getType();
StringWriter writer = new StringWriter();
new Gson().toJson(contents, type, new JsonWriter(writer));
assertThat(writer.toString())
.isEqualTo("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]");
writer = new StringWriter();
new GsonBuilder().disableHtmlEscaping().create()
.toJson(contents, type, new JsonWriter(writer));
assertThat(writer.toString())
.isEqualTo("[\"<\",\">\",\"&\",\"=\",\"'\"]");
}
@Test
public void testWriteLenient() {
List<Double> doubles = Arrays.asList(Double.NaN, Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY, -0.0d, 0.5d, 0.0d);
Type type = new TypeToken<List<Double>>() {}.getType();
StringWriter writer = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(writer);
new GsonBuilder().serializeSpecialFloatingPointValues().create()
.toJson(doubles, type, jsonWriter);
assertThat(writer.toString()).isEqualTo("[NaN,-Infinity,Infinity,-0.0,0.5,0.0]");
try {
new Gson().toJson(doubles, type, new JsonWriter(new StringWriter()));
fail();
} catch (IllegalArgumentException expected) {
}
}
static final class Car {
String name;
int color;
Car(String name, int color) {
this.name = name;
this.color = color;
}
// used by Gson
Car() {}
@Override public int hashCode() {
return name.hashCode() ^ color;
}
@Override public boolean equals(Object o) {
return o instanceof Car
&& ((Car) o).name.equals(name)
&& ((Car) o).color == color;
}
}
}