|
33 | 33 | import static org.hamcrest.Matchers.hasSize;
|
34 | 34 | import static org.hamcrest.Matchers.in;
|
35 | 35 | import static org.hamcrest.Matchers.instanceOf;
|
| 36 | +import static org.hamcrest.Matchers.is; |
36 | 37 | import static org.hamcrest.Matchers.nullValue;
|
37 | 38 | import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage;
|
38 | 39 |
|
@@ -83,6 +84,44 @@ public void testFloat() throws IOException {
|
83 | 84 | }
|
84 | 85 | }
|
85 | 86 |
|
| 87 | + public void testLongCoercion() throws IOException { |
| 88 | + XContentType xContentType = randomFrom(XContentType.values()); |
| 89 | + |
| 90 | + try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) { |
| 91 | + builder.startObject(); |
| 92 | + builder.field("decimal", "5.5"); |
| 93 | + builder.field("expInRange", "5e18"); |
| 94 | + builder.field("expTooBig", "2e100"); |
| 95 | + builder.field("expTooSmall", "2e-100"); |
| 96 | + builder.endObject(); |
| 97 | + |
| 98 | + try (XContentParser parser = createParser(xContentType.xContent(), BytesReference.bytes(builder))) { |
| 99 | + assertThat(parser.nextToken(), is(XContentParser.Token.START_OBJECT)); |
| 100 | + |
| 101 | + assertThat(parser.nextToken(), is(XContentParser.Token.FIELD_NAME)); |
| 102 | + assertThat(parser.currentName(), is("decimal")); |
| 103 | + assertThat(parser.nextToken(), is(XContentParser.Token.VALUE_STRING)); |
| 104 | + assertThat(parser.longValue(), equalTo(5L)); |
| 105 | + |
| 106 | + assertThat(parser.nextToken(), is(XContentParser.Token.FIELD_NAME)); |
| 107 | + assertThat(parser.currentName(), is("expInRange")); |
| 108 | + assertThat(parser.nextToken(), is(XContentParser.Token.VALUE_STRING)); |
| 109 | + assertThat(parser.longValue(), equalTo((long) 5e18)); |
| 110 | + |
| 111 | + assertThat(parser.nextToken(), is(XContentParser.Token.FIELD_NAME)); |
| 112 | + assertThat(parser.currentName(), is("expTooBig")); |
| 113 | + assertThat(parser.nextToken(), is(XContentParser.Token.VALUE_STRING)); |
| 114 | + expectThrows(IllegalArgumentException.class, parser::longValue); |
| 115 | + |
| 116 | + // too small goes to zero |
| 117 | + assertThat(parser.nextToken(), is(XContentParser.Token.FIELD_NAME)); |
| 118 | + assertThat(parser.currentName(), is("expTooSmall")); |
| 119 | + assertThat(parser.nextToken(), is(XContentParser.Token.VALUE_STRING)); |
| 120 | + assertThat(parser.longValue(), equalTo(0L)); |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
86 | 125 | public void testReadList() throws IOException {
|
87 | 126 | assertThat(readList("{\"foo\": [\"bar\"]}"), contains("bar"));
|
88 | 127 | assertThat(readList("{\"foo\": [\"bar\",\"baz\"]}"), contains("bar", "baz"));
|
|
0 commit comments