Skip to content

Instantly share code, notes, and snippets.

@jfrantzius
Last active March 1, 2017 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfrantzius/db6474f87300b45c887cdc2e45cd2dff to your computer and use it in GitHub Desktop.
Save jfrantzius/db6474f87300b45c887cdc2e45cd2dff to your computer and use it in GitHub Desktop.
package com.aperto.javascript;
import org.junit.Test;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
import static org.junit.Assert.assertEquals;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
/**
* Test whether we can use a single ScriptContext without Nashorn wrongly assuming Global boundary
* crossing.
* @author joerg.frantzius
*
*/
public class TestSingleContextContainment {
@Test
public void testObjectCreateInFunctionFails() throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
SimpleScriptContext context = new SimpleScriptContext();
context.setAttribute("f", engine.eval("(function () {Object.create(this)})", context), ScriptContext.ENGINE_SCOPE);
engine.eval("f.call({})", context);
}
@Test
public void testObjectCreateInFunctionSucceeds() throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
SimpleScriptContext context = new SimpleScriptContext();
context.setAttribute("f", engine.eval("(function () {Object.create(this)})"), ScriptContext.ENGINE_SCOPE);
engine.eval("f.call(f)", context);
}
@Test
public void testJson() throws NoSuchMethodException, ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
ScriptContext globals = new SimpleScriptContext();
ScriptObjectMirror jsonParse = (ScriptObjectMirror) engine.eval("JSON.parse", globals);
ScriptObjectMirror jsonObject = (ScriptObjectMirror) jsonParse.call(jsonParse, "{\"foo\": \"bar\"}");
ScriptObjectMirror f = (ScriptObjectMirror) engine.eval("(function () {return Object.create(this).foo})");
assertEquals("bar", f.call(jsonObject));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment