Improve resiliency to auto-formatting in client (#48617)

Backport of #48447. Make a number of changes so that code in the
`client` directory is more resilient to automatic formatting. This
covers:

* Literal JSON handling:
   * Reformatting multiline JSON to embed whitespace in the strings
   * Remove string concatenation where JSON fits on a single line
   * Use `String.format` for large documents with variable content
* Remove some erroneous doc refs in `QueryDSLDocumentationTests`
* Move some comments around to they aren't auto-formatted to a strange
  place
This commit is contained in:
Rory Hunter 2019-10-29 10:40:54 +00:00 committed by GitHub
parent 61a4e24ecf
commit da4654527b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 222 additions and 211 deletions

View File

@ -1558,10 +1558,8 @@ public class IndicesClientIT extends ESRestHighLevelClientTestCase {
.order(10)
.create(randomBoolean())
.settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0"))
.mapping("{ \"properties\":{"
+ "\"host_name\": {\"type\":\"keyword\"}"
+ "}"
+ "}", XContentType.JSON)
.mapping("{ \"properties\": { \"host_name\": { \"type\": \"keyword\" } } }", XContentType.JSON)
.alias(new Alias("alias-1").indexRouting("abc"))
.alias(new Alias("alias-1").indexRouting("abc")).alias(new Alias("{index}-write").searchRouting("xyz"));
AcknowledgedResponse putTemplateResponse = execute(putTemplateRequest,
@ -1585,13 +1583,18 @@ public class IndicesClientIT extends ESRestHighLevelClientTestCase {
.order(10)
.create(randomBoolean())
.settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0"))
.mapping("{ "
+ "\"my_doc_type\":{"
+ "\"properties\":{"
+ "\"host_name\": {\"type\":\"keyword\"}"
+ "}"
+ "}"
+ "}", XContentType.JSON)
.mapping(
"{"
+ " \"my_doc_type\": {"
+ " \"properties\": {"
+ " \"host_name\": {"
+ " \"type\": \"keyword\""
+ " }"
+ " }"
+ " }"
+ "}",
XContentType.JSON
)
.alias(new Alias("alias-1").indexRouting("abc")).alias(new Alias("{index}-write").searchRouting("xyz"));
@ -1688,8 +1691,16 @@ public class IndicesClientIT extends ESRestHighLevelClientTestCase {
createIndex(index, Settings.EMPTY);
Request postDoc = new Request(HttpPost.METHOD_NAME, "/" + index + "/_doc");
postDoc.setJsonEntity(
"{\"type\":\"act\",\"line_id\":1,\"play_name\":\"Henry IV\", \"speech_number\":\"\"," +
"\"line_number\":\"\",\"speaker\":\"\",\"text_entry\":\"ACT I\"}");
"{"
+ " \"type\": \"act\","
+ " \"line_id\": 1,"
+ " \"play_name\": \"Henry IV\","
+ " \"speech_number\": \"\","
+ " \"line_number\": \"\","
+ " \"speaker\": \"\","
+ " \"text_entry\": \"ACT I\""
+ "}"
);
assertOK(client().performRequest(postDoc));
QueryBuilder builder = QueryBuilders

View File

@ -93,10 +93,29 @@ public class IngestRequestConvertersTests extends ESTestCase {
public void testSimulatePipeline() throws IOException {
String pipelineId = ESTestCase.randomBoolean() ? "some_pipeline_id" : null;
boolean verbose = ESTestCase.randomBoolean();
String json = "{\"pipeline\":{" +
"\"description\":\"_description\"," +
"\"processors\":[{\"set\":{\"field\":\"field2\",\"value\":\"_value\"}}]}," +
"\"docs\":[{\"_index\":\"index\",\"_type\":\"_doc\",\"_id\":\"id\",\"_source\":{\"foo\":\"rab\"}}]}";
String json = "{"
+ " \"pipeline\": {"
+ " \"description\": \"_description\","
+ " \"processors\": ["
+ " {"
+ " \"set\": {"
+ " \"field\": \"field2\","
+ " \"value\": \"_value\""
+ " }"
+ " }"
+ " ]"
+ " },"
+ " \"docs\": ["
+ " {"
+ " \"_index\": \"index\","
+ " \"_type\": \"_doc\","
+ " \"_id\": \"id\","
+ " \"_source\": {"
+ " \"foo\": \"rab\""
+ " }"
+ " }"
+ " ]"
+ "}";
SimulatePipelineRequest request = new SimulatePipelineRequest(
new BytesArray(json.getBytes(StandardCharsets.UTF_8)),
XContentType.JSON

View File

@ -894,14 +894,7 @@ public class SearchIT extends ESRestHighLevelClientTestCase {
searchTemplateRequest.setRequest(new SearchRequest("index"));
searchTemplateRequest.setScriptType(ScriptType.INLINE);
searchTemplateRequest.setScript(
"{" +
" \"query\": {" +
" \"match\": {" +
" \"num\": {{number}}" +
" }" +
" }" +
"}");
searchTemplateRequest.setScript("{ \"query\": { \"match\": { \"num\": {{number}} } } }");
Map<String, Object> scriptParams = new HashMap<>();
scriptParams.put("number", 10);
@ -949,14 +942,7 @@ public class SearchIT extends ESRestHighLevelClientTestCase {
SearchTemplateRequest searchTemplateRequest = new SearchTemplateRequest();
searchTemplateRequest.setScriptType(ScriptType.INLINE);
searchTemplateRequest.setScript(
"{" +
" \"query\": {" +
" \"match\": {" +
" \"num\": {{number}}" +
" }" +
" }" +
"}");
searchTemplateRequest.setScript("{ \"query\": { \"match\": { \"num\": {{number}} } } }");
Map<String, Object> scriptParams = new HashMap<>();
scriptParams.put("number", 10);
@ -993,14 +979,7 @@ public class SearchIT extends ESRestHighLevelClientTestCase {
SearchTemplateRequest goodRequest = new SearchTemplateRequest();
goodRequest.setRequest(new SearchRequest("index"));
goodRequest.setScriptType(ScriptType.INLINE);
goodRequest.setScript(
"{" +
" \"query\": {" +
" \"match\": {" +
" \"num\": {{number}}" +
" }" +
" }" +
"}");
goodRequest.setScript("{ \"query\": { \"match\": { \"num\": {{number}} } } }");
Map<String, Object> scriptParams = new HashMap<>();
scriptParams.put("number", 10);
goodRequest.setScriptParams(scriptParams);
@ -1052,14 +1031,7 @@ public class SearchIT extends ESRestHighLevelClientTestCase {
SearchTemplateRequest badRequest1 = new SearchTemplateRequest();
badRequest1.setRequest(new SearchRequest("index"));
badRequest1.setScriptType(ScriptType.INLINE);
badRequest1.setScript(
"{" +
" \"query\": {" +
" \"match\": {" +
" \"num\": {{number}}" +
" }" +
" }" +
"}");
badRequest1.setScript("{ \"query\": { \"match\": { \"num\": {{number}} } } }");
Map<String, Object> scriptParams = new HashMap<>();
scriptParams.put("number", "BAD NUMBER");
badRequest1.setScriptParams(scriptParams);

View File

@ -93,8 +93,16 @@ public class TasksIT extends ESRestHighLevelClientTestCase {
RestClient lowClient = highLevelClient().getLowLevelClient();
Request request = new Request("POST", "_reindex");
request.addParameter("wait_for_completion", "false");
request.setJsonEntity("{" + " \"source\": {\n" + " \"index\": \"source1\"\n" + " },\n" + " \"dest\": {\n"
+ " \"index\": \"dest\"\n" + " }" + "}");
request.setJsonEntity(
"{"
+ " \"source\": {\n"
+ " \"index\": \"source1\"\n"
+ " },\n"
+ " \"dest\": {\n"
+ " \"index\": \"dest\"\n"
+ " }"
+ "}"
);
Response response = lowClient.performRequest(request);
Map<String, Object> map = entityAsMap(response);
Object taskId = map.get("task");

View File

@ -565,15 +565,9 @@ public class IndicesClientDocumentationIT extends ESRestHighLevelClientTestCase
CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT);
assertTrue(createIndexResponse.isAcknowledged());
PutMappingRequest request = new PutMappingRequest("twitter");
request.source(
"{\n" +
" \"properties\": {\n" +
" \"message\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}", // <1>
XContentType.JSON);
request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }",
XContentType.JSON
);
AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
assertTrue(putMappingResponse.isAcknowledged());
}
@ -619,15 +613,9 @@ public class IndicesClientDocumentationIT extends ESRestHighLevelClientTestCase
CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT);
assertTrue(createIndexResponse.isAcknowledged());
PutMappingRequest request = new PutMappingRequest("twitter");
request.source(
"{\n" +
" \"properties\": {\n" +
" \"message\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}", // <1>
XContentType.JSON);
request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }",
XContentType.JSON
);
AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
assertTrue(putMappingResponse.isAcknowledged());
}
@ -2295,14 +2283,9 @@ public class IndicesClientDocumentationIT extends ESRestHighLevelClientTestCase
PutIndexTemplateRequest putRequest = new PutIndexTemplateRequest("my-template");
putRequest.patterns(Arrays.asList("pattern-1", "log-*"));
putRequest.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1));
putRequest.mapping(
"{\n" +
" \"properties\": {\n" +
" \"message\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}", XContentType.JSON);
putRequest.mapping("{ \"properties\": { \"message\": { \"type\": \"text\" } } }",
XContentType.JSON
);
assertTrue(client.indices().putTemplate(putRequest, RequestOptions.DEFAULT).isAcknowledged());
}

View File

@ -456,26 +456,28 @@ public class QueryDSLDocumentationTests extends ESTestCase {
}
public void testRankFeatureSaturation() {
RankFeatureQueryBuilders.saturation(
"pagerank"); // <1>
RankFeatureQueryBuilders.saturation("pagerank");
}
public void testRankFeatureSaturationPivot() {
RankFeatureQueryBuilders.saturation(
"pagerank", // <1>
8); // <2>
"pagerank",
8
);
}
public void testRankFeatureLog() {
RankFeatureQueryBuilders.log(
"pagerank", // <1>
4f); // <2>
"pagerank",
4f
);
}
public void testRankFeatureSigmoid() {
RankFeatureQueryBuilders.sigmoid(
"pagerank", // <1>
7, // <2>
0.6f); // <3>
"pagerank",
7,
0.6f
);
}
}

View File

@ -773,11 +773,10 @@ public class SearchDocumentationIT extends ESRestHighLevelClientTestCase {
// end::render-search-template-response
assertNotNull(source);
assertEquals((
"{" +
" \"size\" : \"5\"," +
" \"query\": { \"match\" : { \"title\" : \"elasticsearch\" } }" +
"}").replaceAll("\\s+", ""), source.utf8ToString());
assertEquals(
("{ \"size\" : \"5\", \"query\": { \"match\" : { \"title\" : \"elasticsearch\" } }}").replaceAll("\\s+", ""),
source.utf8ToString()
);
}
public void testSearchTemplateWithStoredScript() throws Exception {

View File

@ -1,4 +1,6 @@
package org.elasticsearch.client.documentation;/*
package org.elasticsearch.client.documentation;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright

View File

@ -55,12 +55,8 @@ import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester;
import static org.hamcrest.Matchers.equalTo;
public class GetIndexTemplatesResponseTests extends ESTestCase {
static final String mappingString = "{\"properties\":{"
+ "\"f1\": {\"type\":\"text\"},"
+ "\"f2\": {\"type\":\"keyword\"}"
+ "}}";
static final String mappingString = "{\"properties\":{\"f1\": {\"type\":\"text\"},\"f2\": {\"type\":\"keyword\"}}}";
public void testFromXContent() throws IOException {
xContentTester(this::createParser,
@ -147,7 +143,7 @@ public class GetIndexTemplatesResponseTests extends ESTestCase {
;
}
private static void assertEqualInstances(GetIndexTemplatesResponse expectedInstance, GetIndexTemplatesResponse newInstance) {
private static void assertEqualInstances(GetIndexTemplatesResponse expectedInstance, GetIndexTemplatesResponse newInstance) {
assertEquals(expectedInstance, newInstance);
// Check there's no doc types at the root of the mapping
Map<String, Object> expectedMap = XContentHelper.convertToMap(
@ -157,10 +153,10 @@ public class GetIndexTemplatesResponseTests extends ESTestCase {
if(mappingMD != null) {
Map<String, Object> mappingAsMap = mappingMD.sourceAsMap();
assertEquals(expectedMap, mappingAsMap);
}
}
}
}
}
static GetIndexTemplatesResponse createTestInstance() {
List<IndexTemplateMetaData> templates = new ArrayList<>();
int numTemplates = between(0, 10);
@ -196,20 +192,20 @@ public class GetIndexTemplatesResponseTests extends ESTestCase {
// As the client class GetIndexTemplatesResponse doesn't have toXContent method, adding this method here only for the test
static void toXContent(GetIndexTemplatesResponse response, XContentBuilder builder) throws IOException {
//Create a server-side counterpart for the client-side class and call toXContent on it
List<org.elasticsearch.cluster.metadata.IndexTemplateMetaData> serverIndexTemplates = new ArrayList<>();
List<IndexTemplateMetaData> clientIndexTemplates = response.getIndexTemplates();
for (IndexTemplateMetaData clientITMD : clientIndexTemplates) {
org.elasticsearch.cluster.metadata.IndexTemplateMetaData.Builder serverTemplateBuilder =
org.elasticsearch.cluster.metadata.IndexTemplateMetaData.Builder serverTemplateBuilder =
org.elasticsearch.cluster.metadata.IndexTemplateMetaData.builder(clientITMD.name());
serverTemplateBuilder.patterns(clientITMD.patterns());
Iterator<AliasMetaData> aliases = clientITMD.aliases().valuesIt();
aliases.forEachRemaining((a)->serverTemplateBuilder.putAlias(a));
serverTemplateBuilder.settings(clientITMD.settings());
serverTemplateBuilder.order(clientITMD.order());
serverTemplateBuilder.version(clientITMD.version());
@ -219,7 +215,7 @@ public class GetIndexTemplatesResponseTests extends ESTestCase {
serverIndexTemplates.add(serverTemplateBuilder.build());
}
org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse serverResponse = new
org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse serverResponse = new
org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse(serverIndexTemplates);
serverResponse.toXContent(builder, ToXContent.EMPTY_PARAMS);
}

View File

@ -43,11 +43,12 @@ public class GetRollupCapsResponseTests extends RollupCapsResponseTestCase<GetRo
@Override
protected Predicate<String> randomFieldsExcludeFilter() {
return (field) ->
return (field) -> {
// base cannot have extra things in it
"".equals(field)
// the field list expects to be a nested object of a certain type
|| field.contains("fields");
return "".equals(field)
// the field list expects to be a nested object of a certain type
|| field.contains("fields");
};
}
@Override

View File

@ -44,10 +44,12 @@ public class GetRollupIndexCapsResponseTests extends RollupCapsResponseTestCase<
@Override
protected Predicate<String> randomFieldsExcludeFilter() {
return (field) ->
{
// base cannot have extra things in it
"".equals(field)
return "".equals(field)
// the field list expects to be a nested object of a certain type
|| field.contains("fields");
};
}
@Override

View File

@ -55,12 +55,13 @@ public class ClearRealmCacheResponseTests extends ESTestCase {
assertThat(response.getHeader().getFailures().get(0).getMessage(), containsString("reason=test"));
}
try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
"{" + nodesHeader + clusterName + "\"nodes\" : { " +
"\"id1\": { \"name\": \"a\"}, " +
"\"id2\": { \"name\": \"b\"}" +
"}}")) {
try (
XContentParser parser = JsonXContent.jsonXContent.createParser(
NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
"{" + nodesHeader + clusterName + "\"nodes\" : { \"id1\": { \"name\": \"a\"}, \"id2\": { \"name\": \"b\"}}}"
)
) {
ClearRealmCacheResponse response = ClearRealmCacheResponse.fromXContent(parser);
assertNotNull(response);

View File

@ -55,12 +55,13 @@ public class ClearRolesCacheResponseTests extends ESTestCase {
assertThat(response.getHeader().getFailures().get(0).getMessage(), containsString("reason=test"));
}
try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
"{" + nodesHeader + clusterName + "\"nodes\" : { " +
"\"id1\": { \"name\": \"a\"}, " +
"\"id2\": { \"name\": \"b\"}" +
"}}")) {
try (
XContentParser parser = JsonXContent.jsonXContent.createParser(
NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
"{" + nodesHeader + clusterName + "\"nodes\" : { \"id1\": { \"name\": \"a\"}, \"id2\": { \"name\": \"b\"}}}"
)
) {
ClearRolesCacheResponse response = ClearRolesCacheResponse.fromXContent(parser);
assertNotNull(response);

View File

@ -34,12 +34,10 @@ public class CreateTokenRequestTests extends ESTestCase {
assertThat(new String(request.getPassword()), equalTo("top secret password"));
assertThat(request.getScope(), nullValue());
assertThat(request.getRefreshToken(), nullValue());
assertThat(Strings.toString(request), equalTo("{" +
"\"grant_type\":\"password\"," +
"\"username\":\"jsmith\"," +
"\"password\":\"top secret password\"" +
"}"
));
assertThat(
Strings.toString(request),
equalTo("{\"grant_type\":\"password\",\"username\":\"jsmith\",\"password\":\"top secret password\"}")
);
}
public void testCreateTokenFromRefreshToken() {
@ -49,11 +47,10 @@ public class CreateTokenRequestTests extends ESTestCase {
assertThat(request.getScope(), nullValue());
assertThat(request.getUsername(), nullValue());
assertThat(request.getPassword(), nullValue());
assertThat(Strings.toString(request), equalTo("{" +
"\"grant_type\":\"refresh_token\"," +
"\"refresh_token\":\"9a7f41cf-9918-4d1f-bfaa-ad3f8f9f02b9\"" +
"}"
));
assertThat(
Strings.toString(request),
equalTo("{\"grant_type\":\"refresh_token\",\"refresh_token\":\"9a7f41cf-9918-4d1f-bfaa-ad3f8f9f02b9\"}")
);
}
public void testCreateTokenFromClientCredentials() {
@ -74,8 +71,10 @@ public class CreateTokenRequestTests extends ESTestCase {
assertThat(request.getPassword(), nullValue());
assertThat(request.getRefreshToken(), nullValue());
assertThat(new String(request.getKerberosTicket()), equalTo("top secret kerberos ticket"));
assertThat(Strings.toString(request), equalTo("{\"grant_type\":\"_kerberos\"," +
"\"kerberos_ticket\":\"top secret kerberos ticket\"}"));
assertThat(
Strings.toString(request),
equalTo("{\"grant_type\":\"_kerberos\",\"kerberos_ticket\":\"top secret kerberos ticket\"}")
);
}
public void testEqualsAndHashCode() {

View File

@ -32,10 +32,7 @@ public class InvalidateTokenRequestTests extends ESTestCase {
final InvalidateTokenRequest request = InvalidateTokenRequest.accessToken(token);
assertThat(request.getAccessToken(), equalTo(token));
assertThat(request.getRefreshToken(), nullValue());
assertThat(Strings.toString(request), equalTo("{" +
"\"token\":\"Tf01rrAymdUjxMY4VlG3gV3gsFFUWxVVPrztX+4uhe0=\"" +
"}"
));
assertThat(Strings.toString(request), equalTo("{\"token\":\"Tf01rrAymdUjxMY4VlG3gV3gsFFUWxVVPrztX+4uhe0=\"}"));
}
public void testInvalidateRefreshToken() {
@ -43,10 +40,7 @@ public class InvalidateTokenRequestTests extends ESTestCase {
final InvalidateTokenRequest request = InvalidateTokenRequest.refreshToken(token);
assertThat(request.getAccessToken(), nullValue());
assertThat(request.getRefreshToken(), equalTo(token));
assertThat(Strings.toString(request), equalTo("{" +
"\"refresh_token\":\"4rE0YPT/oHODS83TbTtYmuh8\"" +
"}"
));
assertThat(Strings.toString(request), equalTo("{\"refresh_token\":\"4rE0YPT/oHODS83TbTtYmuh8\"}"));
}
public void testInvalidateRealmTokens() {
@ -56,10 +50,7 @@ public class InvalidateTokenRequestTests extends ESTestCase {
assertThat(request.getRefreshToken(), nullValue());
assertThat(request.getRealmName(), equalTo(realmName));
assertThat(request.getUsername(), nullValue());
assertThat(Strings.toString(request), equalTo("{" +
"\"realm_name\":\"native\"" +
"}"
));
assertThat(Strings.toString(request), equalTo("{\"realm_name\":\"native\"}"));
}
public void testInvalidateUserTokens() {
@ -69,10 +60,7 @@ public class InvalidateTokenRequestTests extends ESTestCase {
assertThat(request.getRefreshToken(), nullValue());
assertThat(request.getRealmName(), nullValue());
assertThat(request.getUsername(), equalTo(username));
assertThat(Strings.toString(request), equalTo("{" +
"\"username\":\"user\"" +
"}"
));
assertThat(Strings.toString(request), equalTo("{\"username\":\"user\"}"));
}
public void testInvalidateUserTokensInRealm() {
@ -83,12 +71,7 @@ public class InvalidateTokenRequestTests extends ESTestCase {
assertThat(request.getRefreshToken(), nullValue());
assertThat(request.getRealmName(), equalTo(realmName));
assertThat(request.getUsername(), equalTo(username));
assertThat(Strings.toString(request), equalTo("{" +
"\"realm_name\":\"native\"," +
"\"username\":\"user\"" +
"}"
));
assertThat(Strings.toString(request), equalTo("{\"realm_name\":\"native\",\"username\":\"user\"}"));
}
public void testEqualsAndHashCode() {

View File

@ -34,6 +34,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
@ -132,16 +133,27 @@ public class PutRoleMappingRequestTests extends ESTestCase {
final XContentBuilder builder = XContentFactory.jsonBuilder();
putRoleMappingRequest.toXContent(builder, ToXContent.EMPTY_PARAMS);
final String output = Strings.toString(builder);
final String expected =
"{"+
"\"enabled\":" + enabled + "," +
"\"roles\":[\"superuser\"]," +
"\"role_templates\":[]," +
"\"rules\":{" +
"\"field\":{\"username\":[\"user\"]}" +
"}," +
"\"metadata\":{\"k1\":\"v1\"}" +
"}";
final String expected = String.format(
Locale.ROOT,
"{"
+ " \"enabled\": %s,"
+ " \"roles\": ["
+ " \"superuser\""
+ " ],"
+ "\"role_templates\":[],"
+ "\"rules\":{"
+ " \"field\": {"
+ " \"username\": ["
+ " \"user\""
+ " ]"
+ " }"
+ "},"
+ " \"metadata\": {"
+ " \"k1\": \"v1\""
+ " }"
+ "}",
enabled
).replaceAll("\\s+", "");
assertThat(output, equalTo(expected));
}
@ -164,19 +176,34 @@ public class PutRoleMappingRequestTests extends ESTestCase {
final XContentBuilder builder = XContentFactory.jsonBuilder();
putRoleMappingRequest.toXContent(builder, ToXContent.EMPTY_PARAMS);
final String output = Strings.toString(builder);
final String expected =
"{"+
"\"enabled\":" + enabled + "," +
"\"roles\":[]," +
"\"role_templates\":[" +
"{\"template\":\"{\\\"source\\\":\\\"_realm_{{realm.name}}\\\"}\",\"format\":\"string\"}," +
"{\"template\":\"{\\\"source\\\":\\\"some_role\\\"}\",\"format\":\"string\"}" +
"]," +
"\"rules\":{" +
"\"field\":{\"username\":[\"user\"]}" +
"}," +
"\"metadata\":{\"k1\":\"v1\"}" +
"}";
final String expected = String.format(
Locale.ROOT,
"{"
+ " \"enabled\": %s,"
+ "\"roles\":[],"
+ "\"role_templates\":["
+ " {"
+ " \"template\": \"{\\\"source\\\":\\\"_realm_{{realm.name}}\\\"}\","
+ " \"format\": \"string\""
+ " },"
+ " {"
+ " \"template\": \"{\\\"source\\\":\\\"some_role\\\"}\","
+ " \"format\": \"string\""
+ " }"
+ "],"
+ "\"rules\":{"
+ " \"field\": {"
+ " \"username\": ["
+ " \"user\""
+ " ]"
+ " }"
+ "},"
+ " \"metadata\": {"
+ " \"k1\": \"v1\""
+ " }"
+ "}",
enabled
).replaceAll("\\s+", "");
assertThat(output, equalTo(expected));
}

View File

@ -87,21 +87,25 @@ public class GroupConfigTests extends AbstractXContentTestCase<GroupConfig> {
public void testLenientParsing() throws IOException {
BytesArray json = new BytesArray(
"{ " +
"\"unknown-field\":\"foo\", " +
"\"destination-field\": {" +
"\"terms\": {" +
"\"field\": \"term-field\"" +
"}" +
"}," +
"\"unknown-field-2\":\"bar\"," +
"\"destination-field2\": {" +
"\"terms\": {" +
"\"field\": \"term-field2\"" +
"}" +
"}," +
"\"array-field\" : [1.0, 2.0]" +
"}");
"{"
+ " \"unknown-field\": \"foo\","
+ " \"destination-field\": {"
+ " \"terms\": {"
+ " \"field\": \"term-field\""
+ " }"
+ " },"
+ " \"unknown-field-2\": \"bar\","
+ " \"destination-field2\": {"
+ " \"terms\": {"
+ " \"field\": \"term-field2\""
+ " }"
+ " },"
+ " \"array-field\": ["
+ " 1,"
+ " 2"
+ " ]"
+ "}"
);
XContentParser parser = JsonXContent.jsonXContent
.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json.streamInput());
@ -116,20 +120,21 @@ public class GroupConfigTests extends AbstractXContentTestCase<GroupConfig> {
public void testLenientParsingUnknowGroupType() throws IOException {
BytesArray json = new BytesArray(
"{ " +
"\"destination-field1\": {" +
"\"newgroup\": {" +
"\"field1\": \"bar\"," +
"\"field2\": \"foo\"" +
"}" +
"}," +
"\"unknown-field\":\"bar\"," +
"\"destination-field2\": {" +
"\"terms\": {" +
"\"field\": \"term-field\"" +
"}" +
"}" +
"}");
"{"
+ " \"destination-field1\": {"
+ " \"newgroup\": {"
+ " \"field1\": \"bar\","
+ " \"field2\": \"foo\""
+ " }"
+ " },"
+ " \"unknown-field\": \"bar\","
+ " \"destination-field2\": {"
+ " \"terms\": {"
+ " \"field\": \"term-field\""
+ " }"
+ " }"
+ "}"
);
XContentParser parser = JsonXContent.jsonXContent
.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json.streamInput());