Beispiel #1
0
        public static async Task AddEmbeddedScriptInsideEmbedded()
        {
            var resources = Mocks.ResourceProvider(
                "http://localhost",
                Mocks.Page(@"
			document.addEventListener(""DOMNodeInserted"", function(e){
console.log('node added');
}, false);

var d = document.createElement('script');
d.id='aaa';
d.async = true;
d.innerHTML = ""console.log('in new script');console.log(document.getElementById('aaa') != null ? 'ok' : 'null');"";
d.onload = function(){console.log('onload');};
document.head.appendChild(d);
console.log('afterappend');"));
            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resources, console);

            await engine.OpenUrl("http://localhost");

            Thread.Sleep(1000);

            CollectionAssert.AreEqual(new[] { "in new script", "ok", "node added", "afterappend" }, console.LogHistory);
        }
Beispiel #2
0
        public static async Task AddScriptAsync()
        {
            var resources = Mocks.ResourceProvider(
                "http://localhost",
                Mocks.Page(@"
			document.addEventListener(""DOMNodeInserted"", function(e){
console.log('nodeadded');
}, false);

var d = document.createElement('script');
d.id='aaa';
d.async = true;
d.src = ""http://localhost/script.js"";
d.onload = function(){console.log('onload');};
document.head.appendChild(d);
console.log('afterappend');")).Resource("http://localhost/script.js", "console.log('in new script');");

            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resources, console);

            await engine.OpenUrl("http://localhost");

            Thread.Sleep(1000);
            Assert.AreEqual("nodeadded,afterappend,in new script,onload",
                            string.Join(",", console.LogHistory));
        }
Beispiel #3
0
        public static async Task XmlHttpRequestSend()
        {
            var resourceProvider = Mocks.ResourceProvider("http://localhost", Mocks.Page(
                                                              @"var client = new XMLHttpRequest();
client.onreadystatechange = function () {
  console.log(this.readyState);
  if(this.readyState == this.DONE) {
		console.log(this.status);
    if(this.status == 200 ) {
		console.log(this.responseText);
    }
  }
};
client.open(""GET"", ""http://localhost/unicorn.xml"", false);
client.send();"))
                                   .Resource("http://localhost/unicorn.xml", "hello");

            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resourceProvider, console);
            await engine.OpenUrl("http://localhost");

            Thread.Sleep(1000);

            Mock.Get(resourceProvider).Verify(x => x.SendRequestAsync(It.IsAny <Request>()), Times.Exactly(2));
            CollectionAssert.AreEqual(new object[] { 1.0d, 4.0d, 200.0d, "hello" }, console.LogHistory);
        }
Beispiel #4
0
        public void Post()
        {
            var resourceProvider = Mock.Of <IResourceProvider>()
                                   .Resource("http://localhost",
                                             "<html><head><script> " + R.JQueryJs +
                                             " </script><script src='test.js' defer/></head><body><div id='uca'></div></body></html>")
                                   .Resource("http://localhost/test.js",
                                             "$.post('http://localhost/data').done(function(x){console.log(x);});")
                                   .Resource("http://localhost/data", "OK");

            var console = new Mock <IConsole>();
            var engine  = TestingEngine.BuildJint(resourceProvider, console.Object);

            var log    = new List <string>();
            var signal = new ManualResetEvent(false);

            console.Setup(x => x.Log(It.IsAny <string>(), It.IsAny <object[]>())).Callback <string, object[]>((msg, _) =>
            {
                System.Console.WriteLine(msg);
                log.Add(msg);
                signal.Set();
            });

            engine.OpenUrl("http://localhost");
            Assert.IsTrue(signal.WaitOne(10000));
            CollectionAssert.AreEqual(new[] { "OK" }, log);
        }
Beispiel #5
0
        public static async Task AddScriptThatAddsScriptModifyingDom()
        {
            var modifyingScript = "var form = document.body.getElementsByTagName('form')[0];" +
                                  " var div = document.createElement('div');" +
                                  " div.name = 'generatedDiv';   " +
                                  "form.appendChild(document.createElement('div'));";

            var scriptThatAddsScript =
                $@"var script = document.createElement('script');
				script.text = ""{modifyingScript}"";
				document.body.getElementsByTagName('form')[0].appendChild(script);"                ;

            var accesingScript = @"var div = document.getElementsByName('generatedDiv');
			                     console.log(div != null);"            ;

            var resourceProvider = Mocks.ResourceProvider("http://localhost",
                                                          $"<html><body><form><script id=adding>{scriptThatAddsScript}</script><script id=accessing>{accesingScript}</script></form></body></html>");

            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resourceProvider, console);

            var page = await engine.OpenUrl("http://localhost");

            page.Assert(x => x.Document.Body.GetElementsByTagName("form")[0].ChildNodes.Count == 4);

            Assert.AreEqual(new[] { true }, console.LogHistory);
        }
Beispiel #6
0
        public void LogonToKwintoError()
        {
            var engine = TestingEngine.BuildJint();

            engine.LogEvents();
            engine.OpenUrl("http://localhost:2930").Wait(timeout);

            var logonButton = engine.WaitId("logon") as HtmlElement;

            Thread.Sleep(5000);

            var userName = engine.Document.GetElementById("UserName") as HtmlInputElement;
            var password = engine.Document.GetElementById("Password") as HtmlInputElement;

            Assert.IsNotNull(logonButton, "LogonButton");
            Assert.IsNotNull(userName, "UserName");
            Assert.IsNotNull(password, "Password");

            userName.EnterText("admin");
            password.EnterText("b");
            logonButton.Click();

            var error = engine.WaitId("validationError");

            Assert.IsNotNull(error, "error");
            System.Console.WriteLine(error.InnerHTML);
        }
Beispiel #7
0
        public void LogonToOkkam()
        {
            var engine = TestingEngine.BuildJint();

            engine.LogEvents();
            engine.OpenUrl("http://okkamtech.com").Wait(timeout);
            //engine.OpenUrl("http://localhost:2930");

            var logonButton = engine.WaitId("logon") as HtmlElement;

            Thread.Sleep(5000);

            var userName = engine.Document.GetElementById("UserName") as HtmlInputElement;
            var password = engine.Document.GetElementById("Password") as HtmlInputElement;

            Assert.IsNotNull(logonButton, "LogonButton");
            Assert.IsNotNull(userName, "UserName");
            Assert.IsNotNull(password, "Password");

            userName.Value = "a";
            password.Value = "b";
            logonButton.Click();

            var error = engine.WaitId("validationError");

            Assert.IsNotNull(error, "error");
        }
Beispiel #8
0
        public async Task Smoke()
        {
            var engine = TestingEngine.BuildJint("<html><head><script> " + R.JQueryJs + " </script></head><body></body></html>");

            engine.ScriptExecutor.OnException += exception => System.Console.WriteLine(exception);
            await engine.OpenUrl("http://localhost");
        }
Beispiel #9
0
        public void XmlHttpRequestUserAgent()
        {
            var httpResourceProvider = Mocks.HttpResourceProvider()
                                       .Resource("http://localhost/", @"<html><script>
		
function reqListener () {
		console.log(this.responseText);
}
		var oReq = new XMLHttpRequest();
		oReq.onload = reqListener;
		oReq.open('get', 'data.txt', false);
		oReq.send();</script></html>"        )
                                       .Resource("http://localhost/data.txt", "data!");

            var resourceProvider = new ResourceProvider(httpResourceProvider, null);

            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resourceProvider, console);

            ((Navigator)engine.Window.Navigator).UserAgent = "My favorite browser";

            engine.OpenUrl("http://localhost").Wait();

            Assert.AreEqual(new[] { "data!" }, console.LogHistory);
            Assert.AreEqual(2, httpResourceProvider.History.Count);
            Assert.AreEqual("My favorite browser", httpResourceProvider.History[0].Headers["User-Agent"]);
            Assert.AreEqual("My favorite browser", httpResourceProvider.History[1].Headers["User-Agent"]);
        }
Beispiel #10
0
        public void SendCookies()
        {
            var index  = "<html><head><script>document.cookie = 'name=ivan'</script><script src='test.js'/>";
            var script = "console.log(document.cookie)";

            var requests = new List <Request>();

            var resourceProvider = Mock.Of <IResourceProvider>();

            Mock.Get(resourceProvider).Setup(x => x.SendRequestAsync(It.IsAny <Request>()))
            .Returns <Request>(req =>
            {
                requests.Add(req);
                return(Task.Run(() =>
                                req.Url.ToString() == "http://localhost/"
                                                        ? new Response("text/html", new MemoryStream(Encoding.UTF8.GetBytes(index)))
                                                        : req.Url.ToString() == "http://localhost/test.js"
                                                                ? new Response("text/html", new MemoryStream(Encoding.UTF8.GetBytes(script)))
                                                                : (IResource)null));
            });

            var engine = TestingEngine.BuildJint(resourceProvider);

            engine.OpenUrl("http://localhost").Wait();

            Assert.AreEqual(2, requests.Count, "requests count");
            Assert.IsNotNull(requests[1].Cookies);
            Assert.AreEqual(1, requests[1].Cookies.Count);
            Assert.AreEqual("ivan", requests[1].Cookies.GetCookies(new Uri("http://localhost/"))["name"].Value);
        }
Beispiel #11
0
        public async Task LoadAndRunScriptAddedInRuntime()
        {
            var resourceProvider =
                Mocks.ResourceProvider("http://localhost/script.js", "console.log('hello');")
                .Resource("http://localhost", "<html><head></head></html>");

            var signal  = new ManualResetEvent(false);
            var console = new Mock <IConsole>();

            console.Setup(x => x.Log(It.IsAny <string>())).Callback(() => signal.Set());

            var engine = TestingEngine.BuildJint(resourceProvider, console.Object);

            var page = await engine.OpenUrl("http://localhost");

            var script = (HtmlScriptElement)page.Document.CreateElement("script");

            script.Src = "http://localhost/script.js";
            page.Document.Head.AppendChild(script);

            Assert.True(signal.WaitOne(1000));

            //todo: Mock.Get(resourceProvider).Verify(x => x.GetResourceAsync("http://localhost/script.js"), Times.Once());
            console.Verify(x => x.Log("hello"), Times.Once);
        }
Beispiel #12
0
        public async Task AddScriptAsync()
        {
            var resources = Mocks.ResourceProvider("http://localhost/script.js", "console.log('in new script');")
                            .Resource("http://localhost", "<html><head></head></html>");

            var console = new TestingConsole();
            //todo: rewrite it with JS. current test is not stable due to multithreading.
            var engine = TestingEngine.BuildJint(resources, console);

            var page = await engine.OpenUrl("http://localhost");

            page.Document.AddEventListener("DOMNodeInserted", @event =>
            {
                console.Log("nodeadded");
            }, false);

            var onloadSignal = new ManualResetEvent(false);

            var d = (HtmlScriptElement)page.Document.CreateElement("script");

            d.Id      = "aaa";
            d.Async   = true;
            d.Src     = "http://localhost/script.js";
            d.OnLoad += e =>
            {
                console.Log("onload");
                onloadSignal.Set();
            };
            page.Document.Head.AppendChild(d);

            onloadSignal.WaitOne(10000);
            CollectionAssert.AreEqual(new[] { "nodeadded", "in new script", "onload" }, console.LogHistory);
        }
Beispiel #13
0
        public async Task DocumentWithEmbeddedImageEventsOrder()
        {
            var httpResourceProvider = Mocks.HttpResourceProvider()
                                       .Resource("http://localhost/",
                                                 "<html><body onload='console.log(\"body\")'>" +
                                                 "<img src='data:image/bmp;base64,{Img64}'/>" +
                                                 "<script>" +
                                                 "document.getElementsByTagName('img')[0].onload=function(){console.log('img');}" +
                                                 "document.addEventListener('DOMContentLoaded', function(){console.log('DOMContentLoaded-C');}, true);" +
                                                 "document.addEventListener('DOMContentLoaded', function(){console.log('DOMContentLoaded-B');}, false);" +
                                                 "</script>" +
                                                 "</body></html>"
                                                 );

            var resourceProvider = new ResourceProvider(httpResourceProvider, null);

            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resourceProvider, console);
            var page    = await engine.OpenUrl("http://localhost");

            Thread.Sleep(5000);            //rewrite

            Assert.AreEqual(new[] {
                "DOMContentLoaded-C",
                "DOMContentLoaded-B",
                "img",
                "body"
            }, console.LogHistory);

            ((HtmlImageElement)page.Document.GetElementsByTagName(TagsNames.Img).First())
            .Assert(img => img.NaturalWidth == 8 && img.NaturalHeight == 4);
        }
Beispiel #14
0
        public async Task On()
        {
            var script = @"$('#b').on('click', function() {console.log('hi'); });
var e = document.createElement('div');
e.id = 'loaded';
document.body.appendChild(e);";

            var resources = Mocks.ResourceProvider(
                "http://localhost",
                "<html><head><script> " + R.JQueryJs +
                " </script></head><body><div id='b'></div></body><script>" + script +
                "</script></html>");
            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resources, console);
            var page    = await engine.OpenUrl("http://localhost");

            var loaded = page.Document.WaitId("loaded");

            Assert.IsNotNull(loaded);

            var e = engine.Document.CreateEvent("Event");

            e.InitEvent("click", true, true);
            engine.Document.GetElementById("b").DispatchEvent(e);

            Assert.AreEqual(new[] { "hi" }, console.LogHistory);
        }
Beispiel #15
0
        [TestCase("hello", null)]        //bad json
        public void XmlHttpRequestJson(string json, string expectedMsg)
        {
            var resourceProvider = Mocks.ResourceProvider("http://localhost/", @"<html><script>
	var xhr = new XMLHttpRequest();
	xhr.open('GET', 'data.json', true);
	xhr.responseType = 'json';
	xhr.onload = function () {
		if (xhr.readyState === xhr.DONE) {
			if (xhr.status === 200) {
				console.log(xhr.response == null ? null : xhr.response.data);
				var div = document.createElement('div');
				div.id='finished';
				document.body.appendChild(div);
			}
		}
	};
	xhr.send(null);</script></html>"    )
                                   .Resource("http://localhost/data.json", json);

            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resourceProvider, console);

            ((Navigator)engine.Window.Navigator).UserAgent = "My favorite browser";

            engine.OpenUrl("http://localhost").Wait();

            Assert.IsNotNull(engine.WaitId("finished"));
            Assert.AreEqual(new[] { expectedMsg }, console.LogHistory);
        }
Beispiel #16
0
        public static async Task CancelSubmitFromWindow(string returnValue, string log)
        {
            var html = @"<form><button id=b>clickme</button></form>";

            var js = "window.onsubmit=function(){console.log('submit')};" +
                     $"window.onclick=function(){{console.log('click'); return {returnValue};}};";

            var httpResources = Mocks.HttpResourceProvider()
                                .Resource("http://site.net/", $"{html}<script>{js}</script>");

            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(httpResources, console);

            var page = await engine.OpenUrl("http://site.net");

            engine.OnUriChanged += () => console.Log("reload");

            var button = page.Document.Get <HtmlButtonElement>("#b").First();

            button.Click();

            await Task.Delay(1000);

            Assert.AreEqual(log, string.Join(",", console.LogHistory));
        }
Beispiel #17
0
        public static async Task CancelSubmit()
        {
            var html = @"<form><button id=b>clickme</button></form>";

            var js = @"
			window.onsubmit = function(){console.log('window onsubmit');};
			window.onclick = function(){console.log('window onclick')};
			var f = document.getElementsByTagName('form')[0];
			f.onsubmit = function(){console.log('form onsubmit')};
			f.onclick = function(){console.log('form onclick')};
			var b = document.getElementById('b');
			b.onclick=function(){console.log('button onclick'); return false;};"            ;

            var httpResources = Mocks.HttpResourceProvider()
                                .Resource("http://site.net/", $"{html}<script>{js}</script>");

            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(httpResources, console);

            engine.OpenUrl("http://site.net").Wait();

            var doc = engine.Document;

            var button = doc.Get <HtmlButtonElement>("#b").First();

            button.Click();

            Assert.AreEqual(new[]
            {
                "button onclick",
                "form onclick",
                "window onclick"
            }, console.LogHistory);
        }
Beispiel #18
0
        static async Task <HtmlDocument> Load(string html)
        {
            var rp     = Mocks.ResourceProvider("http://localhost", html);
            var engine = TestingEngine.BuildJint(rp, SystemConsole.Instance);

            return((await engine.OpenUrl("http://localhost")).Document);
        }
Beispiel #19
0
        public async Task DocumentReadyStateComplete()
        {
            var resources = Mocks.ResourceProvider("http://localhost", "<html><body></body></html>");
            var engine    = TestingEngine.BuildJint(resources);
            var page      = await engine.OpenUrl("http://localhost");

            Assert.AreEqual(DocumentReadyStates.Complete, page.Document.ReadyState);
        }
Beispiel #20
0
        private static Engine Load(IResourceProvider resourceProvider)
        {
            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resourceProvider, console);

            engine.OpenUrl("http://localhost").Wait();
            return(engine);
        }
