vmtest/src/main/java/org/apidesign/bck2brwsr/vmtest/VMTest.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 17 Dec 2012 17:51:05 +0100
branchlauncher
changeset 347 6f964a88e6c5
parent 346 b671ac44bc55
child 349 3fe5a86bd123
permissions -rw-r--r--
Cleanup and calling the VMTest.read method directly
     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.bck2brwsr.vmtest;
    19 
    20 import java.io.File;
    21 import java.io.FileWriter;
    22 import java.io.IOException;
    23 import java.io.InputStream;
    24 import java.lang.reflect.Method;
    25 import java.net.URL;
    26 import java.util.Enumeration;
    27 import java.util.Map;
    28 import java.util.WeakHashMap;
    29 import javax.script.Invocable;
    30 import javax.script.ScriptEngine;
    31 import javax.script.ScriptEngineManager;
    32 import org.apidesign.vm4brwsr.Bck2Brwsr;
    33 import org.testng.Assert;
    34 import org.testng.ITest;
    35 import org.testng.annotations.Factory;
    36 import org.testng.annotations.Test;
    37 
    38 /** A TestNG {@link Factory} that seeks for {@link Compare} annotations
    39  * in provided class and builds set of tests that compare the computations
    40  * in real as well as JavaScript virtual machines. Use as:<pre>
    41  * {@code @}{@link Factory} public static create() {
    42  *   return @{link VMTest}.{@link #create(YourClass.class);
    43  * }</pre>
    44  *
    45  * @author Jaroslav Tulach <jtulach@netbeans.org>
    46  */
    47 public final class VMTest implements ITest {
    48     private final Run first, second;
    49     private final Method m;
    50     
    51     private VMTest(Method m, Run first, Run second) {
    52         this.first = first;
    53         this.second = second;
    54         this.m = m;
    55     }
    56 
    57     /** Inspects <code>clazz</code> and for each {@lik Compare} method creates
    58      * instances of tests. Each instance runs the test in different virtual
    59      * machine and at the end they compare the results.
    60      * 
    61      * @param clazz the class to inspect
    62      * @return the set of created tests
    63      */
    64     public static Object[] create(Class<?> clazz) {
    65         Method[] arr = clazz.getMethods();
    66         Object[] ret = new Object[3 * arr.length];
    67         int cnt = 0;
    68         for (Method m : arr) {
    69             Compare c = m.getAnnotation(Compare.class);
    70             if (c == null) {
    71                 continue;
    72             }
    73             final Run real = new Run(m, false);
    74             final Run js = new Run(m, true);
    75             ret[cnt++] = real;
    76             ret[cnt++] = js;
    77             ret[cnt++] = new VMTest(m, real, js);
    78         }
    79         Object[] r = new Object[cnt];
    80         for (int i = 0; i < cnt; i++) {
    81             r[i] = ret[i];
    82         }
    83         return r;
    84     }
    85 
    86     /** Test that compares the previous results.
    87      * @throws Throwable 
    88      */
    89     @Test(dependsOnGroups = "run") public void compareResults() throws Throwable {
    90         Object v1 = first.value;
    91         Object v2 = second.value;
    92         if (v1 instanceof Number) {
    93             v1 = ((Number)v1).doubleValue();
    94         }
    95         Assert.assertEquals(v2, v1, "Comparing results");
    96     }
    97     
    98     /** Test name.
    99      * @return name of the tested method followed by a suffix
   100      */
   101     @Override
   102     public String getTestName() {
   103         return m.getName() + "[Compare]";
   104     }
   105 
   106     /** Helper method that inspects the classpath and loads given resource
   107      * (usually a class file). Used while running tests in Rhino.
   108      * 
   109      * @param name resource name to find
   110      * @return the array of bytes in the given resource
   111      * @throws IOException I/O in case something goes wrong
   112      */
   113     public static byte[] read(String name) throws IOException {
   114         URL u = null;
   115         Enumeration<URL> en = VMTest.class.getClassLoader().getResources(name);
   116         while (en.hasMoreElements()) {
   117             u = en.nextElement();
   118         }
   119         if (u == null) {
   120             throw new IOException("Can't find " + name);
   121         }
   122         try (InputStream is = u.openStream()) {
   123             byte[] arr;
   124             arr = new byte[is.available()];
   125             int offset = 0;
   126             while (offset < arr.length) {
   127                 int len = is.read(arr, offset, arr.length - offset);
   128                 if (len == -1) {
   129                     throw new IOException("Can't read " + name);
   130                 }
   131                 offset += len;
   132             }
   133             return arr;
   134         }
   135     }
   136    
   137     public static final class Run implements ITest {
   138         private final Method m;
   139         private final boolean js;
   140         Object value;
   141         private Invocable code;
   142         private CharSequence codeSeq;
   143         private static final Map<Class,Object[]> compiled = new WeakHashMap<>();
   144 
   145         private Run(Method m, boolean js) {
   146             this.m = m;
   147             this.js = js;
   148         }
   149 
   150         private void compileTheCode(Class<?> clazz) throws Exception {
   151             final Object[] data = compiled.get(clazz);
   152             if (data != null) {
   153                 code = (Invocable) data[0];
   154                 codeSeq = (CharSequence) data[1];
   155                 return;
   156             }
   157             StringBuilder sb = new StringBuilder();
   158             Bck2Brwsr.generate(sb, VMTest.class.getClassLoader());
   159 
   160             ScriptEngineManager sem = new ScriptEngineManager();
   161             ScriptEngine mach = sem.getEngineByExtension("js");
   162             
   163             sb.append(
   164                   "\nvar vm = bck2brwsr(org.apidesign.bck2brwsr.vmtest.VMTest.read);"
   165                 + "\nfunction initVM() { return vm; };"
   166                 + "\n");
   167 
   168             Object res = mach.eval(sb.toString());
   169             Assert.assertTrue(mach instanceof Invocable, "It is invocable object: " + res);
   170             code = (Invocable) mach;
   171             codeSeq = sb;
   172             compiled.put(clazz, new Object[] { code, codeSeq });
   173         }
   174 
   175         @Test(groups = "run") public void executeCode() throws Throwable {
   176             if (js) {
   177                 try {
   178                     compileTheCode(m.getDeclaringClass());
   179                     Object vm = code.invokeFunction("initVM");
   180                     Object inst = code.invokeMethod(vm, "loadClass", m.getDeclaringClass().getName());
   181                     value = code.invokeMethod(inst, m.getName() + "__" + computeSignature(m));
   182                 } catch (Exception ex) {
   183                     throw new AssertionError(dumpJS(codeSeq)).initCause(ex);
   184                 }
   185             } else {
   186                 value = m.invoke(m.getDeclaringClass().newInstance());
   187             }
   188         }
   189         @Override
   190         public String getTestName() {
   191             return m.getName() + (js ? "[JavaScript]" : "[Java]");
   192         }
   193         
   194         private static String computeSignature(Method m) {
   195             StringBuilder sb = new StringBuilder();
   196             appendType(sb, m.getReturnType());
   197             for (Class<?> c : m.getParameterTypes()) {
   198                 appendType(sb, c);
   199             }
   200             return sb.toString();
   201         }
   202         
   203         private static void appendType(StringBuilder sb, Class<?> t) {
   204             if (t == null) {
   205                 sb.append('V');
   206                 return;
   207             }
   208             if (t.isPrimitive()) {
   209                 int ch = -1;
   210                 if (t == int.class) {
   211                     ch = 'I';
   212                 }
   213                 if (t == short.class) {
   214                     ch = 'S';
   215                 }
   216                 if (t == byte.class) {
   217                     ch = 'B';
   218                 }
   219                 if (t == boolean.class) {
   220                     ch = 'Z';
   221                 }
   222                 if (t == long.class) {
   223                     ch = 'J';
   224                 }
   225                 if (t == float.class) {
   226                     ch = 'F';
   227                 }
   228                 if (t == double.class) {
   229                     ch = 'D';
   230                 }
   231                 assert ch != -1 : "Unknown primitive type " + t;
   232                 sb.append((char)ch);
   233                 return;
   234             }
   235             if (t.isArray()) {
   236                 sb.append("_3");
   237                 appendType(sb, t.getComponentType());
   238                 return;
   239             }
   240             sb.append('L');
   241             sb.append(t.getName().replace('.', '_'));
   242             sb.append("_2");
   243         }
   244     }
   245     
   246     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   247         File f = File.createTempFile("execution", ".js");
   248         try (FileWriter w = new FileWriter(f)) {
   249             w.append(sb);
   250         }
   251         return new StringBuilder(f.getPath());
   252     }
   253 }