vmtest/src/main/java/org/apidesign/bck2brwsr/vmtest/VMTest.java
branchlauncher
changeset 346 b671ac44bc55
parent 306 f36b3c273de6
child 347 6f964a88e6c5
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/vmtest/src/main/java/org/apidesign/bck2brwsr/vmtest/VMTest.java	Mon Dec 17 17:45:08 2012 +0100
     1.3 @@ -0,0 +1,254 @@
     1.4 +/**
     1.5 + * Back 2 Browser Bytecode Translator
     1.6 + * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     1.7 + *
     1.8 + * This program is free software: you can redistribute it and/or modify
     1.9 + * it under the terms of the GNU General Public License as published by
    1.10 + * the Free Software Foundation, version 2 of the License.
    1.11 + *
    1.12 + * This program is distributed in the hope that it will be useful,
    1.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
    1.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1.15 + * GNU General Public License for more details.
    1.16 + *
    1.17 + * You should have received a copy of the GNU General Public License
    1.18 + * along with this program. Look for COPYING file in the top folder.
    1.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
    1.20 + */
    1.21 +package org.apidesign.bck2brwsr.vmtest;
    1.22 +
    1.23 +import java.io.File;
    1.24 +import java.io.FileWriter;
    1.25 +import java.io.IOException;
    1.26 +import java.io.InputStream;
    1.27 +import java.lang.reflect.Method;
    1.28 +import java.net.URL;
    1.29 +import java.util.Enumeration;
    1.30 +import java.util.Map;
    1.31 +import java.util.WeakHashMap;
    1.32 +import javax.script.Invocable;
    1.33 +import javax.script.ScriptEngine;
    1.34 +import javax.script.ScriptEngineManager;
    1.35 +import org.apidesign.vm4brwsr.Bck2Brwsr;
    1.36 +import org.testng.Assert;
    1.37 +import org.testng.ITest;
    1.38 +import org.testng.annotations.Factory;
    1.39 +import org.testng.annotations.Test;
    1.40 +
    1.41 +/** A TestNG {@link Factory} that seeks for {@link Compare} annotations
    1.42 + * in provided class and builds set of tests that compare the computations
    1.43 + * in real as well as JavaScript virtual machines. Use as:<pre>
    1.44 + * {@code @}{@link Factory} public static create() {
    1.45 + *   return @{link VMTest}.{@link #create(YourClass.class);
    1.46 + * }</pre>
    1.47 + *
    1.48 + * @author Jaroslav Tulach <jtulach@netbeans.org>
    1.49 + */
    1.50 +public final class VMTest implements ITest {
    1.51 +    private final Run first, second;
    1.52 +    private final Method m;
    1.53 +    
    1.54 +    private VMTest(Method m, Run first, Run second) {
    1.55 +        this.first = first;
    1.56 +        this.second = second;
    1.57 +        this.m = m;
    1.58 +    }
    1.59 +
    1.60 +    /** Inspects <code>clazz</code> and for each {@lik Compare} method creates
    1.61 +     * instances of tests. Each insteance runs the test in different virtual
    1.62 +     * machine and at the end they compare the results.
    1.63 +     * 
    1.64 +     * @param clazz the class to inspect
    1.65 +     * @return the set of created tests
    1.66 +     */
    1.67 +    public static Object[] create(Class<?> clazz) {
    1.68 +        Method[] arr = clazz.getMethods();
    1.69 +        Object[] ret = new Object[3 * arr.length];
    1.70 +        int cnt = 0;
    1.71 +        for (Method m : arr) {
    1.72 +            Compare c = m.getAnnotation(Compare.class);
    1.73 +            if (c == null) {
    1.74 +                continue;
    1.75 +            }
    1.76 +            final Run real = new Run(m, false);
    1.77 +            final Run js = new Run(m, true);
    1.78 +            ret[cnt++] = real;
    1.79 +            ret[cnt++] = js;
    1.80 +            ret[cnt++] = new VMTest(m, real, js);
    1.81 +        }
    1.82 +        Object[] r = new Object[cnt];
    1.83 +        for (int i = 0; i < cnt; i++) {
    1.84 +            r[i] = ret[i];
    1.85 +        }
    1.86 +        return r;
    1.87 +    }
    1.88 +
    1.89 +    /** Test that compares the previous results.
    1.90 +     * @throws Throwable 
    1.91 +     */
    1.92 +    @Test(dependsOnGroups = "run") public void compareResults() throws Throwable {
    1.93 +        Object v1 = first.value;
    1.94 +        Object v2 = second.value;
    1.95 +        if (v1 instanceof Number) {
    1.96 +            v1 = ((Number)v1).doubleValue();
    1.97 +        }
    1.98 +        Assert.assertEquals(v2, v1, "Comparing results");
    1.99 +    }
   1.100 +    
   1.101 +    /** Test name.
   1.102 +     * @return name of the tested method followed by a suffix
   1.103 +     */
   1.104 +    @Override
   1.105 +    public String getTestName() {
   1.106 +        return m.getName() + "[Compare]";
   1.107 +    }
   1.108 +
   1.109 +    /** Helper method that inspects the classpath and loads given resource
   1.110 +     * (usually a class file). Used while running tests in Rhino.
   1.111 +     * 
   1.112 +     * @param name resource name to find
   1.113 +     * @return the array of bytes in the given resource
   1.114 +     * @throws IOException I/O in case something goes wrong
   1.115 +     */
   1.116 +    public static byte[] read(String name) throws IOException {
   1.117 +        URL u = null;
   1.118 +        Enumeration<URL> en = VMTest.class.getClassLoader().getResources(name);
   1.119 +        while (en.hasMoreElements()) {
   1.120 +            u = en.nextElement();
   1.121 +        }
   1.122 +        if (u == null) {
   1.123 +            throw new IOException("Can't find " + name);
   1.124 +        }
   1.125 +        try (InputStream is = u.openStream()) {
   1.126 +            byte[] arr;
   1.127 +            arr = new byte[is.available()];
   1.128 +            int offset = 0;
   1.129 +            while (offset < arr.length) {
   1.130 +                int len = is.read(arr, offset, arr.length - offset);
   1.131 +                if (len == -1) {
   1.132 +                    throw new IOException("Can't read " + name);
   1.133 +                }
   1.134 +                offset += len;
   1.135 +            }
   1.136 +            return arr;
   1.137 +        }
   1.138 +    }
   1.139 +   
   1.140 +    public static final class Run implements ITest {
   1.141 +        private final Method m;
   1.142 +        private final boolean js;
   1.143 +        Object value;
   1.144 +        private Invocable code;
   1.145 +        private CharSequence codeSeq;
   1.146 +        private static final Map<Class,Object[]> compiled = new WeakHashMap<Class,Object[]>();
   1.147 +
   1.148 +        private Run(Method m, boolean js) {
   1.149 +            this.m = m;
   1.150 +            this.js = js;
   1.151 +        }
   1.152 +
   1.153 +        private void compileTheCode(Class<?> clazz) throws Exception {
   1.154 +            final Object[] data = compiled.get(clazz);
   1.155 +            if (data != null) {
   1.156 +                code = (Invocable) data[0];
   1.157 +                codeSeq = (CharSequence) data[1];
   1.158 +                return;
   1.159 +            }
   1.160 +            StringBuilder sb = new StringBuilder();
   1.161 +            Bck2Brwsr.generate(sb, VMTest.class.getClassLoader());
   1.162 +
   1.163 +            ScriptEngineManager sem = new ScriptEngineManager();
   1.164 +            ScriptEngine js = sem.getEngineByExtension("js");
   1.165 +            
   1.166 +            sb.append("\nfunction initVM() {"
   1.167 +                + "\n  return bck2brwsr("
   1.168 +                + "\n    function(name) { return org.apidesign.bck2brwsr.vmtest.VMTest.read(name);}"
   1.169 +                + "\n  );"
   1.170 +                + "\n};");
   1.171 +
   1.172 +            Object res = js.eval(sb.toString());
   1.173 +            Assert.assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   1.174 +            code = (Invocable) js;
   1.175 +            codeSeq = sb;
   1.176 +            compiled.put(clazz, new Object[] { code, codeSeq });
   1.177 +        }
   1.178 +
   1.179 +        @Test(groups = "run") public void executeCode() throws Throwable {
   1.180 +            if (js) {
   1.181 +                try {
   1.182 +                    compileTheCode(m.getDeclaringClass());
   1.183 +                    Object vm = code.invokeFunction("initVM");
   1.184 +                    Object inst = code.invokeMethod(vm, "loadClass", m.getDeclaringClass().getName());
   1.185 +                    value = code.invokeMethod(inst, m.getName() + "__" + computeSignature(m));
   1.186 +                } catch (Exception ex) {
   1.187 +                    throw new AssertionError(dumpJS(codeSeq)).initCause(ex);
   1.188 +                }
   1.189 +            } else {
   1.190 +                value = m.invoke(m.getDeclaringClass().newInstance());
   1.191 +            }
   1.192 +        }
   1.193 +        @Override
   1.194 +        public String getTestName() {
   1.195 +            return m.getName() + (js ? "[JavaScript]" : "[Java]");
   1.196 +        }
   1.197 +        
   1.198 +        private static String computeSignature(Method m) {
   1.199 +            StringBuilder sb = new StringBuilder();
   1.200 +            appendType(sb, m.getReturnType());
   1.201 +            for (Class<?> c : m.getParameterTypes()) {
   1.202 +                appendType(sb, c);
   1.203 +            }
   1.204 +            return sb.toString();
   1.205 +        }
   1.206 +        
   1.207 +        private static void appendType(StringBuilder sb, Class<?> t) {
   1.208 +            if (t == null) {
   1.209 +                sb.append('V');
   1.210 +                return;
   1.211 +            }
   1.212 +            if (t.isPrimitive()) {
   1.213 +                int ch = -1;
   1.214 +                if (t == int.class) {
   1.215 +                    ch = 'I';
   1.216 +                }
   1.217 +                if (t == short.class) {
   1.218 +                    ch = 'S';
   1.219 +                }
   1.220 +                if (t == byte.class) {
   1.221 +                    ch = 'B';
   1.222 +                }
   1.223 +                if (t == boolean.class) {
   1.224 +                    ch = 'Z';
   1.225 +                }
   1.226 +                if (t == long.class) {
   1.227 +                    ch = 'J';
   1.228 +                }
   1.229 +                if (t == float.class) {
   1.230 +                    ch = 'F';
   1.231 +                }
   1.232 +                if (t == double.class) {
   1.233 +                    ch = 'D';
   1.234 +                }
   1.235 +                assert ch != -1 : "Unknown primitive type " + t;
   1.236 +                sb.append((char)ch);
   1.237 +                return;
   1.238 +            }
   1.239 +            if (t.isArray()) {
   1.240 +                sb.append("_3");
   1.241 +                appendType(sb, t.getComponentType());
   1.242 +                return;
   1.243 +            }
   1.244 +            sb.append('L');
   1.245 +            sb.append(t.getName().replace('.', '_'));
   1.246 +            sb.append("_2");
   1.247 +        }
   1.248 +    }
   1.249 +    
   1.250 +    static StringBuilder dumpJS(CharSequence sb) throws IOException {
   1.251 +        File f = File.createTempFile("execution", ".js");
   1.252 +        FileWriter w = new FileWriter(f);
   1.253 +        w.append(sb);
   1.254 +        w.close();
   1.255 +        return new StringBuilder(f.getPath());
   1.256 +    }
   1.257 +}