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