rt/flow/src/test/java/org/apidesign/bck2brwsr/flow/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 13 Mar 2015 11:58:30 +0100
branchflow
changeset 1817 c1fd23f4e0ae
parent 1815 fbe883b5a793
permissions -rw-r--r--
Cleaning up the test harness
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012-2015 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.bck2brwsr.flow;
    19 
    20 import java.io.File;
    21 import java.io.FileOutputStream;
    22 import java.io.IOException;
    23 import java.io.InputStream;
    24 import java.io.OutputStreamWriter;
    25 import java.io.Writer;
    26 import java.net.URL;
    27 import java.util.ArrayList;
    28 import java.util.Arrays;
    29 import java.util.Enumeration;
    30 import java.util.List;
    31 import javax.script.Invocable;
    32 import javax.script.ScriptContext;
    33 import javax.script.ScriptEngine;
    34 import javax.script.ScriptEngineManager;
    35 import javax.script.ScriptException;
    36 import org.apidesign.vm4brwsr.Bck2Brwsr;
    37 import org.apidesign.vm4brwsr.Bck2Brwsr.Flow;
    38 import static org.testng.Assert.*;
    39 
    40 public final class TestVM {
    41     private final ScriptEngine js;
    42     private Invocable code;
    43     private final CharSequence codeSeq;
    44     private Object bck2brwsr;
    45     
    46     
    47     private TestVM(ScriptEngine js, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
    48         this.js = js;
    49         this.codeSeq = codeSeq;
    50     }
    51     
    52     public Object execCode(
    53         String msg, Class<?> clazz, String method, 
    54         Object expRes, Object... args
    55     ) throws Exception {
    56         Object ret = null;
    57         try {
    58             ret = getCode().invokeMethod(bck2brwsr, "loadClass", clazz.getName());
    59             List<Object> ma = new ArrayList<Object>();
    60             ma.add(method);
    61             ma.addAll(Arrays.asList(args));
    62             ret = getCode().invokeMethod(ret, "invoke", ma.toArray());
    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)getCode()).eval("Number.prototype.toFP");
    79                 if (ret instanceof Long) {
    80                     ret = getCode().invokeMethod(toFP, "call", ret);
    81                 }
    82                 ret = getCode().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, GraalFlowAnalyzer.getDefault(), names);
   110     }
   111     
   112     static TestVM compileClass(StringBuilder sb, Flow.Analyzer flow, String... names) throws ScriptException, IOException {
   113         return compileClass(sb, null, flow, names);
   114     }
   115 
   116     static TestVM compileClass(StringBuilder sb, 
   117         ScriptEngine[] eng, Flow.Analyzer flow, String... names
   118     ) throws ScriptException, IOException {
   119         return compileClass(sb, eng, flow, new EmulationResources(), names);
   120     }
   121     static TestVM compileClass(
   122         StringBuilder sb, 
   123         ScriptEngine[] eng, 
   124         Flow.Analyzer flow,
   125         Bck2Brwsr.Resources resources, 
   126         String... names
   127     ) throws ScriptException, IOException {
   128         if (sb == null) {
   129             sb = new StringBuilder();
   130         }
   131         Bck2Brwsr.newCompiler()
   132             .resources(resources)
   133             .addClasses(names)
   134             .flowAnalyzer(flow)
   135             .generate(sb);
   136         ScriptEngineManager sem = new ScriptEngineManager();
   137         ScriptEngine js = sem.getEngineByExtension("js");
   138         if (eng != null) {
   139             eng[0] = js;
   140         }
   141         try {
   142             return new TestVM(js, sb);
   143         } catch (Exception ex) {
   144             if (sb.length() > 2000) {
   145                 sb = dumpJS(sb);
   146             }
   147             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   148             return null;
   149         }
   150     }
   151 
   152     Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
   153         return getCode().invokeMethod(bck2brwsr, "loadClass", LoopControl.class.getName());
   154     }
   155     
   156     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   157         return getCode().invokeMethod(obj, method, params);
   158     }
   159 
   160     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   161         return getCode().invokeFunction(methodName, args);
   162     }
   163 
   164     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   165         File f = File.createTempFile("execution", ".js");
   166         Writer w = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
   167         w.append(sb);
   168         w.close();
   169         return new StringBuilder(f.getPath());
   170     }
   171 
   172     @Override
   173     public String toString() {
   174         try {
   175             return dumpJS(codeSeq).toString();
   176         } catch (IOException ex) {
   177             return ex.toString();
   178         }
   179     }
   180 
   181     final CharSequence codeSeq() {
   182         return codeSeq;
   183     }
   184 
   185     /**
   186      * @return the code
   187      */
   188     private Invocable getCode() throws ScriptException {
   189         if (code == null) {
   190             js.eval(codeSeq.toString());
   191             js.getContext().setAttribute("loader", this, ScriptContext.ENGINE_SCOPE);
   192             this.bck2brwsr = js.eval("bck2brwsr(function(n) { return loader.get(n); })");
   193             code = (Invocable) js;
   194         }
   195         return (Invocable)code;
   196     }
   197     
   198     private static class EmulationResources implements Bck2Brwsr.Resources {
   199         @Override
   200         public InputStream get(String name) throws IOException {
   201             if ("java/net/URI.class".equals(name)) {
   202                 // skip
   203                 return null;
   204             }
   205             if ("java/net/URLConnection.class".equals(name)) {
   206                 // skip
   207                 return null;
   208             }
   209             if ("java/lang/System.class".equals(name)) {
   210                 // skip
   211                 return null;
   212             }
   213             if ("java/io/PrintStream.class".equals(name)) {
   214                 // skip
   215                 return null;
   216             }
   217             if ("java/io/PrintWriter.class".equals(name)) {
   218                 // skip
   219                 return null;
   220             }
   221             Enumeration<URL> en = LoopControlTest.class.getClassLoader().getResources(name);
   222             URL u = null;
   223             while (en.hasMoreElements()) {
   224                 u = en.nextElement();
   225             }
   226             if (u == null) {
   227                 throw new IOException("Can't find " + name);
   228             }
   229             if (u.toExternalForm().contains("rt.jar!")) {
   230                 throw new IOException("No emulation for " + u);
   231             }
   232             return u.openStream();
   233         }
   234     }
   235 }