Beispiel #1
0
        public void EvaluationReturnsEmptyArraysWhenNull()
        {
            var result = TargetView.EvaluateScript <int[]>("null");

            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.Length);
        }
 public async Task EvaluateSimpleScript()
 {
     await Run(() => {
         var result = TargetView.EvaluateScript <int>("2+1");
         Assert.AreEqual(3, result);
     });
 }
Beispiel #3
0
        public void EvaluationTimeoutIsThrown()
        {
            var exception = Assert.Throws <WebView.JavascriptException>(
                () => TargetView.EvaluateScript <int>("var start = new Date().getTime(); while((new Date().getTime() - start) < 150);",
                                                      TimeSpan.FromMilliseconds(50)));

            Assert.True(exception.Message.Contains("Timeout"));
        }
        public void JavascriptEngineInitializationTimeout()
        {
            LoadAndWaitReady("<html><body></body></html>");
            var exception = Assert.Throws <WebView.JavascriptException>(() => TargetView.EvaluateScript <int>("1", TimeSpan.FromSeconds(1)));

            Assert.IsNotNull(exception);
            Assert.IsTrue(exception.Message.Contains("not initialized"));
        }
 public async Task EvaluationReturnsEmptyArraysWhenNull()
 {
     await Run(() => {
         var result = TargetView.EvaluateScript <int[]>("null");
         Assert.IsNotNull(result);
         Assert.AreEqual(0, result.Length);
     });
 }
Beispiel #6
0
 public async Task EvaluationTimeoutIsThrown()
 {
     await Run(async() => {
         var exception = await Assertions.AssertThrows <JavascriptException>(
             async() => await TargetView.EvaluateScript <int>("var start = new Date().getTime(); while((new Date().getTime() - start) < 150);", timeout: TimeSpan.FromMilliseconds(50)));
         StringAssert.Contains("Timeout", exception.Message);
     });
 }
Beispiel #7
0
        public void ResourceRequestIsCanceled()
        {
            TargetView.BeforeResourceLoad += (resourceHandler) => resourceHandler.Cancel();
            LoadAndWaitReady(HtmlWithResource);

            var failed = TargetView.EvaluateScript <bool>("scriptFailed"); // check that the value of x is what was declared before in the resource

            Assert.True(failed);
        }
Beispiel #8
0
        public void InterceptedResourceRequestIsLoaded()
        {
            TargetView.BeforeResourceLoad += (resourceHandler) => resourceHandler.RespondWith(ToStream("scriptLoaded = true"), "js"); // declare x
            LoadAndWaitReady(HtmlWithResource);

            var loaded = TargetView.EvaluateScript <bool>("scriptLoaded"); // check that the value of x is what was declared before in the resource

            Assert.True(loaded);
        }
Beispiel #9
0
        public void EmbeddedFilesWithDashesInFilenameLoad()
        {
            var embeddedResourceUrl = new ResourceUrl(GetType().Assembly, "Resources", "dash-folder", "EmbeddedJavascriptFile-With-Dashes.js");

            LoadAndWaitReady($"<html><script src='{embeddedResourceUrl}'></script></html>");
            var embeddedFileLoaded = TargetView.EvaluateScript <bool>("embeddedFileLoaded");

            Assert.IsTrue(embeddedFileLoaded);
        }
Beispiel #10
0
 public async Task EvaluateAfterInitialization()
 {
     await Run(async() => {
         await Load("<html><script></script><body>1</body></html>");
         await Load("<html><script></script><body>2</body></html>");
         var result = await TargetView.EvaluateScript <int>("1", timeout: TimeSpan.FromSeconds(30));
         Assert.AreEqual(result, 1);
     });
 }
Beispiel #11
0
        public async Task HtmlIsWellEncoded()
        {
            await Run(async() => {
                const string BodyContent = "some text and a double byte char '●'";
                await Load($"<html><script>;</script><body>{BodyContent}</body></html>");

                var body = TargetView.EvaluateScript <string>("document.body.innerText");
                Assert.AreEqual(BodyContent, body);
            });
        }
