rt/vm/src/test/java/org/apidesign/vm4brwsr/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 28 Apr 2014 20:23:44 +0200
branchclosure
changeset 1497 daa5f903b529
parent 1495 d5dd07b45f79
child 1513 ba912ef24b27
permissions -rw-r--r--
Testing loading of resource from an extension and preparing for loading them from multiple extensions
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.vm4brwsr;
    19 
    20 import java.io.ByteArrayInputStream;
    21 import java.io.File;
    22 import java.io.FileWriter;
    23 import java.io.IOException;
    24 import java.io.InputStream;
    25 import java.net.URL;
    26 import java.util.Enumeration;
    27 import javax.script.Invocable;
    28 import javax.script.ScriptEngine;
    29 import javax.script.ScriptEngineManager;
    30 import javax.script.ScriptException;
    31 import static org.testng.Assert.*;
    32 
    33 final class TestVM {
    34     private final Invocable code;
    35     private final CharSequence codeSeq;
    36     private final Object bck2brwsr;
    37     
    38     
    39     private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
    40         this.code = code;
    41         this.codeSeq = codeSeq;
    42         this.bck2brwsr = code.invokeFunction("bck2brwsr");
    43     }
    44     
    45 
    46     public Object execCode(
    47         String msg, Class<?> clazz, String method, 
    48         Object expRes, Object... args
    49     ) throws Exception {
    50         Object ret = null;
    51         try {
    52             ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
    53             ret = code.invokeMethod(ret, method, args);
    54         } catch (ScriptException ex) {
    55             fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    56         } catch (NoSuchMethodException ex) {
    57             fail("Cannot find method in " + dumpJS(codeSeq), ex);
    58         }
    59         if (ret == null && expRes == null) {
    60             return null;
    61         }
    62         if (expRes != null && expRes.equals(ret)) {
    63             return null;
    64         }
    65         if (expRes instanceof Number) {
    66             // in case of Long it is necessary convert it to number
    67             // since the Long is represented by two numbers in JavaScript
    68             try {
    69                 final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
    70                 if (ret instanceof Long) {
    71                     ret = code.invokeMethod(toFP, "call", ret);
    72                 }
    73                 ret = code.invokeFunction("Number", ret);
    74             } catch (ScriptException ex) {
    75                 fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    76             } catch (NoSuchMethodException ex) {
    77                 fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    78             }
    79         }
    80         return ret;
    81     }
    82     
    83     void assertExec(
    84         String msg, Class clazz, String method, Object expRes, Object... args
    85     ) throws Exception {
    86         Object ret = execCode(msg, clazz, method, expRes, args);
    87         if (ret == null) {
    88             return;
    89         }
    90         if (expRes instanceof Integer && ret instanceof Double) {
    91             expRes = ((Integer)expRes).doubleValue();
    92         }
    93         if (expRes != null && expRes.equals(ret)) {
    94             return;
    95         }
    96         assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
    97     }    
    98 
    99     static TestVM compileClass(String... names) throws ScriptException, IOException {
   100         return compileClass(null, names);
   101     }
   102     
   103     static TestVM compileClass(StringBuilder sb, String... names) throws ScriptException, IOException {
   104         return compileClass(sb, null, names);
   105     }
   106 
   107     static TestVM compileClass(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
   108         if (sb == null) {
   109             sb = new StringBuilder();
   110         }
   111         Bck2Brwsr.generate(sb, new EmulationResources(), names);
   112         ScriptEngineManager sem = new ScriptEngineManager();
   113         ScriptEngine js = sem.getEngineByExtension("js");
   114         if (eng != null) {
   115             eng[0] = js;
   116         }
   117         try {
   118             Object res = js.eval(sb.toString());
   119             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   120             return new TestVM((Invocable) js, sb);
   121         } catch (Exception ex) {
   122             if (sb.length() > 2000) {
   123                 sb = dumpJS(sb);
   124             }
   125             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   126             return null;
   127         }
   128     }
   129     
   130     static TestVM compileClassAsExtension(
   131         StringBuilder sb, ScriptEngine[] eng, 
   132         String name, final String resourceName, final String resourceContent
   133     ) throws ScriptException, IOException {
   134         if (sb == null) {
   135             sb = new StringBuilder();
   136         }
   137         if (eng[0] == null) {
   138             ScriptEngineManager sem = new ScriptEngineManager();
   139             ScriptEngine js = sem.getEngineByExtension("js");
   140             eng[0] = js;
   141             Bck2Brwsr.generate(sb, new EmulationResources());
   142         }
   143         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   144             resources(new EmulationResources() {
   145                 @Override
   146                 public InputStream get(String name) throws IOException {
   147                     if (name.equals(resourceName)) {
   148                         return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
   149                     }
   150                     return super.get(name);
   151                 }
   152             }).
   153             addRootClasses(name).library(true);
   154         if (resourceName != null) {
   155             b2b = b2b.addResources(resourceName);
   156         }
   157         b2b.generate(sb);
   158         try {
   159             defineAtoB(eng[0]);
   160             Object res = eng[0].eval(sb.toString());
   161             assertTrue(eng[0] instanceof Invocable, "It is invocable object: " + res);
   162             return new TestVM((Invocable) eng[0], sb);
   163         } catch (Exception ex) {
   164             if (sb.length() > 2000) {
   165                 sb = dumpJS(sb);
   166             }
   167             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   168             return null;
   169         }
   170     }
   171     
   172     static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
   173         if (sb == null) {
   174             sb = new StringBuilder();
   175         }
   176         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   177             resources(new EmulationResources()).
   178             addRootClasses(name).
   179             addResources(resources).
   180             library(false);
   181         b2b.generate(sb);
   182         ScriptEngineManager sem = new ScriptEngineManager();
   183         ScriptEngine js = sem.getEngineByExtension("js");
   184         if (eng != null) {
   185             eng[0] = js;
   186         }
   187         try {
   188             defineAtoB(js);
   189             
   190             Object res = js.eval(sb.toString());
   191             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   192             return new TestVM((Invocable) js, sb);
   193         } catch (Exception ex) {
   194             if (sb.length() > 2000) {
   195                 sb = dumpJS(sb);
   196             }
   197             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   198             return null;
   199         }
   200     }
   201 
   202     private static void defineAtoB(ScriptEngine js) throws ScriptException {
   203         js.eval("atob = function(s) { return org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s); }");
   204         
   205         Object ahoj = js.eval("atob('QWhvag==')");
   206         assertEquals(ahoj, "Ahoj", "Verify the atob function behaves properly");
   207     }
   208 
   209     Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
   210         return code.invokeMethod(bck2brwsr, "loadClass", Exceptions.class.getName());
   211     }
   212     
   213     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   214         return code.invokeMethod(obj, method, params);
   215     }
   216 
   217     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   218         return code.invokeFunction(methodName, args);
   219     }
   220 
   221     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   222         File f = File.createTempFile("execution", ".js");
   223         FileWriter w = new FileWriter(f);
   224         w.append(sb);
   225         w.close();
   226         return new StringBuilder(f.getPath());
   227     }
   228 
   229     @Override
   230     public String toString() {
   231         try {
   232             return dumpJS(codeSeq).toString();
   233         } catch (IOException ex) {
   234             return ex.toString();
   235         }
   236     }
   237     
   238     
   239     private static class EmulationResources implements Bck2Brwsr.Resources {
   240         @Override
   241         public InputStream get(String name) throws IOException {
   242             Enumeration<URL> en = StaticMethodTest.class.getClassLoader().getResources(name);
   243             URL u = null;
   244             while (en.hasMoreElements()) {
   245                 u = en.nextElement();
   246             }
   247             if (u == null) {
   248                 throw new IOException("Can't find " + name);
   249             }
   250             if (u.toExternalForm().contains("rt.jar!")) {
   251                 throw new IOException("No emulation for " + u);
   252             }
   253             return u.openStream();
   254         }
   255     }
   256 }