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