package com.oracle.truffle.js.scriptengine.test;
import java.util.concurrent.Callable;
import javax.script.ScriptContext;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
import org.graalvm.polyglot.Engine;
import org.junit.Assert;
import org.junit.Test;
import com.oracle.truffle.js.scriptengine.GraalJSScriptEngine;
public class TestScriptEngineInterop {
private static final String ID = "js";
@Test
public void testCustomBuilder() throws ScriptException {
Engine graalEngine = Engine.newBuilder().build();
GraalJSScriptEngine graalJSScriptEngine = GraalJSScriptEngine.create(graalEngine,
TestUtil.newContextBuilder().engine(graalEngine));
Assert.assertEquals(42, graalJSScriptEngine.eval("42"));
graalEngine.close();
}
@Test
public void testInterop() throws ScriptException {
GraalJSScriptEngine engine = GraalJSScriptEngine.create(null, TestUtil.newContextBuilder());
Object result = engine.eval("a = 42");
Assert.assertEquals(42, result);
Assert.assertEquals(42, engine.get("a"));
engine.getContext().setAttribute("a", 43, ScriptContext.ENGINE_SCOPE);
Assert.assertEquals(43, engine.getPolyglotContext().getBindings(ID).getMember("a").asInt());
SimpleScriptContext context = new SimpleScriptContext();
Assert.assertEquals(43, engine.eval("this['a']"));
Assert.assertNull(engine.eval("this['a']", context));
Assert.assertEquals(43, engine.eval("this['a']"));
Assert.assertNotSame(engine.getPolyglotContext(), engine.getPolyglotContext(context));
Assert.assertSame(engine.getPolyglotContext().getEngine(), engine.getPolyglotContext(context).getEngine());
Assert.assertSame(engine.getPolyglotEngine(), engine.getPolyglotContext().getEngine());
}
@Test
public void testDirectPolyglotContextAccess() {
GraalJSScriptEngine engine = GraalJSScriptEngine.create();
SimpleScriptContext context = new SimpleScriptContext();
Assert.assertNotNull(engine.getPolyglotContext(context));
}
interface TestInterface {
}
@Test
public void testClose() throws ScriptException {
GraalJSScriptEngine engine = GraalJSScriptEngine.create();
Object obj = engine.eval("({})");
engine.close();
expectIllegalState(() -> engine.eval(""));
expectIllegalState(() -> engine.compile(""));
expectIllegalState(() -> engine.get("key"));
expectIllegalState(() -> {
engine.put("key", "");
return null;
});
expectIllegalState(() -> {
engine.invokeFunction("");
return null;
});
expectIllegalState(() -> {
engine.invokeMethod(obj, "");
return null;
});
expectIllegalState(() -> {
engine.getInterface(TestInterface.class);
return null;
});
}
private static void expectIllegalState(Callable<?> r) {
try {
r.call();
Assert.fail("expected illegal state");
} catch (IllegalStateException e) {
} catch (Exception e) {
throw new AssertionError(e);
}
}
}