Skip to content

Commit

Permalink
add tests for optional single value json
Browse files Browse the repository at this point in the history
  • Loading branch information
lucidd committed Sep 11, 2015
1 parent accdfbb commit 4fb5cb0
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ public Date read(JsonReader jsonReader) throws IOException {
*/
private class OptionalTypeAdapterFactory implements TypeAdapterFactory {

@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Type type = typeToken.getType();
Expand All @@ -151,6 +152,7 @@ public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {

private <A> TypeAdapter<Optional<A>> optionalAdapter(TypeAdapter<A> innerAdapter) {
return new TypeAdapter<Optional<A>>() {
@Override
public Optional<A> read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
Expand All @@ -161,12 +163,12 @@ public Optional<A> read(JsonReader in) throws IOException {
}
}

@Override
public void write(JsonWriter out, Optional<A> optional) throws IOException {
innerAdapter.write(out, optional.orElse(null));
}
};
}

}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,6 @@ public void testSaltStackJobsWithKwargsParser() throws Exception {
assertEquals("lucid", job.getUser());
}


@Test
public void testOptionalParser() {
InputStream is = this.getClass()
Expand All @@ -227,6 +226,19 @@ public void testOptionalParser() {
assertEquals(expected, result.maybeInts);
}

@Test
public void testOptionalSingleValue() {
JsonParser<Optional<Integer>> parser =
new JsonParser<>(new TypeToken<Optional<Integer>>(){});
InputStream nullValue = this.getClass()
.getResourceAsStream("/single_null_value.json");
assertFalse(parser.parse(nullValue).isPresent());

InputStream intValue = this.getClass()
.getResourceAsStream("/single_int_value.json");
assertEquals(new Integer(123), parser.parse(intValue).get());
}

@Test
public void testSaltStackJobsWithArgsAsKwargsParser() throws Exception {
InputStream is = this.getClass()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,4 @@ public class OptionalTest {
public Optional<String> valueString = Optional.empty();
public Optional<String> absentString = Optional.empty();
public List<Optional<Integer>> maybeInts;

}
1 change: 1 addition & 0 deletions src/test/resources/single_int_value.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
123
1 change: 1 addition & 0 deletions src/test/resources/single_null_value.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
null

0 comments on commit 4fb5cb0

Please sign in to comment.