rt/vm/src/test/java/org/apidesign/vm4brwsr/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 26 Apr 2014 21:30:06 +0200
branchclosure
changeset 1491 4a1398eff4fb
parent 1487 84a744941c9f
child 1493 234fea368401
permissions -rw-r--r--
Different meaning of root vs. added classes. Ability to explicitly enumerate classes that should be exported and available with fully qualified name.
     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.File;
    21 import java.io.FileWriter;
    22 import java.io.IOException;
    23 import java.io.InputStream;
    24 import java.net.URL;
    25 import java.util.Enumeration;
    26 import javax.script.Invocable;
    27 import javax.script.ScriptEngine;
    28 import javax.script.ScriptEngineManager;
    29 import javax.script.ScriptException;
    30 import static org.testng.Assert.*;
    31 
    32 final class TestVM {
    33     private final Invocable code;
    34     private final CharSequence codeSeq;
    35     private final Object bck2brwsr;
    36     
    37     
    38     private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
    39         this.code = code;
    40         this.codeSeq = codeSeq;
    41         this.bck2brwsr = code.invokeFunction("bck2brwsr");
    42     }
    43     
    44 
    45     public Object execCode(
    46         String msg, Class<?> clazz, String method, 
    47         Object expRes, Object... args
    48     ) throws Exception {
    49         Object ret = null;
    50         try {
    51             ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
    52             ret = code.invokeMethod(ret, method, args);
    53         } catch (ScriptException ex) {
    54             fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    55         } catch (NoSuchMethodException ex) {
    56             fail("Cannot find method in " + dumpJS(codeSeq), ex);
    57         }
    58         if (ret == null && expRes == null) {
    59             return null;
    60         }
    61         if (expRes != null && expRes.equals(ret)) {
    62             return null;
    63         }
    64         if (expRes instanceof Number) {
    65             // in case of Long it is necessary convert it to number
    66             // since the Long is represented by two numbers in JavaScript
    67             try {
    68                 final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
    69                 if (ret instanceof Long) {
    70                     ret = code.invokeMethod(toFP, "call", ret);
    71                 }
    72                 ret = code.invokeFunction("Number", ret);
    73             } catch (ScriptException ex) {
    74                 fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    75             } catch (NoSuchMethodException ex) {
    76                 fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    77             }
    78         }
    79         return ret;
    80     }
    81     
    82     void assertExec(
    83         String msg, Class clazz, String method, Object expRes, Object... args
    84     ) throws Exception {
    85         Object ret = execCode(msg, clazz, method, expRes, args);
    86         if (ret == null) {
    87             return;
    88         }
    89         if (expRes instanceof Integer && ret instanceof Double) {
    90             expRes = ((Integer)expRes).doubleValue();
    91         }
    92         if (expRes != null && expRes.equals(ret)) {
    93             return;
    94         }
    95         assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
    96     }    
    97 
    98     static TestVM compileClass(String... names) throws ScriptException, IOException {
    99         return compileClass(null, names);
   100     }
   101     
   102     static TestVM compileClass(StringBuilder sb, String... names) throws ScriptException, IOException {
   103         return compileClass(sb, null, names);
   104     }
   105 
   106     static TestVM compileClass(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
   107         if (sb == null) {
   108             sb = new StringBuilder();
   109         }
   110         Bck2Brwsr.generate(sb, new EmulationResources(), names);
   111         ScriptEngineManager sem = new ScriptEngineManager();
   112         ScriptEngine js = sem.getEngineByExtension("js");
   113         if (eng != null) {
   114             eng[0] = js;
   115         }
   116         try {
   117             Object res = js.eval(sb.toString());
   118             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   119             return new TestVM((Invocable) js, sb);
   120         } catch (Exception ex) {
   121             if (sb.length() > 2000) {
   122                 sb = dumpJS(sb);
   123             }
   124             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   125             return null;
   126         }
   127     }
   128     
   129     static TestVM compileClassAsExtension(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
   130         if (sb == null) {
   131             sb = new StringBuilder();
   132         }
   133         Bck2Brwsr.generate(sb, new EmulationResources());
   134         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   135             resources(new EmulationResources()).
   136             addRootClasses(names).library(true);
   137         b2b.generate(sb);
   138         ScriptEngineManager sem = new ScriptEngineManager();
   139         ScriptEngine js = sem.getEngineByExtension("js");
   140         if (eng != null) {
   141             eng[0] = js;
   142         }
   143         try {
   144             Object res = js.eval(sb.toString());
   145             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   146             return new TestVM((Invocable) js, sb);
   147         } catch (Exception ex) {
   148             if (sb.length() > 2000) {
   149                 sb = dumpJS(sb);
   150             }
   151             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   152             return null;
   153         }
   154     }
   155 
   156     Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
   157         return code.invokeMethod(bck2brwsr, "loadClass", Exceptions.class.getName());
   158     }
   159     
   160     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   161         return code.invokeMethod(obj, method, params);
   162     }
   163 
   164     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   165         return code.invokeFunction(methodName, args);
   166     }
   167 
   168     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   169         File f = File.createTempFile("execution", ".js");
   170         FileWriter w = new FileWriter(f);
   171         w.append(sb);
   172         w.close();
   173         return new StringBuilder(f.getPath());
   174     }
   175 
   176     @Override
   177     public String toString() {
   178         try {
   179             return dumpJS(codeSeq).toString();
   180         } catch (IOException ex) {
   181             return ex.toString();
   182         }
   183     }
   184     
   185     
   186     private static class EmulationResources implements Bck2Brwsr.Resources {
   187         @Override
   188         public InputStream get(String name) throws IOException {
   189             Enumeration<URL> en = StaticMethodTest.class.getClassLoader().getResources(name);
   190             URL u = null;
   191             while (en.hasMoreElements()) {
   192                 u = en.nextElement();
   193             }
   194             if (u == null) {
   195                 throw new IOException("Can't find " + name);
   196             }
   197             if (u.toExternalForm().contains("rt.jar!")) {
   198                 throw new IOException("No emulation for " + u);
   199             }
   200             return u.openStream();
   201         }
   202     }
   203 }