Remove most usages of 1-arg Script ctor (elastic/x-pack-elasticsearch#1207)

The one argument ctor for `Script` creates a script with the
default language but most usages of are for testing and either
don't care about the language or are for use with
`MockScriptEngine`. This replaces most usages of the one argument
ctor on `Script` with calls to `ESTestCase#mockScript` to make
it clear that the tests don't need the default scripting language.

Original commit: elastic/x-pack-elasticsearch@c1d05b7357
This commit is contained in:
Nik Everett 2017-04-27 11:35:42 -04:00 committed by GitHub
parent aa7d94ec44
commit 677ea404f7
14 changed files with 80 additions and 73 deletions

View File

@ -6,11 +6,14 @@
package org.elasticsearch.xpack.watcher.transform;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.transform.chain.ChainTransform;
import org.elasticsearch.xpack.watcher.transform.script.ScriptTransform;
import org.elasticsearch.xpack.watcher.transform.search.SearchTransform;
import static java.util.Collections.emptyMap;
public final class TransformBuilders {
private TransformBuilders() {
@ -21,7 +24,7 @@ public final class TransformBuilders {
}
public static ScriptTransform.Builder scriptTransform(String script) {
return scriptTransform(new Script(script));
return scriptTransform(new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, script, emptyMap()));
}
public static ScriptTransform.Builder scriptTransform(Script script) {

View File

@ -6,11 +6,11 @@
package org.elasticsearch.xpack.ml.datafeed;
import com.carrotsearch.randomizedtesting.generators.CodepointSetGenerator;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
@ -55,7 +55,7 @@ public class DatafeedConfigTests extends AbstractSerializingTestCase<DatafeedCon
int scriptsSize = randomInt(3);
List<SearchSourceBuilder.ScriptField> scriptFields = new ArrayList<>(scriptsSize);
for (int scriptIndex = 0; scriptIndex < scriptsSize; scriptIndex++) {
scriptFields.add(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), new Script(randomAlphaOfLength(10)),
scriptFields.add(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), mockScript(randomAlphaOfLength(10)),
randomBoolean()));
}
builder.setScriptFields(scriptFields);
@ -192,7 +192,7 @@ public class DatafeedConfigTests extends AbstractSerializingTestCase<DatafeedCon
datafeed.setIndexes(Arrays.asList("my_index"));
datafeed.setTypes(Arrays.asList("my_type"));
datafeed.setScriptFields(Arrays.asList(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10),
new Script(randomAlphaOfLength(10)), randomBoolean())));
mockScript(randomAlphaOfLength(10)), randomBoolean())));
datafeed.setAggregations(new AggregatorFactories.Builder().addAggregator(AggregationBuilders.avg("foo")));
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> datafeed.build());

View File

@ -9,7 +9,6 @@ import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.builder.SearchSourceBuilder;
@ -53,7 +52,7 @@ public class DatafeedUpdateTests extends AbstractSerializingTestCase<DatafeedUpd
int scriptsSize = randomInt(3);
List<SearchSourceBuilder.ScriptField> scriptFields = new ArrayList<>(scriptsSize);
for (int scriptIndex = 0; scriptIndex < scriptsSize; scriptIndex++) {
scriptFields.add(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), new Script(randomAlphaOfLength(10)),
scriptFields.add(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), mockScript(randomAlphaOfLength(10)),
randomBoolean()));
}
builder.setScriptFields(scriptFields);
@ -126,7 +125,7 @@ public class DatafeedUpdateTests extends AbstractSerializingTestCase<DatafeedUpd
update.setQueryDelay(TimeValue.timeValueSeconds(42));
update.setFrequency(TimeValue.timeValueSeconds(142));
update.setQuery(QueryBuilders.termQuery("a", "b"));
update.setScriptFields(Arrays.asList(new SearchSourceBuilder.ScriptField("a", new Script("b"), false)));
update.setScriptFields(Arrays.asList(new SearchSourceBuilder.ScriptField("a", mockScript("b"), false)));
update.setScrollSize(8000);
update.setSource(true);
update.setChunkingConfig(ChunkingConfig.newManual(TimeValue.timeValueHours(1)));
@ -141,7 +140,7 @@ public class DatafeedUpdateTests extends AbstractSerializingTestCase<DatafeedUpd
assertThat(updatedDatafeed.getQuery(), equalTo(QueryBuilders.termQuery("a", "b")));
assertThat(updatedDatafeed.hasAggregations(), is(false));
assertThat(updatedDatafeed.getScriptFields(),
equalTo(Arrays.asList(new SearchSourceBuilder.ScriptField("a", new Script("b"), false))));
equalTo(Arrays.asList(new SearchSourceBuilder.ScriptField("a", mockScript("b"), false))));
assertThat(updatedDatafeed.getScrollSize(), equalTo(8000));
assertThat(updatedDatafeed.isSource(), is(true));
assertThat(updatedDatafeed.getChunkingConfig(), equalTo(ChunkingConfig.newManual(TimeValue.timeValueHours(1))));