Beispiel #21
0
        public void SetLocationHref()
        {
            var resourceProvider = Mocks.ResourceProvider("http://todosoft.ru", "");
            var engine           = TestingEngine.BuildJint(resourceProvider);

            //todo: write similar test on js
            engine.Window.Location.Href = "http://todosoft.ru";
//todo:			Mock.Get(resourceProvider).Verify(x => x.GetResourceAsync("http://todosoft.ru"), Times.Once());
        }
Beispiel #22
0
        private Engine Open(string testUrl)
        {
            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(console).LogEvents();

            engine.OpenUrl(GetTestUrl(testUrl));
            engine.WaitDocumentLoad();
            return(engine);
        }
Beispiel #23
0
        public void Location()
        {
            var resourceProvider = Mocks.ResourceProvider("http://todosoft.ru", "");
            var engine           = TestingEngine.BuildJint(resourceProvider);

            engine.OpenUrl("http://todosoft.ru");
            Assert.AreEqual("http://todosoft.ru/", engine.Window.Location.Href);
            Assert.AreEqual("http:", engine.Window.Location.Protocol);
        }
Beispiel #24
0
        public async Task NotFoundHttpStatusCode()
        {
            var resourceProvider = new ResourceProvider(Mocks.HttpResourceProvider(), null);
            var engine           = TestingEngine.BuildJint(resourceProvider);

            var result = await engine.OpenUrl("http://some.site") as HttpPage;

            Assert.AreEqual(HttpStatusCode.NotFound, result.HttpStatusCode);
        }
