use of org.opensearch.common.xcontent.ToXContentObject in project OpenSearch by opensearch-project.
the class XContentHelperTests method testToXContent.
public void testToXContent() throws IOException {
final XContentType xContentType = randomFrom(XContentType.values());
final ToXContent toXContent;
final boolean error;
if (randomBoolean()) {
if (randomBoolean()) {
error = false;
toXContent = (builder, params) -> builder.field("field", "value");
} else {
error = true;
toXContent = (builder, params) -> builder.startObject().field("field", "value").endObject();
}
} else {
if (randomBoolean()) {
error = false;
toXContent = (ToXContentObject) (builder, params) -> builder.startObject().field("field", "value").endObject();
} else {
error = true;
toXContent = (ToXContentObject) (builder, params) -> builder.field("field", "value");
}
}
if (error) {
expectThrows(IOException.class, () -> XContentHelper.toXContent(toXContent, xContentType, randomBoolean()));
} else {
BytesReference bytes = XContentHelper.toXContent(toXContent, xContentType, randomBoolean());
try (XContentParser parser = xContentType.xContent().createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, bytes.streamInput())) {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
assertTrue(parser.nextToken().isValue());
assertEquals("value", parser.text());
assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken());
}
}
}
use of org.opensearch.common.xcontent.ToXContentObject in project OpenSearch by opensearch-project.
the class StringsTests method testToStringToXContent.
public void testToStringToXContent() {
final ToXContent toXContent;
final boolean error;
if (randomBoolean()) {
if (randomBoolean()) {
error = false;
toXContent = (builder, params) -> builder.field("ok", "here").field("catastrophe", "");
} else {
error = true;
toXContent = (builder, params) -> builder.startObject().field("ok", "here").field("catastrophe", "").endObject();
}
} else {
if (randomBoolean()) {
error = false;
toXContent = (ToXContentObject) (builder, params) -> builder.startObject().field("ok", "here").field("catastrophe", "").endObject();
} else {
error = true;
toXContent = (ToXContentObject) (builder, params) -> builder.field("ok", "here").field("catastrophe", "");
}
}
String toString = Strings.toString(toXContent);
if (error) {
assertThat(toString, containsString("\"error\":\"error building toString out of XContent:"));
assertThat(toString, containsString("\"stack_trace\":"));
} else {
assertThat(toString, containsString("\"ok\":\"here\""));
assertThat(toString, containsString("\"catastrophe\":\"\""));
}
}
Aggregations