View File

@ -12,12 +12,13 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.script.Script;
import org.junit.Before;
import java.io.BufferedReader;
@ -34,6 +35,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.util.Collections.emptyMap;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@ -278,9 +280,9 @@ public class ScrollDataExtractorTests extends ESTestCase {
public void testDomainSplitScriptField() throws IOException {
SearchSourceBuilder.ScriptField withoutSplit = new SearchSourceBuilder.ScriptField(
"script1", new Script("return 1+1;"), false);
"script1", mockScript("return 1+1;"), false);
SearchSourceBuilder.ScriptField withSplit = new SearchSourceBuilder.ScriptField(
"script2", new Script("return domainSplit('foo.com', params);"), false);
"script2", new Script(ScriptType.INLINE, "painless", "return domainSplit('foo.com', params);", emptyMap()), false);
List<SearchSourceBuilder.ScriptField> sFields = Arrays.asList(withoutSplit, withSplit);
ScrollDataExtractorContext context = new ScrollDataExtractorContext(jobId, extractedFields, indexes,
@ -317,7 +319,7 @@ public class ScrollDataExtractorTests extends ESTestCase {
assertThat(searchRequest, containsString("\"stored_fields\":\"_none_\""));
// Check for the scripts
assertThat(searchRequest, containsString("{\"script\":{\"inline\":\"return 1 + 1;\",\"lang\":\"painless\"}"
assertThat(searchRequest, containsString("{\"script\":{\"inline\":\"return 1 + 1;\",\"lang\":\"mockscript\"}"
.replaceAll("\\s", "")));
assertThat(searchRequest, containsString("List domainSplit(String host, Map params)".replaceAll("\\s", "")));
assertThat(searchRequest, containsString("String replaceDots(String input) {".replaceAll("\\s", "")));

View File

@ -8,7 +8,6 @@ package org.elasticsearch.xpack.watcher.condition;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.test.ESTestCase;
@ -53,7 +52,7 @@ public class AlwaysConditionTests extends ESTestCase {
String type = randomFrom(ScriptCondition.TYPE, AlwaysCondition.TYPE, CompareCondition.TYPE, ArrayCompareCondition.TYPE);
switch (type) {
case ScriptCondition.TYPE:
return new ScriptCondition(new Script("_script"), scriptService);
return new ScriptCondition(mockScript("_script"), scriptService);
case CompareCondition.TYPE:
return new CompareCondition("_path", randomFrom(CompareCondition.Op.values()), randomFrom(5, "3"),
Clock.systemUTC());

View File

@ -12,14 +12,13 @@ import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.index.Index;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
@ -65,11 +64,6 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa
return scripts;
}
@Override
public String pluginScriptLang() {
return WATCHER_LANG;
}
}
public void testExecuteWithAggs() throws Exception {
@ -86,7 +80,7 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa
ScriptService scriptService = internalCluster().getInstance(ScriptService.class);
ScriptCondition condition = new ScriptCondition(
new Script("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5"),
mockScript("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5"),
scriptService);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
@ -106,7 +100,7 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa
public void testExecuteAccessHits() throws Exception {
ScriptService scriptService = internalCluster().getInstance(ScriptService.class);
ScriptCondition condition = new ScriptCondition(
new Script("ctx.payload.hits?.hits[0]?._score == 1.0"), scriptService);
mockScript("ctx.payload.hits?.hits[0]?._score == 1.0"), scriptService);
SearchHit hit = new SearchHit(0, "1", new Text("type"), null);
hit.score(1f);
hit.shard(new SearchShardTarget("a", new Index("a", "testUUID"), 0));

View File

@ -87,7 +87,7 @@ public class ScriptConditionTests extends ESTestCase {
return total > threshold;
});
ScriptEngineService engine = new MockScriptEngine(AbstractWatcherIntegrationTestCase.WATCHER_LANG, scripts);
ScriptEngineService engine = new MockScriptEngine(MockScriptEngine.NAME, scripts);
ScriptEngineRegistry registry = new ScriptEngineRegistry(singleton(engine));
ScriptContextRegistry contextRegistry = new ScriptContextRegistry(singleton(new ScriptContext.Plugin("xpack", "watch")));
@ -106,15 +106,14 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testExecute() throws Exception {
ScriptCondition condition = new ScriptCondition(new Script("ctx.payload.hits.total > 1"), scriptService);
ScriptCondition condition = new ScriptCondition(mockScript("ctx.payload.hits.total > 1"), scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
assertFalse(condition.execute(ctx).met());
}
public void testExecuteMergedParams() throws Exception {
Script script = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG,
"ctx.payload.hits.total > threshold", singletonMap("threshold", 1));
Script script = new Script(ScriptType.INLINE, "mockscript", "ctx.payload.hits.total > threshold", singletonMap("threshold", 1));
ScriptCondition executable = new ScriptCondition(script, scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
@ -123,7 +122,7 @@ public class ScriptConditionTests extends ESTestCase {
public void testParserValid() throws Exception {
XContentBuilder builder = createConditionContent("ctx.payload.hits.total > 1", null, ScriptType.INLINE);
XContentBuilder builder = createConditionContent("ctx.payload.hits.total > 1", "mockscript", ScriptType.INLINE);
XContentParser parser = createParser(builder);
parser.nextToken();
@ -135,7 +134,7 @@ public class ScriptConditionTests extends ESTestCase {
assertFalse(executable.execute(ctx).met());
builder = createConditionContent("return true", null, ScriptType.INLINE);
builder = createConditionContent("return true", "mockscript", ScriptType.INLINE);
parser = createParser(builder);
parser.nextToken();
executable = ScriptCondition.parse(scriptService, "_watch", parser);
@ -176,7 +175,7 @@ public class ScriptConditionTests extends ESTestCase {
expectedException = GeneralScriptException.class;
script = "foo = = 1";
}
XContentBuilder builder = createConditionContent(script, "painless", scriptType);
XContentBuilder builder = createConditionContent(script, "mockscript", scriptType);
XContentParser parser = createParser(builder);
parser.nextToken();
@ -196,7 +195,7 @@ public class ScriptConditionTests extends ESTestCase {
public void testScriptConditionThrowException() throws Exception {
ScriptCondition condition = new ScriptCondition(
new Script("null.foo"), scriptService);
mockScript("null.foo"), scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
ScriptException exception = expectThrows(ScriptException.class, () -> condition.execute(ctx));
@ -204,7 +203,7 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testScriptConditionReturnObjectThrowsException() throws Exception {
ScriptCondition condition = new ScriptCondition(new Script("return new Object()"), scriptService);
ScriptCondition condition = new ScriptCondition(mockScript("return new Object()"), scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
Exception exception = expectThrows(IllegalStateException.class, () -> condition.execute(ctx));
@ -213,7 +212,7 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testScriptConditionAccessCtx() throws Exception {
ScriptCondition condition = new ScriptCondition(new Script("ctx.trigger.scheduled_time.getMillis() < new Date().time"),
ScriptCondition condition = new ScriptCondition(mockScript("ctx.trigger.scheduled_time.getMillis() < new Date().time"),
scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new DateTime(DateTimeZone.UTC), new Payload.XContent(response));

View File

@ -14,7 +14,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.script.Script;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.common.http.HttpRequestTemplate;
import org.elasticsearch.xpack.common.http.auth.basic.BasicAuth;
@ -153,7 +152,7 @@ public class ChainInputTests extends ESTestCase {
watchBuilder()
.trigger(schedule(interval("5s")))
.input(chainedInputBuilder)
.condition(new ScriptCondition(new Script("ctx.payload.hits.total == 1")))
.condition(new ScriptCondition(mockScript("ctx.payload.hits.total == 1")))
.addAction("_id", loggingAction("watch [{{ctx.watch_id}}] matched"))
.toXContent(builder, ToXContent.EMPTY_PARAMS);

View File

@ -13,6 +13,7 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.node.MockNode;
import org.elasticsearch.node.Node;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.common.http.HttpRequestTemplate;
@ -25,7 +26,6 @@ import org.elasticsearch.xpack.watcher.trigger.ScheduleTriggerEngineMock;
import org.elasticsearch.xpack.watcher.trigger.TriggerEngine;
import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleRegistry;
import javax.security.auth.DestroyFailedException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStoreException;
@ -35,6 +35,9 @@ import java.security.cert.CertificateException;
import java.time.Clock;
import java.util.Arrays;
import javax.security.auth.DestroyFailedException;
import static java.util.Collections.emptyMap;
import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.indexAction;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.httpInput;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.searchInput;
@ -88,7 +91,11 @@ public class WatcherExecutorServiceBenchmark {
PutWatchRequest putAlertRequest = new PutWatchRequest(name, new WatchSourceBuilder()
.trigger(schedule(interval("5s")))
.input(searchInput(templateRequest(new SearchSourceBuilder(), "test")))
.condition(new ScriptCondition(new Script("ctx.payload.hits.total > 0"))));
.condition(new ScriptCondition(new Script(
ScriptType.INLINE,
Script.DEFAULT_SCRIPT_LANG,
"ctx.payload.hits.total > 0",
emptyMap()))));
putAlertRequest.setId(name);
watcherClient.putWatch(putAlertRequest).actionGet();
}
@ -130,7 +137,7 @@ public class WatcherExecutorServiceBenchmark {
.trigger(schedule(interval("5s")))
.input(searchInput(templateRequest(new SearchSourceBuilder(), "test"))
.extractKeys("hits.total"))
.condition(new ScriptCondition(new Script("1 == 1")))
.condition(new ScriptCondition(new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, "1 == 1", emptyMap())))
.addAction("_id", indexAction("index", "type")));
putAlertRequest.setId(name);
watcherClient.putWatch(putAlertRequest).actionGet();
@ -174,7 +181,11 @@ public class WatcherExecutorServiceBenchmark {
PutWatchRequest putAlertRequest = new PutWatchRequest(name, new WatchSourceBuilder()
.trigger(schedule(interval("5s")))
.input(httpInput(HttpRequestTemplate.builder("localhost", 9200)))
.condition(new ScriptCondition(new Script("ctx.payload.tagline == \"You Know, for Search\""))));
.condition(new ScriptCondition(new Script(
ScriptType.INLINE,
Script.DEFAULT_SCRIPT_LANG,
"ctx.payload.tagline == \"You Know, for Search\"",
emptyMap()))));
putAlertRequest.setId(name);
watcherClient.putWatch(putAlertRequest).actionGet();
}

View File

@ -21,11 +21,13 @@ import org.elasticsearch.monitor.jvm.JvmInfo;
import org.elasticsearch.node.MockNode;
import org.elasticsearch.node.Node;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.percentiles.Percentiles;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.threadpool.ThreadPoolStats;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.watcher.WatcherState;
import org.elasticsearch.xpack.watcher.actions.ActionBuilders;
import org.elasticsearch.xpack.watcher.actions.logging.LoggingLevel;
@ -34,7 +36,6 @@ import org.elasticsearch.xpack.watcher.client.WatcherClient;
import org.elasticsearch.xpack.watcher.condition.ScriptCondition;
import org.elasticsearch.xpack.watcher.history.HistoryStore;
import org.elasticsearch.xpack.watcher.watch.Watch;
import org.elasticsearch.xpack.XPackPlugin;
import java.io.IOException;
import java.time.Clock;
@ -44,6 +45,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.util.Collections.emptyMap;
import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram;
import static org.elasticsearch.search.aggregations.AggregationBuilders.percentiles;
import static org.elasticsearch.search.aggregations.AggregationBuilders.terms;
@ -110,7 +112,11 @@ public class WatcherScheduleEngineBenchmark {
.setSource(new WatchSourceBuilder()
.trigger(schedule(interval(interval + "s")))
.input(searchInput(templateRequest(new SearchSourceBuilder(), "test")))
.condition(new ScriptCondition(new Script("ctx.payload.hits.total > 0")))
.condition(new ScriptCondition(new Script(
ScriptType.INLINE,
Script.DEFAULT_SCRIPT_LANG,
"ctx.payload.hits.total > 0",
emptyMap())))
.addAction("logging", ActionBuilders.loggingAction("test").setLevel(LoggingLevel.TRACE))
.buildAsBytes(XContentType.JSON), XContentType.JSON
).get();
@ -182,8 +188,11 @@ public class WatcherScheduleEngineBenchmark {
}
}
client.admin().indices().prepareRefresh(HistoryStore.INDEX_PREFIX_WITH_TEMPLATE + "*").get();
Script script = new Script("doc['trigger_event.schedule.triggered_time'].value - doc['trigger_event.schedule" +
".scheduled_time'].value");
Script script = new Script(
ScriptType.INLINE,
Script.DEFAULT_SCRIPT_LANG,
"doc['trigger_event.schedule.triggered_time'].value - doc['trigger_event.schedule.scheduled_time'].value",
emptyMap());
SearchResponse searchResponse = client.prepareSearch(HistoryStore.INDEX_PREFIX_WITH_TEMPLATE + "*")
.setQuery(QueryBuilders.rangeQuery("trigger_event.schedule.scheduled_time").gte(startTime).lte(endTime))
.addAggregation(terms("state").field("state"))

View File

@ -9,7 +9,6 @@ import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.xpack.watcher.client.WatcherClient;
import org.elasticsearch.xpack.watcher.condition.ScriptCondition;
import org.elasticsearch.xpack.watcher.support.xcontent.ObjectPath;
@ -107,11 +106,6 @@ public class ExecutionVarsIntegrationTests extends AbstractWatcherIntegrationTes
return scripts;
}
@Override
public String pluginScriptLang() {
return WATCHER_LANG;
}
}
public void testVars() throws Exception {
@ -121,15 +115,16 @@ public class ExecutionVarsIntegrationTests extends AbstractWatcherIntegrationTes
.trigger(schedule(cron("0/1 * * * * ?")))
.input(simpleInput("value", 5))
.condition(new ScriptCondition(
new Script("ctx.vars.condition_value = ctx.payload.value + 5; return ctx.vars.condition_value > 5;")))
.transform(scriptTransform("ctx.vars.watch_transform_value = ctx.vars.condition_value + 5; return ctx.payload;"))
mockScript("ctx.vars.condition_value = ctx.payload.value + 5; return ctx.vars.condition_value > 5;")))
.transform(
scriptTransform(mockScript("ctx.vars.watch_transform_value = ctx.vars.condition_value + 5; return ctx.payload;")))
.addAction(
"a1",
scriptTransform("transform a1"),
scriptTransform(mockScript("transform a1")),
loggingAction("_text"))
.addAction(
"a2",
scriptTransform("transform a2"),
scriptTransform(mockScript("transform a2")),
loggingAction("_text")))
.get();
@ -184,15 +179,16 @@ public class ExecutionVarsIntegrationTests extends AbstractWatcherIntegrationTes
.trigger(schedule(cron("0/1 * * * * ? 2020")))
.input(simpleInput("value", 5))
.condition(new ScriptCondition(
new Script("ctx.vars.condition_value = ctx.payload.value + 5; return ctx.vars.condition_value > 5;")))
.transform(scriptTransform("ctx.vars.watch_transform_value = ctx.vars.condition_value + 5; return ctx.payload;"))
mockScript("ctx.vars.condition_value = ctx.payload.value + 5; return ctx.vars.condition_value > 5;")))
.transform(
scriptTransform(mockScript("ctx.vars.watch_transform_value = ctx.vars.condition_value + 5; return ctx.payload;")))
.addAction(
"a1",
scriptTransform("transform a1"),
scriptTransform(mockScript("transform a1")),
loggingAction("_text"))
.addAction(
"a2",
scriptTransform("transform a2"),
scriptTransform(mockScript("transform a2")),
loggingAction("_text")))
.get();

View File

@ -78,7 +78,7 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
// When using the MockScriptPlugin we can map File scripts to inline scripts:
// the name of the file script is used in test method while the source of the file script
// must match a predefined script from CustomScriptPlugin.pluginScripts() method
Files.write(scripts.resolve("my-script.painless"), "['key3' : ctx.payload.key1 + ctx.payload.key2]".getBytes("UTF-8"));
Files.write(scripts.resolve("my-script.mockscript"), "['key3' : ctx.payload.key1 + ctx.payload.key2]".getBytes("UTF-8"));
} catch (IOException ex) {
throw new RuntimeException("Failed to create scripts", ex);
}
@ -111,29 +111,24 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
return scripts;
}
@Override
public String pluginScriptLang() {
return WATCHER_LANG;
}
}
public void testScriptTransform() throws Exception {
final Script script;
if (randomBoolean()) {
logger.info("testing script transform with an inline script");
script = new Script("['key3' : ctx.payload.key1 + ctx.payload.key2]");
script = mockScript("['key3' : ctx.payload.key1 + ctx.payload.key2]");
} else if (randomBoolean()) {
logger.info("testing script transform with an indexed script");
assertAcked(client().admin().cluster().preparePutStoredScript()
.setId("my-script")
.setLang("painless")
.setLang("mockscript")
.setContent(new BytesArray("{\"script\" : \"['key3' : ctx.payload.key1 + ctx.payload.key2]\"}"), XContentType.JSON)
.get());
script = new Script(ScriptType.STORED, "painless", "my-script", Collections.emptyMap());
script = new Script(ScriptType.STORED, "mockscript", "my-script", Collections.emptyMap());
} else {
logger.info("testing script transform with a file script");
script = new Script(ScriptType.FILE, "painless", "my-script", Collections.emptyMap());
script = new Script(ScriptType.FILE, "mockscript", "my-script", Collections.emptyMap());
}
// put a watch that has watch level transform:
@ -227,8 +222,8 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
}
public void testChainTransform() throws Exception {
Script script1 = new Script("['key3' : ctx.payload.key1 + ctx.payload.key2]");
Script script2 = new Script("['key4' : ctx.payload.key3 + 10]");
Script script1 = mockScript("['key3' : ctx.payload.key1 + ctx.payload.key2]");
Script script2 = mockScript("['key4' : ctx.payload.key3 + 10]");
// put a watch that has watch level transform:
PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id1")

View File

@ -28,6 +28,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
@ -161,7 +162,7 @@ public class ScriptTransformTests extends ESTestCase {
XContentParser parser = createParser(builder);
parser.nextToken();
ExecutableScriptTransform transform = new ScriptTransformFactory(Settings.EMPTY, service).parseExecutable("_id", parser);
assertThat(transform.transform().getScript(), equalTo(new Script("_script")));
assertEquals(new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, "_script", emptyMap()), transform.transform().getScript());
}
public void testScriptConditionParserBadScript() throws Exception {

View File

@ -433,7 +433,7 @@ public class WatchTests extends ESTestCase {
DateTimeZone timeZone = randomBoolean() ? DateTimeZone.UTC : null;
switch (type) {
case ScriptTransform.TYPE:
return new ExecutableScriptTransform(new ScriptTransform(new Script("_script")), logger, scriptService);
return new ExecutableScriptTransform(new ScriptTransform(mockScript("_script")), logger, scriptService);
case SearchTransform.TYPE:
SearchTransform transform = new SearchTransform(
templateRequest(searchSource()), timeout, timeZone);
@ -441,14 +441,14 @@ public class WatchTests extends ESTestCase {
default: // chain
SearchTransform searchTransform = new SearchTransform(
templateRequest(searchSource()), timeout, timeZone);
ScriptTransform scriptTransform = new ScriptTransform(new Script("_script"));
ScriptTransform scriptTransform = new ScriptTransform(mockScript("_script"));
ChainTransform chainTransform = new ChainTransform(Arrays.asList(searchTransform, scriptTransform));
return new ExecutableChainTransform(chainTransform, logger, Arrays.<ExecutableTransform>asList(
new ExecutableSearchTransform(new SearchTransform(
templateRequest(searchSource()), timeout, timeZone),
logger, client, searchTemplateService, null),
new ExecutableScriptTransform(new ScriptTransform(new Script("_script")),
new ExecutableScriptTransform(new ScriptTransform(mockScript("_script")),
logger, scriptService)));
}
}