Beispiel #12
0
        public async Task EmbeddedFilesWithDashesInFilenameLoad()
        {
            await Run(async() => {
                var embeddedResourceUrl = new ResourceUrl(GetType().Assembly, "Resources", "dash-folder", "EmbeddedJavascriptFile-With-Dashes.js");
                await Load($"<html><script src='{embeddedResourceUrl}'></script></html>");

                var embeddedFileLoaded = TargetView.EvaluateScript <bool>("embeddedFileLoaded");
                Assert.IsTrue(embeddedFileLoaded);
            });
        }
Beispiel #13
0
        public void UnhandledExceptionEventIsCalled()
        {
            const string ExceptionMessage = "nooo";

            Exception exception = null;

            var controlUnhandled    = false;
            var dispatcherUnhandled = false;
            var markAsHandled       = true;

            DispatcherUnhandledExceptionEventHandler unhandledDispatcherException = (o, e) => {
                exception           = e.Exception;
                dispatcherUnhandled = true;
                e.Handled           = true;
            };

            Action <int> assertResult = (result) => {
                Assert.NotNull(exception);
                Assert.IsTrue(exception.Message.Contains(exception.Message));
                Assert.AreEqual(2, result, "Result should not be affected");
            };

            TargetView.Dispatcher.UnhandledException += unhandledDispatcherException;

            WithUnhandledExceptionHandling(() => {
                try {
                    TargetView.ExecuteScript($"throw new Error('{ExceptionMessage}')");
                    var result = TargetView.EvaluateScript <int>("1+1"); // force exception to occur

                    assertResult(result);
                    Assert.IsTrue(controlUnhandled);
                    Assert.IsFalse(dispatcherUnhandled);

                    controlUnhandled = false;
                    markAsHandled    = false;

                    TargetView.ExecuteScript($"throw new Error('{ExceptionMessage}')");
                    result = TargetView.EvaluateScript <int>("1+1"); // force exception to occur

                    WaitFor(() => dispatcherUnhandled);

                    assertResult(result);
                    Assert.IsTrue(controlUnhandled);
                    Assert.IsTrue(dispatcherUnhandled);
                } finally {
                    TargetView.Dispatcher.UnhandledException -= unhandledDispatcherException;
                }
            },
                                           e => {
                exception        = e;
                controlUnhandled = true;
                return(markAsHandled);
            });
        }
Beispiel #14
0
        public void EvaluationErrorsReturnsDetails()
        {
            var exception = Assert.Throws <WebView.JavascriptException>(() => TargetView.EvaluateScript <int>("(function foo() { (function bar() { throw new Error('ups'); })() })()"));

            Assert.AreEqual("Error: ups", exception.Message);
            var stack = exception.StackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            Assert.Greater(stack.Length, 2);
            Assert.True(stack.ElementAt(0).StartsWith("   at bar"));
            Assert.True(stack.ElementAt(1).StartsWith("   at foo"));
        }
Beispiel #15
0
        public void ComplexObjectsEvaluation()
        {
            var result = TargetView.EvaluateScript <TestObject>("({ Name: 'Snows', Age: 32, Parent: { Name: 'Snows Parent', Age: 60 }, Kind: 2 })");

            Assert.IsNotNull(result);
            Assert.AreEqual("Snows", result.Name);
            Assert.AreEqual(32, result.Age);
            Assert.IsNotNull(result.Parent);
            Assert.AreEqual("Snows Parent", result.Parent.Name);
            Assert.AreEqual(60, result.Parent.Age);
            Assert.AreEqual(Kind.C, result.Kind);
        }
        public async Task EvaluationErrorsContainsMessageAndJavascriptStack()
        {
            await Run(() => {
                var exception = Assert.Throws <JavascriptException>(() => TargetView.EvaluateScript <int>("(function foo() { (function bar() { throw new Error('ups'); })() })()"));

                Assert.AreEqual("Error: ups", exception.Message);
                var stack = exception.StackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                Assert.Greater(stack.Length, 2);
                StringAssert.StartsWith("   at bar in about", stack.ElementAt(0));
                StringAssert.StartsWith("   at foo in about", stack.ElementAt(1));
            });
        }
        public async Task ScriptsWithComplexSyntaxAreEvaluated()
        {
            await Run(() => {
                var result = TargetView.EvaluateScript <int>("2+1 // some comments");
                Assert.AreEqual(3, result);

                result = TargetView.EvaluateScript <int>("var x = 1; 5");
                Assert.AreEqual(5, result);

                var resultObj = TargetView.EvaluateScript <TestObject>("({ Name: 'Snows', Age: 32})");
                Assert.IsNotNull(resultObj);
            });
        }
Beispiel #18
0
        public void HtmlIsWellEncoded()
        {
            const string BodyContent = "some text and a double byte char '●'";
            var          navigated   = false;

            TargetView.Navigated += (_, __) => navigated = true;

            TargetView.LoadHtml($"<html><script>;</script><body>{BodyContent}</body></html>");
            WaitFor(() => navigated);
            var body = TargetView.EvaluateScript <string>("document.body.innerText");

            Assert.AreEqual(BodyContent, body);
        }
Beispiel #19
0
 public async Task JavascriptEvaluationOnNavigatedDoesNotBlock()
 {
     await Run(async() => {
         var taskCompletionSource = new TaskCompletionSource <bool>();
         TargetView.Navigated    += delegate {
             TargetView.EvaluateScript <int>("1+1");
             taskCompletionSource.SetResult(true);
         };
         await Load("<html><body></body></html>");
         var navigatedCalled = await taskCompletionSource.Task;
         Assert.IsTrue(navigatedCalled, "JS evaluation on navigated event is blocked!");
     });
 }
Beispiel #20
0
        public void JavascriptEvaluationOnNavigatedDoesNotBlock()
        {
            var navigated = false;

            TargetView.Navigated += _ => {
                TargetView.EvaluateScript <int>("1+1");
                navigated = true;
            };
            LoadAndWaitReady("<html>><body></body></html>");

            WaitFor(() => navigated);
            Assert.IsTrue(navigated);
        }
Beispiel #21
0
        public async Task ResourceFile()
        {
            await Run(async() => {
                var embeddedResourceUrl = new ResourceUrl(GetType().Assembly, "Resources", "ResourceJavascriptFile.js");
                await Load($"<html><script src='{embeddedResourceUrl}'></script></html>");

                var resourceFileLoaded = TargetView.EvaluateScript <bool>("resourceFileLoaded");
                Assert.IsTrue(resourceFileLoaded);

                Stream missingResource = null;
                Assert.DoesNotThrow(() => missingResource = ResourcesManager.TryGetResourceWithFullPath(GetType().Assembly, new[] { "Resources", "Missing.txt" }));
                Assert.IsNull(missingResource);
            });
        }
Beispiel #22
0
        public async Task ResourceRequestIsCanceled()
        {
            await Run(async() => {
                var taskCompletionSource       = new TaskCompletionSource <bool>();
                TargetView.BeforeResourceLoad += (resourceHandler) => {
                    resourceHandler.Cancel();
                    taskCompletionSource.SetResult(true);
                };
                await Load(HtmlWithResource);
                await taskCompletionSource.Task;

                var failed = TargetView.EvaluateScript <bool>("scriptFailed"); // check that the value of x is what was declared before in the resource
                Assert.IsTrue(failed);
            });
        }
Beispiel #23
0
        public async Task InterceptedResourceRequestIsLoaded()
        {
            await Run(async() => {
                var taskCompletionSource       = new TaskCompletionSource <bool>();
                TargetView.BeforeResourceLoad += (resourceHandler) => {
                    resourceHandler.RespondWith(ToStream("scriptLoaded = true"), "js"); // declare x
                    taskCompletionSource.SetResult(true);
                };
                await Load(HtmlWithResource);
                await taskCompletionSource.Task;

                var loaded = TargetView.EvaluateScript <bool>("scriptLoaded"); // check that the value of x is what was declared before in the resource
                Assert.IsTrue(loaded);
            });
        }
        public void JavascriptEvaluationOnIframe()
        {
            LoadAndWaitReady(
                "<html>" +
                "<body>" +
                "<script>" +
                "var x = 1;" +
                "</script>" +
                "<iframe name='test' srcdoc='<html><body><script>var y = 2;</script></body></html>'></iframe>" +
                "</body>" +
                "</html>"
                );
            var x = TargetView.EvaluateScript <int>("x", "");
            var y = TargetView.EvaluateScript <int>("y", "test");

            Assert.AreEqual(1, x);
            Assert.AreEqual(2, y);
        }
        public void RegisteredJsObjectMethodExecutesInDispatcherThreadWithoutBlocking()
        {
            const string DotNetObject   = "DotNetObject";
            bool         functionCalled = false;

            Func <int> functionToCall = () => {
                TargetView.EvaluateScript <int>("1+1");
                functionCalled = true;
                return(1);
            };

            TargetView.RegisterJavascriptObject(DotNetObject, functionToCall, executeCallsInUI: true);
            LoadAndWaitReady("<html><script>function test() { DotNetObject.invoke(); return 1; }</script><body></body></html>");

            var result = TargetView.EvaluateScriptFunction <int>("test");

            WaitFor(() => functionCalled, DefaultTimeout);
            Assert.AreEqual(1, result);
        }
Beispiel #26
0
        public async Task JavascriptEvaluationOnIframe()
        {
            await Run(async() => {
                await Load(
                    "<html>" +
                    "<body>" +
                    "<script>" +
                    "var x = 1;" +
                    "</script>" +
                    "<iframe name='test' srcdoc='<html><body><script>var y = 2;</script></body></html>'></iframe>" +
                    "</body>" +
                    "</html>"
                    );

                var x = await TargetView.EvaluateScript <int>("x", "");
                var y = await TargetView.EvaluateScript <int>("test.y", "");
                Assert.AreEqual(1, x);
                Assert.AreEqual(2, y);
            });
        }
        public async Task RegisteredJsObjectMethodExecutesInDispatcherThreadWithoutBlocking()
        {
            await Run(async() => {
                const string DotNetObject = "DotNetObject";
                var taskCompletionSource  = new TaskCompletionSource <bool>();

                Func <int> functionToCall = () => {
                    TargetView.EvaluateScript <int>("1+1");
                    taskCompletionSource.SetResult(true);
                    return(1);
                };

                TargetView.RegisterJavascriptObject(DotNetObject, functionToCall, executeCallsInUI: true);
                await Load("<html><script>function test() { DotNetObject.invoke(); return 1; }</script><body></body></html>");

                var result = await TargetView.EvaluateScriptFunction <int>("test");
                await taskCompletionSource.Task;
                Assert.AreEqual(1, result);
            });
        }
Beispiel #28
0
        public void ExecutionOrderIsRespected()
        {
            try {
                TargetView.ExecuteScript("x = ''");
                var expectedResult = "";
                // queue 10000 scripts
                for (var i = 0; i < 10000; i++)
                {
                    TargetView.ExecuteScript($"x += '{i},'");
                    expectedResult += i + ",";
                }
                var result = TargetView.EvaluateScript <string>("x");
                Assert.AreEqual(expectedResult, result);

                TargetView.ExecuteScript("x = '-'");
                result = TargetView.EvaluateScript <string>("x");
                Assert.AreEqual("-", result);
            } finally {
                TargetView.EvaluateScript <bool>("delete x");
            }
        }
Beispiel #29
0
        public async Task LoadCustomScheme()
        {
            await Run(async() => {
                var embeddedResourceUrl = new ResourceUrl(GetType().Assembly, "Resources", "EmbeddedHtml.html");

                var taskCompletionSource = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);

                void OnNavigated(string url, string frameName)
                {
                    if (url != UrlHelper.AboutBlankUrl)
                    {
                        TargetView.Navigated -= OnNavigated;
                        taskCompletionSource.SetResult(true);
                    }
                }
                TargetView.Navigated += OnNavigated;
                TargetView.LoadResource(embeddedResourceUrl);
                await taskCompletionSource.Task;

                var content = await TargetView.EvaluateScript <string>("document.documentElement.innerText");
                Assert.AreEqual("test", content);
            });
        }
        public async Task UnhandledExceptionEventIsCalled()
        {
            await Run(() => {
                const string ExceptionMessage = "nooo";

                var taskCompletionSource = new TaskCompletionSource <Exception>();

                WithUnhandledExceptionHandling(() => {
                    TargetView.ExecuteScript($"throw new Error('{ExceptionMessage}')");

                    var result = TargetView.EvaluateScript <int>("1+1"); // force exception to occur
                    Assert.AreEqual(2, result, "Result should not be affected");

                    var exception = taskCompletionSource.Task.Result;

                    StringAssert.Contains(ExceptionMessage, exception.Message);
                },
                                               e => {
                    taskCompletionSource.SetResult(e);
                    return(true);
                });
            });
        }