Пример #1
0
        public static JsResult ToJs(ModuleDefinition module, bool verbose = false)
        {
            Func <TypeDefinition, IEnumerable <TypeDefinition> > getSelfAndNestedTypes = null;

            getSelfAndNestedTypes = type => type.NestedTypes.SelectMany(x => getSelfAndNestedTypes(x)).Concat(type);
            var exportedTypes = module.Types
                                .SelectMany(x => getSelfAndNestedTypes(x))
                                .Where(x => x.GetCustomAttribute <JsExportAttribute>() != null)
                                .ToArray();

            if (!exportedTypes.Any())
            {
                throw new InvalidOperationException("No types exported");
            }
            var exportedMethods = exportedTypes.SelectMany(x => x.Methods.Where(m => m.IsPublic)).ToArray();
            var nestedTypes     = exportedTypes.Where(x => x.IsNested).Select(x => "Nested type: " + x.FullName).ToArray();
            var privateTypes    = exportedTypes.Where(x => !(x.IsPublic || x.IsNestedPublic)).Select(x => "Private type: " + x.FullName).ToArray();
            var genTypes        = exportedTypes.Where(x => x.HasGenericParameters).Select(x => "Generic type: " + x.FullName).ToArray();
            var genMethods      = exportedMethods.Where(x => x.HasGenericParameters).Select(x => "Generic method: " + x.FullName).ToArray();
            var errors          = nestedTypes.Concat(privateTypes).Concat(genTypes).Concat(genMethods).ToArray();

            if (errors.Any())
            {
                var msg = string.Format("Export errors:{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, errors));
                throw new InvalidOperationException(msg);
            }
            var js = Js.CreateFrom(exportedMethods, verbose);

            return(js);
        }
Пример #2
0
 public static JsResult ToJs(MethodInfo methodInfo, bool verbose = false)
 {
     return(Js.CreateFrom(GetMethod(methodInfo), verbose));
 }
Пример #3
0
        protected void Start(Action action, Func <IWebDriver, bool> preExtraTest = null, Func <IWebDriver, bool> postExtraTest = null, TimeSpan?timeout = null)
        {
            if (timeout == null)
            {
                timeout = TimeSpan.FromSeconds(1000);
            }
            var method   = CecilHelper.GetMethod(action.Method);
            var jsResult = Js.CreateFrom(method, this.Verbose, true);
            var js       = jsResult.Js;

            if (this.Verbose)
            {
                Console.WriteLine(js);
            }
            var completeHtml = this.MakeHtml(js);

            using (var http = new HttpListener()) {
                http.Prefixes.Add("http://localhost:7890/");
                http.Start();
                AsyncCallback cb = null;
                cb = asyncState => {
                    if (!http.IsListening)
                    {
                        return;
                    }
                    HttpListenerContext context;
                    try {
                        context = http.EndGetContext(asyncState);
                    } catch (HttpListenerException) {
                        return;
                    } catch (ObjectDisposedException) {
                        return;
                    }
                    using (var response = context.Response) {
                        var    output = response.OutputStream;
                        var    path   = context.Request.Url.AbsolutePath;
                        string responseString;
                        if (path == "/")
                        {
                            responseString = completeHtml;
                        }
                        else
                        {
                            var request = context.Request;
                            using (var ms = new MemoryStream()) {
                                request.InputStream.CopyTo(ms);
                                var bytes = ms.ToArray();
                                Func <byte[], string> fn;
                                urls.TryGetValue(path, out fn);
                                responseString = fn != null?fn(bytes) : "";
                            }
                        }
                        var bHtml = Encoding.UTF8.GetBytes(responseString);
                        response.ContentLength64 = bHtml.LongLength;
                        output.Write(bHtml, 0, bHtml.Length);
                    }
                    http.BeginGetContext(cb, null);
                };
                http.BeginGetContext(cb, null);
                //var usingNamespace = NamespaceSetup.Chrome != null;
                //var chrome = usingNamespace ? NamespaceSetup.Chrome : new ChromeDriver();
                using (var chrome = NamespaceSetup.ChromeService != null ?
                                    new RemoteWebDriver(NamespaceSetup.ChromeService.ServiceUrl, DesiredCapabilities.Chrome()) :
                                    new ChromeDriver()) {
                    try {
                        this.jsonTypeMap = jsResult.TypeMap;
                        chrome.Manage().Timeouts().ImplicitlyWait(timeout.Value);
                        chrome.Url = "http://localhost:7890/";
                        bool isPass = true;
                        if (preExtraTest != null)
                        {
                            isPass = preExtraTest(chrome);
                        }
                        if (isPass)
                        {
                            IWebElement done;
                            string      doneText = "";
                            try {
                                done     = chrome.FindElementById("__done__");
                                doneText = done.Text;
                            } catch (NoSuchElementException) {
                                isPass = false;
                            } catch {
                                isPass = false;
                            }
                            isPass = doneText == "pass";
                            if (!isPass)
                            {
                                if (doneText.StartsWith("ex:"))
                                {
                                    throw new Exception(doneText.Substring(3));
                                }
                                if (doneText.StartsWith("onerror:"))
                                {
                                    throw new Exception(doneText.Substring(8));
                                }
                            }
                            if (isPass && postExtraTest != null)
                            {
                                isPass = postExtraTest(chrome);
                            }
                        }
                        Assert.That(isPass, Is.True);
                    } finally {
                        //if (!usingNamespace) {
                        chrome.Quit();
                        chrome.Dispose();
                        //}
                        this.jsonTypeMap = null;
                    }
                }
                http.Abort();
            }
        }
Пример #4
0
 public static JsResult ToJs(MethodReference method, bool verbose = false)
 {
     return(Js.CreateFrom(method, verbose));
 }
Пример #5
0
        protected void Test(Delegate d, object knownResult = null, bool knownResultNull = false)
        {
            var mi = d.Method;
            //var stackTrace = new StackTrace();
            //var testMethod = stackTrace.GetFrame(1).GetMethod().Name;
            //Console.WriteLine("Test++ {0}", testMethod);
            var method = CecilHelper.GetMethod(d);
            var js     = Js.CreateFrom(method, this.Verbose, true).Js;

            if (this.Verbose)
            {
                Console.WriteLine(js);
            }
            var testDefaultParamGen = mi.GetCustomAttribute <ParamAttribute>()
                                      ?? mi.DeclaringType.GetCustomAttribute <ParamAttribute>()
                                      ?? defaultParamGen;
            var withinAttr        = mi.GetCustomAttribute <WithinAttribute>();
            var withinUlpsAttr    = mi.GetCustomAttribute <WithinUlpsAttribute>();
            var withinPercentAttr = mi.GetCustomAttribute <WithinPercentAttribute>();
            var icAttr            = mi.GetCustomAttribute <IterationCountAttribute>();
            var minIterations     = mi.GetParameters().Max(x =>
                                                           (x.GetCustomAttribute <ParamAttribute>() ?? testDefaultParamGen).MinIterations);
            int iterationCount;

            if (icAttr != null)
            {
                iterationCount = icAttr.IterationCount;
            }
            else
            {
                iterationCount = method.Parameters.Any() ? defaultTestIterations : 1;
            }
            if (iterationCount < minIterations)
            {
                iterationCount = minIterations.Value;
            }
            var range = Enumerable.Range(0, iterationCount);
            var args  = range.Select(i => this.CreateArgs(mi, i, testDefaultParamGen)).ToArray();

            var runResults = range.Select(i => {
                object r    = null;
                Exception e = null;
                try {
                    r = d.DynamicInvoke(args[i]);
                } catch (TargetInvocationException ex) {
                    e = ex.InnerException;
                }
                if (knownResult != null || knownResultNull)
                {
                    Assert.That(r, Is.EqualTo(knownResult));
                }
                return(Tuple.Create(r, e));
            }).ToArray();

            var usingNamespace = NamespaceSetup.Chrome != null;
            var chrome         = usingNamespace ? NamespaceSetup.Chrome : new ChromeDriver();

            try {
                for (int i = 0; i < args.Length; i++)
                {
                    var arg = args[i];
                    if (!mi.IsStatic)
                    {
                        arg = arg.Prepend(null).ToArray();
                    }
                    var jsArgs = string.Join(", ", arg.Select(x => this.ConvertArgToJavascript(x)));
                    //Console.WriteLine("JS args: '{0}'", jsArgs);
                    var jsCall   = @"
var r;
try {
    r = main(" + jsArgs + @");
    console.log(r);
} catch (e) {
    return {exception:[e._.$$TypeNamespace, e._.$$TypeName, e.$$_message]};
}
if (typeof r === 'number') {
    if (isNaN(r)) {
        return 'NaN';
    }
    if (r === Number.POSITIVE_INFINITY) {
        return '+Infinity';
    }
    if (r === Number.NEGATIVE_INFINITY) {
        return '-Infinity';
    }
    return r.toString();
}
return r;
";
                    var jsResult = chrome.ExecuteScript(js + jsCall);
                    if (jsResult != null && jsResult is Dictionary <string, object> )
                    {
                        // Exception
                        Assert.That(runResults[i].Item1, Is.Null, "JS threw exception, but exception not expected");
                        var jsExInfo       = ((ICollection <object>)((Dictionary <string, object>)jsResult)["exception"]).Cast <string>().ToArray();
                        var jsExType       = jsExInfo[0] + "." + jsExInfo[1];
                        var expectedExType = runResults[i].Item2.GetType().FullName;
                        Assert.That(jsExType, Is.EqualTo(expectedExType));
                    }
                    else
                    {
                        var returnTypeCode = Type.GetTypeCode(d.Method.ReturnType);
                        if (jsResult != null && jsResult.GetType() != d.Method.ReturnType)
                        {
                            switch (returnTypeCode)
                            {
                            case TypeCode.Int64: {
                                var array = (IList <object>)jsResult;
                                var hi    = Convert.ToUInt64(array[0]);
                                var lo    = Convert.ToUInt64(array[1]);
                                jsResult = (long)(((ulong)hi) << 32 | (ulong)lo);
                            }
                            break;

                            case TypeCode.UInt64: {
                                var array = (IList <object>)jsResult;
                                var hi    = Convert.ToUInt64(array[0]);
                                var lo    = Convert.ToUInt64(array[1]);
                                jsResult = ((ulong)hi) << 32 | (ulong)lo;
                            }
                            break;

                            case TypeCode.Single:
                                switch (jsResult as string)
                                {
                                case "NaN": jsResult = Single.NaN; break;

                                case "+Infinity": jsResult = Single.PositiveInfinity; break;

                                case "-Infinity": jsResult = Single.NegativeInfinity; break;

                                default: jsResult = Single.Parse(jsResult as string); break;
                                }
                                break;

                            case TypeCode.Double:
                                switch (jsResult as string)
                                {
                                case "NaN": jsResult = Double.NaN; break;

                                case "+Infinity": jsResult = Double.PositiveInfinity; break;

                                case "-Infinity": jsResult = Double.NegativeInfinity; break;

                                default: jsResult = Double.Parse(jsResult as string); break;
                                }
                                break;

                            case TypeCode.Char:
                                jsResult = (char)int.Parse(jsResult as string);
                                break;

                            default:
                                jsResult = Convert.ChangeType(jsResult, d.Method.ReturnType);
                                break;
                            }
                        }
                        Assert.That(runResults[i].Item2, Is.Null, "Exception expected in JS, but not thrown");
                        EqualConstraint    equalTo  = Is.EqualTo(runResults[i].Item1);
                        IResolveConstraint expected = equalTo;
                        if (withinAttr != null)
                        {
                            expected = equalTo.Within(withinAttr.Delta);
                        }
                        else if (withinUlpsAttr != null)
                        {
                            expected = equalTo.Within(withinUlpsAttr.Ulps).Ulps;
                        }
                        else if (withinPercentAttr != null)
                        {
                            expected = equalTo.Within(withinPercentAttr.Percent).Percent;
                        }
                        else
                        {
                            switch (returnTypeCode)
                            {
                            case TypeCode.Single:
                                // Always allow a little inaccuracy with Singles
                                expected = equalTo.Within(0.0001).Percent;
                                break;

                            case TypeCode.Double:
                                expected = equalTo.Within(0.0001).Percent;
                                break;
                            }
                        }
                        Assert.That(jsResult, expected);
                    }
                }
            } finally {
                if (!usingNamespace)
                {
                    chrome.Quit();
                    chrome.Dispose();
                }
            }

            //Console.WriteLine("Test-- {0}", testMethod);
        }