Skip to content

Commit

Permalink
Handle empty inputs for JSON better
Browse files Browse the repository at this point in the history
We now return `null` instead of throwing an exception
if we attempt to read from an inputstream that doesn't
have any JSON content.
  • Loading branch information
shs96c committed Jul 12, 2021
1 parent 960e168 commit 4c382be
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions java/client/src/org/openqa/selenium/json/JsonInput.java
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,13 @@ public void skipValue() {
}

public <T> T read(Type type) {
skipWhitespace(input);

// Guard against reading an empty stream
if (input.peek() == Input.EOF) {
return null;
}

return coercer.coerce(this, type, setter);
}

Expand Down
31 changes: 31 additions & 0 deletions java/client/test/org/openqa/selenium/json/JsonInputTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.openqa.selenium.json;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.openqa.selenium.json.Json.MAP_TYPE;
Expand All @@ -35,7 +36,13 @@
import org.junit.experimental.categories.Category;
import org.openqa.selenium.testing.UnitTests;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -258,6 +265,30 @@ public void shouldBeAbleToReadNonWellFormedDataLongerThanReadBuffer() {
raw, raw.substring(raw.length() - 128)));
}

@Test
public void nullInputsShouldCoerceAsNullValues() throws IOException {
try (InputStream is = new ByteArrayInputStream(new byte[0]);
Reader reader = new InputStreamReader(is, UTF_8);
JsonInput input = new Json().newInput(reader)) {

Object value = input.read(MAP_TYPE);

assertThat(value).isNull();
}
}

@Test
public void emptyStringsWithNoJsonValuesComeBackAsNull() throws IOException {
try (InputStream is = new ByteArrayInputStream(" ".getBytes(UTF_8));
Reader reader = new InputStreamReader(is, UTF_8);
JsonInput input = new Json().newInput(reader)) {

Object value = input.read(String.class);

assertThat(value).isNull();
}
}

private JsonInput newInput(String raw) {
StringReader reader = new StringReader(raw);
return new JsonInput(reader, new JsonTypeCoercer(), BY_NAME);
Expand Down

0 comments on commit 4c382be

Please sign in to comment.