Last active
March 1, 2017 11:20
-
-
Save jfrantzius/db6474f87300b45c887cdc2e45cd2dff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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