Iternal: Removed Payload.ActionResponse in favour of an extra constructor to Payload.XContent

Tests: Write more tests for AlertUtils

Closes elastic/elasticsearch#132

Original commit: elastic/x-pack-elasticsearch@b0e675b89c
This commit is contained in:
Martijn van Groningen 2015-03-04 12:36:24 +01:00
parent 50f4a1c0e3
commit e6445a9d2e
8 changed files with 102 additions and 28 deletions

View File

@ -67,19 +67,16 @@ public interface Payload extends ToXContent {
}
}
static class ActionResponse extends Simple {
public ActionResponse(org.elasticsearch.action.ActionResponse response) {
super(responseToData(response));
}
}
static class XContent extends Simple {
public XContent(XContentParser parser) {
super(mapOrdered(parser));
}
public XContent(ToXContent response) {
super(responseToData(response));
}
private static Map<String, Object> mapOrdered(XContentParser parser) {
try {
return parser.mapOrdered();

View File

@ -83,7 +83,7 @@ public class SearchInput extends Input<SearchInput.Result> {
}
return new Result(TYPE, new Payload.ActionResponse(response), request);
return new Result(TYPE, new Payload.XContent(response), request);
}
@Override

View File

@ -6,7 +6,6 @@
package org.elasticsearch.alerts.support;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.support.IndicesOptions;
@ -37,7 +36,7 @@ public final class AlertUtils {
private AlertUtils() {
}
public static Map<String, Object> responseToData(ActionResponse response) {
public static Map<String, Object> responseToData(ToXContent response) {
try {
XContentBuilder builder = jsonBuilder().startObject().value(response).endObject();
return XContentHelper.convertToMap(builder.bytes(), false).v2();
@ -101,11 +100,15 @@ public final class AlertUtils {
break;
case "open":
expandOpen = true;
expandClosed = false;
break;
case "closed":
expandOpen = false;
expandClosed = true;
break;
case "none":
expandOpen = false;
expandClosed = false;
break;
default:
throw new ElasticsearchIllegalArgumentException("Unexpected value [" + parser.text() + "]");

View File

@ -64,7 +64,7 @@ public class SearchTransform extends Transform<SearchTransform.Result> {
public Result apply(ExecutionContext ctx, Payload payload) throws IOException {
SearchRequest req = createRequest(request, ctx, payload);
SearchResponse resp = client.search(req).actionGet();
return new Result(TYPE, new Payload.ActionResponse(resp));
return new Result(TYPE, new Payload.XContent(resp));
}
@Override

View File

@ -78,7 +78,7 @@ public class ScriptConditionSearchTests extends AbstractAlertsSingleNodeTests {
ScriptCondition condition = new ScriptCondition(logger, scriptService, new Script("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5"));
ExecutionContext ctx = mockExecutionContext("_name", new Payload.ActionResponse(response));
ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
assertFalse(condition.execute(ctx).met());
client().prepareIndex("my-index", "my-type").setTimestamp("2005-01-01T00:40").setSource("{}").get();
@ -88,7 +88,7 @@ public class ScriptConditionSearchTests extends AbstractAlertsSingleNodeTests {
.addAggregation(AggregationBuilders.dateHistogram("rate").field("_timestamp").interval(DateHistogram.Interval.HOUR).order(Histogram.Order.COUNT_DESC))
.get();
ctx = mockExecutionContext("_name", new Payload.ActionResponse(response));
ctx = mockExecutionContext("_name", new Payload.XContent(response));
assertThat(condition.execute(ctx).met(), is(true));
}
@ -102,10 +102,10 @@ public class ScriptConditionSearchTests extends AbstractAlertsSingleNodeTests {
InternalSearchResponse internalSearchResponse = new InternalSearchResponse(new InternalSearchHits(new InternalSearchHit[]{hit}, 1l, 1f), null, null, null, false, null);
SearchResponse response = new SearchResponse(internalSearchResponse, "", 3, 3, 500l, new ShardSearchFailure[0]);
ExecutionContext ctx = mockExecutionContext("_alert_name", new Payload.ActionResponse(response));
ExecutionContext ctx = mockExecutionContext("_alert_name", new Payload.XContent(response));
assertThat(condition.execute(ctx).met(), is(true));
hit.score(2f);
when(ctx.payload()).thenReturn(new Payload.ActionResponse(response));
when(ctx.payload()).thenReturn(new Payload.XContent(response));
assertThat(condition.execute(ctx).met(), is(false));
}

View File

@ -7,7 +7,6 @@ package org.elasticsearch.alerts.condition.script;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.alerts.Alert;
import org.elasticsearch.alerts.AlertsSettingsException;
import org.elasticsearch.alerts.ExecutionContext;
import org.elasticsearch.alerts.Payload;
@ -15,7 +14,6 @@ import org.elasticsearch.alerts.condition.ConditionException;
import org.elasticsearch.alerts.support.Script;
import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy;
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.common.joda.time.DateTime;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
@ -39,7 +37,6 @@ import java.util.Set;
import static org.elasticsearch.alerts.test.AlertsTestUtils.mockExecutionContext;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.mockito.Mockito.*;
/**
*/
@ -63,7 +60,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase {
ScriptServiceProxy scriptService = getScriptServiceProxy(tp);
ScriptCondition condition = new ScriptCondition(logger, scriptService, new Script("ctx.payload.hits.total > 1"));
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]);
ExecutionContext ctx = mockExecutionContext("_name", new Payload.ActionResponse(response));
ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
assertFalse(condition.execute(ctx).met());
}
@ -73,7 +70,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase {
Script script = new Script("ctx.payload.hits.total > threshold", ScriptService.ScriptType.INLINE, ScriptService.DEFAULT_LANG, ImmutableMap.<String, Object>of("threshold", 1));
ScriptCondition condition = new ScriptCondition(logger, scriptService, script);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]);
ExecutionContext ctx = mockExecutionContext("_name", new Payload.ActionResponse(response));
ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
assertFalse(condition.execute(ctx).met());
}
@ -87,7 +84,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase {
ScriptCondition condition = conditionParser.parse(parser);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]);
ExecutionContext ctx = mockExecutionContext("_name", new Payload.ActionResponse(response));
ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
assertFalse(condition.execute(ctx).met());
@ -97,7 +94,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase {
parser.nextToken();
condition = conditionParser.parse(parser);
ctx = mockExecutionContext("_name", new Payload.ActionResponse(response));
ctx = mockExecutionContext("_name", new Payload.XContent(response));
assertTrue(condition.execute(ctx).met());
}

View File

@ -5,24 +5,35 @@
*/
package org.elasticsearch.alerts.support;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.alerts.input.search.SearchInput;
import org.elasticsearch.common.collect.ImmutableList;
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.common.joda.time.DateTime;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.elasticsearch.alerts.support.AlertUtils.flattenModel;
import static org.elasticsearch.alerts.support.AlertsDateUtils.formatDate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.*;
/**
*
*/
public class AlertUtilsTests {
public class AlertUtilsTests extends ElasticsearchTestCase {
@Test
public void testFlattenModel() throws Exception {
@ -46,4 +57,70 @@ public class AlertUtilsTests {
assertThat(result, hasEntry("c.1", "1000"));
assertThat(result, hasEntry("d", formatDate(now)));
}
@Test
public void testResponseToData() throws Exception {
final Map<String, Object> expected = new HashMap<>();
expected.put("key1", "val");
expected.put("key2", 1);
expected.put("key3", 1.4);
expected.put("key4", Arrays.asList("a", "b", "c"));
Map<String, Object> otherMap = new HashMap<>();
otherMap.putAll(expected);
expected.put("key5", otherMap);
ToXContent content = new ToXContent() {
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
for (Map.Entry<String, ?> entry : expected.entrySet()) {
builder.field(entry.getKey());
builder.value(entry.getValue());
}
return builder;
}
};
Map<String, Object> result = AlertUtils.responseToData(content);
assertThat(result, equalTo(expected));
}
@Test
public void testSerializeSearchRequest() throws Exception {
String[] randomIndices = generateRandomStringArray(5, 5);
SearchRequest expectedRequest = new SearchRequest(randomIndices);
expectedRequest.indicesOptions(IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), AlertUtils.DEFAULT_INDICES_OPTIONS));
expectedRequest.searchType(randomFrom(SearchType.values()));
SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery()).size(11);
XContentBuilder searchSourceJsonBuilder = jsonBuilder();
searchSourceBuilder.toXContent(searchSourceJsonBuilder, ToXContent.EMPTY_PARAMS);
String expectedSource = searchSourceJsonBuilder.string();
expectedRequest.source(expectedSource);
if (randomBoolean()) {
expectedRequest.templateName(randomAsciiOfLengthBetween(1, 5));
expectedRequest.templateType(randomFrom(ScriptService.ScriptType.values()));
if (randomBoolean()) {
Map<String, String> params = new HashMap<>();
int maxParams = randomIntBetween(1, 10);
for (int i = 0; i < maxParams; i++) {
params.put(randomAsciiOfLengthBetween(1, 5), randomAsciiOfLengthBetween(1, 5));
}
expectedRequest.templateParams(params);
}
}
XContentBuilder builder = jsonBuilder();
builder = AlertUtils.writeSearchRequest(expectedRequest, builder, ToXContent.EMPTY_PARAMS);
XContentParser parser = XContentHelper.createParser(builder.bytes());
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
SearchRequest result = AlertUtils.readSearchRequest(parser, SearchInput.DEFAULT_SEARCH_TYPE);
assertThat(result.indices(), arrayContainingInAnyOrder(expectedRequest.indices()));
assertThat(result.indicesOptions(), equalTo(expectedRequest.indicesOptions()));
assertThat(result.searchType(), equalTo(expectedRequest.searchType()));
assertThat(result.source().toUtf8(), equalTo(expectedSource));
assertThat(result.templateName(), equalTo(expectedRequest.templateName()));
assertThat(result.templateType(), equalTo(expectedRequest.templateType()));
assertThat(result.templateParams(), equalTo(expectedRequest.templateParams()));
}
}

View File

@ -60,7 +60,7 @@ public class SearchTransformTests extends AbstractAlertsSingleNodeTests {
assertThat(result.type(), is(SearchTransform.TYPE));
SearchResponse response = client().search(request).get();
Payload expectedPayload = new Payload.ActionResponse(response);
Payload expectedPayload = new Payload.XContent(response);
// we need to remove the "took" field from teh response as this is the only field
// that most likely be different between the two... we don't really care about this
@ -121,7 +121,7 @@ public class SearchTransformTests extends AbstractAlertsSingleNodeTests {
SearchResponse response = client().prepareSearch("idx").setQuery(
filteredQuery(matchAllQuery(), termFilter("value", "val_3")))
.get();
Payload expectedPayload = new Payload.ActionResponse(response);
Payload expectedPayload = new Payload.XContent(response);
// we need to remove the "took" field from teh response as this is the only field
// that most likely be different between the two... we don't really care about this