rt/emul/compact/src/test/java/org/apidesign/vm4brwsr/dynamic/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 09 Aug 2014 12:15:18 +0200
branchjdk8
changeset 1648 905b2a470def
permissions -rw-r--r--
Can these tests be placed in compact profile
     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.dynamic;
    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.ArrayList;
    27 import java.util.Arrays;
    28 import java.util.Enumeration;
    29 import java.util.HashSet;
    30 import java.util.List;
    31 import java.util.Set;
    32 import javax.script.Invocable;
    33 import javax.script.ScriptContext;
    34 import javax.script.ScriptEngine;
    35 import javax.script.ScriptEngineManager;
    36 import javax.script.ScriptException;
    37 import org.apidesign.vm4brwsr.Bck2Brwsr;
    38 import org.apidesign.vm4brwsr.ObfuscationLevel;
    39 import static org.testng.Assert.*;
    40 
    41 public final class TestVM {
    42     private final Invocable code;
    43     private final CharSequence codeSeq;
    44     private final Object bck2brwsr;
    45     
    46     
    47     private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
    48         this.code = code;
    49         this.codeSeq = codeSeq;
    50         this.bck2brwsr = ((ScriptEngine)code).eval("bck2brwsr(function(n) { return loader.get(n); })");
    51         ((ScriptEngine)code).getContext().setAttribute("loader", this, ScriptContext.ENGINE_SCOPE);
    52     }
    53     
    54     public Object execCode(
    55         String msg, Class<?> clazz, String method, 
    56         Object expRes, Object... args
    57     ) throws Exception {
    58         Object ret = null;
    59         try {
    60             ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
    61             List<Object> ma = new ArrayList<>();
    62             ma.add(method);
    63             ma.addAll(Arrays.asList(args));
    64             ret = code.invokeMethod(ret, "invoke", ma.toArray());
    65         } catch (ScriptException ex) {
    66             fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    67         } catch (NoSuchMethodException ex) {
    68             fail("Cannot find method in " + dumpJS(codeSeq), ex);
    69         }
    70         if (ret == null && expRes == null) {
    71             return null;
    72         }
    73         if (expRes != null && expRes.equals(ret)) {
    74             return null;
    75         }
    76         if (expRes instanceof Number) {
    77             // in case of Long it is necessary convert it to number
    78             // since the Long is represented by two numbers in JavaScript
    79             try {
    80                 final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
    81                 if (ret instanceof Long) {
    82                     ret = code.invokeMethod(toFP, "call", ret);
    83                 }
    84                 ret = code.invokeFunction("Number", ret);
    85             } catch (ScriptException ex) {
    86                 fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    87             } catch (NoSuchMethodException ex) {
    88                 fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    89             }
    90         }
    91         return ret;
    92     }
    93     
    94     void assertExec(
    95         String msg, Class clazz, String method, Object expRes, Object... args
    96     ) throws Exception {
    97         Object ret = execCode(msg, clazz, method, expRes, args);
    98         if (ret == null) {
    99             return;
   100         }
   101         if (expRes instanceof Integer && ret instanceof Double) {
   102             expRes = ((Integer)expRes).doubleValue();
   103         }
   104         if (expRes != null && expRes.equals(ret)) {
   105             return;
   106         }
   107         assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
   108     }    
   109 
   110     static TestVM compileClass(String... names) throws ScriptException, IOException {
   111         return compileClass(null, names);
   112     }
   113     
   114     static TestVM compileClass(StringBuilder sb, String... names) throws ScriptException, IOException {
   115         return compileClass(sb, null, names);
   116     }
   117 
   118     static TestVM compileClass(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
   119         return compileClass(sb, eng, new EmulationResources(), names);
   120     }
   121     static TestVM compileClass(
   122         StringBuilder sb, 
   123         ScriptEngine[] eng, 
   124         Bck2Brwsr.Resources resources, 
   125         String... names
   126     ) throws ScriptException, IOException {
   127         if (sb == null) {
   128             sb = new StringBuilder();
   129         }
   130         Bck2Brwsr.generate(sb, resources, names);
   131         ScriptEngineManager sem = new ScriptEngineManager();
   132         ScriptEngine js = sem.getEngineByExtension("js");
   133         if (eng != null) {
   134             eng[0] = js;
   135         }
   136         try {
   137             Object res = js.eval(sb.toString());
   138             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   139             return new TestVM((Invocable) js, sb);
   140         } catch (Exception ex) {
   141             if (sb.length() > 2000) {
   142                 sb = dumpJS(sb);
   143             }
   144             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   145             return null;
   146         }
   147     }
   148     
   149     static TestVM compileClassAsExtension(
   150         StringBuilder sb, ScriptEngine[] eng, 
   151         String name, final String resourceName, final String resourceContent
   152     ) throws ScriptException, IOException {
   153         return compileClassesAsExtension(sb, eng, resourceName, resourceContent, name);
   154     }
   155     static TestVM compileClassesAsExtension(
   156         StringBuilder sb, ScriptEngine[] eng, 
   157         final String resourceName, final String resourceContent, String... names
   158     ) throws ScriptException, IOException {
   159         if (sb == null) {
   160             sb = new StringBuilder();
   161         }
   162         if (eng[0] == null) {
   163             ScriptEngineManager sem = new ScriptEngineManager();
   164             ScriptEngine js = sem.getEngineByExtension("js");
   165             eng[0] = js;
   166             Bck2Brwsr.generate(sb, new EmulationResources());
   167         }
   168         Set<String> exp = new HashSet<String>();
   169         for (String n : names) {
   170             int last = n.lastIndexOf('/');
   171             exp.add(n.substring(0, last + 1));
   172         }
   173         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   174             resources(new EmulationResources() {
   175                 @Override
   176                 public InputStream get(String name) throws IOException {
   177                     if (name.equals(resourceName)) {
   178                         return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
   179                     }
   180                     return super.get(name);
   181                 }
   182             }).
   183             addClasses(names).
   184             addResources("org/apidesign/vm4brwsr/obj.js").
   185             addExported(exp.toArray(new String[0])).
   186             obfuscation(ObfuscationLevel.FULL).
   187             library();
   188         if (resourceName != null) {
   189             b2b = b2b.addResources(resourceName);
   190         }
   191         b2b.generate(sb);
   192         try {
   193             defineAtoB(eng[0]);
   194             Object res = eng[0].eval(sb.toString());
   195             assertTrue(eng[0] instanceof Invocable, "It is invocable object: " + res);
   196             return new TestVM((Invocable) eng[0], sb);
   197         } catch (Exception ex) {
   198             if (sb.length() > 2000) {
   199                 sb = dumpJS(sb);
   200             }
   201             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   202             return null;
   203         }
   204     }
   205     
   206     static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
   207         if (sb == null) {
   208             sb = new StringBuilder();
   209         }
   210         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   211             resources(new EmulationResources()).
   212             addRootClasses(name).
   213             addResources(resources);
   214         b2b.generate(sb);
   215         ScriptEngineManager sem = new ScriptEngineManager();
   216         ScriptEngine js = sem.getEngineByExtension("js");
   217         if (eng != null) {
   218             eng[0] = js;
   219         }
   220         try {
   221             defineAtoB(js);
   222             
   223             Object res = js.eval(sb.toString());
   224             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   225             return new TestVM((Invocable) js, sb);
   226         } catch (Exception ex) {
   227             if (sb.length() > 2000) {
   228                 sb = dumpJS(sb);
   229             }
   230             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   231             return null;
   232         }
   233     }
   234 
   235     private static void defineAtoB(ScriptEngine js) throws ScriptException {
   236         js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
   237     }
   238 
   239     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   240         return code.invokeMethod(obj, method, params);
   241     }
   242 
   243     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   244         return code.invokeFunction(methodName, args);
   245     }
   246 
   247     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   248         File f = File.createTempFile("execution", ".js");
   249         FileWriter w = new FileWriter(f);
   250         w.append(sb);
   251         w.close();
   252         return new StringBuilder(f.getPath());
   253     }
   254 
   255     @Override
   256     public String toString() {
   257         try {
   258             return dumpJS(codeSeq).toString();
   259         } catch (IOException ex) {
   260             return ex.toString();
   261         }
   262     }
   263 
   264     final CharSequence codeSeq() {
   265         return codeSeq;
   266     }
   267     
   268     private static class EmulationResources implements Bck2Brwsr.Resources {
   269         @Override
   270         public InputStream get(String name) throws IOException {
   271             if ("java/net/URI.class".equals(name)) {
   272                 // skip
   273                 return null;
   274             }
   275             if ("java/net/URLConnection.class".equals(name)) {
   276                 // skip
   277                 return null;
   278             }
   279             if ("java/lang/System.class".equals(name)) {
   280                 // skip
   281                 return null;
   282             }
   283             Enumeration<URL> en = TestVM.class.getClassLoader().getResources(name);
   284             URL u = null;
   285             while (en.hasMoreElements()) {
   286                 u = en.nextElement();
   287             }
   288             if (u == null) {
   289                 throw new IOException("Can't find " + name);
   290             }
   291             if (u.toExternalForm().contains("rt.jar!")) {
   292                 throw new IOException("No emulation for " + u);
   293             }
   294             return u.openStream();
   295         }
   296     }
   297 }