Beispiel #25
0
        private static List <object> OpenUrlAndGetLog(string url, IResourceProvider resourceProvider)
        {
            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resourceProvider, console);

            engine.OpenUrl(url).Wait();
            System.Threading.Thread.Sleep(5000);
            return(console.LogHistory);
        }
Beispiel #26
0
        public async Task LoadScriptTest()
        {
            var resourceProvider = Mocks.ResourceProvider("http://localhost/script.js", "console.log('hello');")
                                   .Resource("http://localhost", "<html><head><script src='http://localhost/script.js'></script></head></html>");
            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resourceProvider, console);
            await engine.OpenUrl("http://localhost");

            Assert.AreEqual(new[] { "hello" }, console.LogHistory);
        }
Beispiel #27
0
        public void BrowseOkkam()
        {
            var engine = TestingEngine.BuildJint();

            engine.ScriptExecutor.OnException += exception => System.Console.WriteLine(exception.ToString());
            engine.OpenUrl("http://okkamtech.com").Wait(timeout);
            var userName = engine.WaitId("UserName");

            Assert.IsNotNull(userName);
        }
Beispiel #28
0
        public async Task AppendScriptAsInnerHtml()
        {
            var console   = new Mock <IConsole>();
            var resources = Mocks.ResourceProvider("http://localhost", "<html><head></head><body></body></html>");
            var engine    = TestingEngine.BuildJint(resources, console.Object);
            var page      = await engine.OpenUrl("http://localhost");

            page.Document.Body.InnerHTML = "<script>console.log('HI');</script>";
            console.Verify(x => x.Log("HI"), Times.Once);
        }
Beispiel #29
0
        public async Task NonJsScript()
        {
            var resources = Mocks.ResourceProvider("http://localhost",
                                                   "<html><head><script id='template' type='text/html'><div>a</div></script></head></html>");
            var engine = TestingEngine.BuildJint(resources);
            var page   = await engine.OpenUrl("http://localhost");

            var script = page.Document.GetElementById("template");

            Assert.AreEqual("<div>a</div>", script.InnerHTML);
        }
Beispiel #30
0
        public async Task SetWindowProperty(string code)
        {
            var resourceProvider = Mocks.ResourceProvider("http://loc/",
                                                          $"<html><script>{code}</script></html>");

            var console = new TestingConsole();
            var engine  = TestingEngine.BuildJint(resourceProvider, console);
            var page    = await engine.OpenUrl("http://loc/");

            Assert.AreEqual(new[] { true }, console.LogHistory);
        }