use of org.opensearch.script.ScriptException in project OpenSearch by opensearch-project.
the class RegexTests method testBadRegexPattern.
public void testBadRegexPattern() {
ScriptException e = expectThrows(ScriptException.class, () -> {
// Invalid unicode
exec("/\\ujjjj/");
});
assertEquals("invalid regular expression: could not compile regex constant [\\ujjjj] with flags []", e.getCause().getMessage());
// And make sure the location of the error points to the offset inside the pattern
assertScriptStack(e, "/\\ujjjj/", " ^---- HERE");
}
use of org.opensearch.script.ScriptException in project OpenSearch by opensearch-project.
the class WhenThingsGoWrongTests method testScriptStack.
/**
* Test that the scriptStack looks good. By implication this tests that we build proper "line numbers" in stack trace. These line
* numbers are really 1 based character numbers.
*/
public void testScriptStack() {
for (String type : new String[] { "String", "def " }) {
// trigger NPE at line 1 of the script
ScriptException exception = expectThrows(ScriptException.class, () -> {
exec(type + " x = null; boolean y = x.isEmpty();\n" + "return y;");
});
// null deref at x.isEmpty(), the '.' is offset 30
assertScriptElementColumn(30, exception);
assertScriptStack(exception, "y = x.isEmpty();\n", " ^---- HERE");
assertThat(exception.getCause(), instanceOf(NullPointerException.class));
// trigger NPE at line 2 of the script
exception = expectThrows(ScriptException.class, () -> {
exec(type + " x = null;\n" + "return x.isEmpty();");
});
// null deref at x.isEmpty(), the '.' is offset 25
assertScriptElementColumn(25, exception);
assertScriptStack(exception, "return x.isEmpty();", " ^---- HERE");
assertThat(exception.getCause(), instanceOf(NullPointerException.class));
// trigger NPE at line 3 of the script
exception = expectThrows(ScriptException.class, () -> {
exec(type + " x = null;\n" + type + " y = x;\n" + "return y.isEmpty();");
});
// null deref at y.isEmpty(), the '.' is offset 39
assertScriptElementColumn(39, exception);
assertScriptStack(exception, "return y.isEmpty();", " ^---- HERE");
assertThat(exception.getCause(), instanceOf(NullPointerException.class));
// trigger NPE at line 4 in script (inside conditional)
exception = expectThrows(ScriptException.class, () -> {
exec(type + " x = null;\n" + "boolean y = false;\n" + "if (!y) {\n" + " y = x.isEmpty();\n" + "}\n" + "return y;");
});
// null deref at x.isEmpty(), the '.' is offset 53
assertScriptElementColumn(53, exception);
assertScriptStack(exception, "y = x.isEmpty();\n}\n", " ^---- HERE");
assertThat(exception.getCause(), instanceOf(NullPointerException.class));
}
}
use of org.opensearch.script.ScriptException in project OpenSearch by opensearch-project.
the class OpenSearchExceptionTests method testFailureToAndFromXContentWithDetails.
public void testFailureToAndFromXContentWithDetails() throws IOException {
final XContent xContent = randomFrom(XContentType.values()).xContent();
Exception failure;
Throwable failureCause;
OpenSearchException expected;
OpenSearchException expectedCause;
OpenSearchException suppressed;
switch(randomIntBetween(0, 6)) {
case // Simple opensearch exception without cause
0:
failure = new NoNodeAvailableException("A");
expected = new OpenSearchException("OpenSearch exception [type=no_node_available_exception, reason=A]");
expected.addSuppressed(new OpenSearchException("OpenSearch exception [type=no_node_available_exception, reason=A]"));
break;
case // Simple opensearch exception with headers (other metadata of type number are not parsed)
1:
failure = new ParsingException(3, 2, "B", null);
((OpenSearchException) failure).addHeader("header_name", "0", "1");
expected = new OpenSearchException("OpenSearch exception [type=parsing_exception, reason=B]");
expected.addHeader("header_name", "0", "1");
suppressed = new OpenSearchException("OpenSearch exception [type=parsing_exception, reason=B]");
suppressed.addHeader("header_name", "0", "1");
expected.addSuppressed(suppressed);
break;
case // OpenSearch exception with a cause, headers and parsable metadata
2:
failureCause = new NullPointerException("var is null");
failure = new ScriptException("C", failureCause, singletonList("stack"), "test", "painless");
((OpenSearchException) failure).addHeader("script_name", "my_script");
expectedCause = new OpenSearchException("OpenSearch exception [type=null_pointer_exception, reason=var is null]");
expected = new OpenSearchException("OpenSearch exception [type=script_exception, reason=C]", expectedCause);
expected.addHeader("script_name", "my_script");
expected.addMetadata("opensearch.lang", "painless");
expected.addMetadata("opensearch.script", "test");
expected.addMetadata("opensearch.script_stack", "stack");
suppressed = new OpenSearchException("OpenSearch exception [type=script_exception, reason=C]");
suppressed.addHeader("script_name", "my_script");
suppressed.addMetadata("opensearch.lang", "painless");
suppressed.addMetadata("opensearch.script", "test");
suppressed.addMetadata("opensearch.script_stack", "stack");
expected.addSuppressed(suppressed);
break;
case // JDK exception without cause
3:
failure = new IllegalStateException("D");
expected = new OpenSearchException("OpenSearch exception [type=illegal_state_exception, reason=D]");
suppressed = new OpenSearchException("OpenSearch exception [type=illegal_state_exception, reason=D]");
expected.addSuppressed(suppressed);
break;
case // JDK exception with cause
4:
failureCause = new RoutingMissingException("idx", "id");
failure = new RuntimeException("E", failureCause);
expectedCause = new OpenSearchException("OpenSearch exception [type=routing_missing_exception, " + "reason=routing is required for [idx]/[id]]");
expectedCause.addMetadata("opensearch.index", "idx");
expectedCause.addMetadata("opensearch.index_uuid", "_na_");
expected = new OpenSearchException("OpenSearch exception [type=runtime_exception, reason=E]", expectedCause);
suppressed = new OpenSearchException("OpenSearch exception [type=runtime_exception, reason=E]");
expected.addSuppressed(suppressed);
break;
case // Wrapped exception with cause
5:
failureCause = new FileAlreadyExistsException("File exists");
failure = new BroadcastShardOperationFailedException(new ShardId("_index", "_uuid", 5), "F", failureCause);
expected = new OpenSearchException("OpenSearch exception [type=file_already_exists_exception, reason=File exists]");
suppressed = new OpenSearchException("OpenSearch exception [type=file_already_exists_exception, reason=File exists]");
expected.addSuppressed(suppressed);
break;
case // SearchPhaseExecutionException with cause and multiple failures
6:
DiscoveryNode node = new DiscoveryNode("node_g", buildNewFakeTransportAddress(), Version.CURRENT);
failureCause = new NodeClosedException(node);
failureCause = new NoShardAvailableActionException(new ShardId("_index_g", "_uuid_g", 6), "node_g", failureCause);
ShardSearchFailure[] shardFailures = new ShardSearchFailure[] { new ShardSearchFailure(new ParsingException(0, 0, "Parsing g", null), new SearchShardTarget("node_g", new ShardId(new Index("_index_g", "_uuid_g"), 61), null, OriginalIndices.NONE)), new ShardSearchFailure(new RepositoryException("repository_g", "Repo"), new SearchShardTarget("node_g", new ShardId(new Index("_index_g", "_uuid_g"), 62), null, OriginalIndices.NONE)), new ShardSearchFailure(new SearchContextMissingException(new ShardSearchContextId(UUIDs.randomBase64UUID(), 0L)), null) };
failure = new SearchPhaseExecutionException("phase_g", "G", failureCause, shardFailures);
expectedCause = new OpenSearchException("OpenSearch exception [type=node_closed_exception, " + "reason=node closed " + node + "]");
expectedCause = new OpenSearchException("OpenSearch exception [type=no_shard_available_action_exception, " + "reason=node_g]", expectedCause);
expectedCause.addMetadata("opensearch.index", "_index_g");
expectedCause.addMetadata("opensearch.index_uuid", "_uuid_g");
expectedCause.addMetadata("opensearch.shard", "6");
expected = new OpenSearchException("OpenSearch exception [type=search_phase_execution_exception, " + "reason=G]", expectedCause);
expected.addMetadata("opensearch.phase", "phase_g");
expected.addSuppressed(new OpenSearchException("OpenSearch exception [type=parsing_exception, reason=Parsing g]"));
expected.addSuppressed(new OpenSearchException("OpenSearch exception [type=repository_exception, " + "reason=[repository_g] Repo]"));
expected.addSuppressed(new OpenSearchException("OpenSearch exception [type=search_context_missing_exception, " + "reason=No search context found for id [0]]"));
break;
default:
throw new UnsupportedOperationException("Failed to generate randomized failure");
}
Exception finalFailure = failure;
BytesReference failureBytes = toShuffledXContent((builder, params) -> {
OpenSearchException.generateFailureXContent(builder, params, finalFailure, true);
return builder;
}, xContent.type(), ToXContent.EMPTY_PARAMS, randomBoolean());
try (XContentParser parser = createParser(xContent, failureBytes)) {
failureBytes = BytesReference.bytes(shuffleXContent(parser, randomBoolean()));
}
OpenSearchException parsedFailure;
try (XContentParser parser = createParser(xContent, failureBytes)) {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
parsedFailure = OpenSearchException.failureFromXContent(parser);
assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken());
}
assertDeepEquals(expected, parsedFailure);
}
use of org.opensearch.script.ScriptException in project OpenSearch by opensearch-project.
the class ScriptProcessorFactoryTests method testFactoryInvalidateWithInvalidCompiledScript.
public void testFactoryInvalidateWithInvalidCompiledScript() throws Exception {
String randomType = randomFrom("source", "id");
ScriptService mockedScriptService = mock(ScriptService.class);
ScriptException thrownException = new ScriptException("compile-time exception", new RuntimeException(), Collections.emptyList(), "script", "mockscript");
when(mockedScriptService.compile(any(), any())).thenThrow(thrownException);
factory = new ScriptProcessor.Factory(mockedScriptService);
Map<String, Object> configMap = new HashMap<>();
configMap.put(randomType, "my_script");
OpenSearchException exception = expectThrows(OpenSearchException.class, () -> factory.create(null, randomAlphaOfLength(10), null, configMap));
assertThat(exception.getMessage(), is("compile-time exception"));
}
use of org.opensearch.script.ScriptException in project OpenSearch by opensearch-project.
the class ScriptTestCase method expectScriptThrows.
/**
* Checks a specific exception class is thrown (boxed inside ScriptException) and returns it.
*/
public static final <T extends Throwable> T expectScriptThrows(Class<T> expectedType, boolean shouldHaveScriptStack, ThrowingRunnable runnable) {
try {
runnable.run();
} catch (Throwable e) {
if (e instanceof ScriptException) {
boolean hasEmptyScriptStack = ((ScriptException) e).getScriptStack().isEmpty();
if (shouldHaveScriptStack && hasEmptyScriptStack) {
/* If this fails you *might* be missing -XX:-OmitStackTraceInFastThrow in the test jvm
* In Eclipse you can add this by default by going to Preference->Java->Installed JREs,
* clicking on the default JRE, clicking edit, and adding the flag to the
* "Default VM Arguments". */
AssertionFailedError assertion = new AssertionFailedError("ScriptException should have a scriptStack");
assertion.initCause(e);
throw assertion;
} else if (false == shouldHaveScriptStack && false == hasEmptyScriptStack) {
AssertionFailedError assertion = new AssertionFailedError("ScriptException shouldn't have a scriptStack");
assertion.initCause(e);
throw assertion;
}
e = e.getCause();
if (expectedType.isInstance(e)) {
return expectedType.cast(e);
}
} else {
AssertionFailedError assertion = new AssertionFailedError("Expected boxed ScriptException");
assertion.initCause(e);
throw assertion;
}
AssertionFailedError assertion = new AssertionFailedError("Unexpected exception type, expected " + expectedType.getSimpleName());
assertion.initCause(e);
throw assertion;
}
throw new AssertionFailedError("Expected exception " + expectedType.getSimpleName());
}
Aggregations