How to use createWorker method in Playwright Internal

Best JavaScript code snippet using playwright-internal

test-content-proxy.js

Source:test-content-proxy.js Github

copy

Full Screen

...24 let helper = {25 xrayWindow: xrayWindow,26 rawWindow: rawWindow,27 createWorker: function (contentScript) {28 return createWorker(assert, xrayWindow, contentScript, helper.done);29 },30 done: function () {31 if (isDone)32 return;33 isDone = true;34 hiddenFrames.remove(hiddenFrame);35 done();36 }37 }38 callback(helper, assert);39 }40 hiddenFrame.element.addEventListener("DOMContentLoaded", onDOMReady, false);41 hiddenFrame.element.setAttribute("src", url);42 }43 }));44 };45}46function createWorker(assert, xrayWindow, contentScript, done) {47 // We have to use Sandboxed loader in order to get access to the private48 // unlock key `PRIVATE_KEY`. This key should not be used anywhere else.49 // See `PRIVATE_KEY` definition in worker.js50 let loader = Loader(module);51 let Worker = loader.require("sdk/content/worker").Worker;52 let key = loader.sandbox("sdk/content/worker").PRIVATE_KEY;53 let worker = Worker({54 exposeUnlockKey : USE_JS_PROXIES ? key : null,55 window: xrayWindow,56 contentScript: [57 'new ' + function () {58 assert = function assert(v, msg) {59 self.port.emit("assert", {assertion:v, msg:msg});60 }61 done = function done() {62 self.port.emit("done");63 }64 },65 contentScript66 ]67 });68 worker.port.on("done", done);69 worker.port.on("assert", function (data) {70 assert.ok(data.assertion, data.msg);71 });72 return worker;73}74/* Examples for the `createProxyTest` uses */75let html = "<script>var documentGlobal = true</script>";76exports["test Create Proxy Test"] = createProxyTest(html, function (helper, assert) {77 // You can get access to regular `test` object in second argument of78 // `createProxyTest` method:79 assert.ok(helper.rawWindow.documentGlobal,80 "You have access to a raw window reference via `helper.rawWindow`");81 assert.ok(!("documentGlobal" in helper.xrayWindow),82 "You have access to an XrayWrapper reference via `helper.xrayWindow`");83 // If you do not create a Worker, you have to call helper.done(),84 // in order to say when your test is finished85 helper.done();86});87exports["test Create Proxy Test With Worker"] = createProxyTest("", function (helper) {88 helper.createWorker(89 "new " + function WorkerScope() {90 assert(true, "You can do assertions in your content script");91 // And if you create a worker, you either have to call `done`92 // from content script or helper.done()93 done();94 }95 );96});97exports["test Create Proxy Test With Events"] = createProxyTest("", function (helper, assert) {98 let worker = helper.createWorker(99 "new " + function WorkerScope() {100 self.port.emit("foo");101 }102 );103 worker.port.on("foo", function () {104 assert.pass("You can use events");105 // And terminate your test with helper.done:106 helper.done();107 });108});109if (USE_JS_PROXIES) {110 // Verify that the attribute `exposeUnlockKey`, that allow this test111 // to identify proxies, works correctly.112 // See `PRIVATE_KEY` definition in worker.js113 exports["test Key Access"] = createProxyTest("", function(helper) {114 helper.createWorker(115 'new ' + function ContentScriptScope() {116 assert("UNWRAP_ACCESS_KEY" in window, "have access to `UNWRAP_ACCESS_KEY`");117 done();118 }119 );120 });121}122// Bug 714778: There was some issue around `toString` functions123// that ended up being shared between content scripts124exports["test Shared To String Proxies"] = createProxyTest("", function(helper) {125 let worker = helper.createWorker(126 'new ' + function ContentScriptScope() {127 // We ensure that `toString` can't be modified so that nothing could128 // leak to/from the document and between content scripts129 // It only applies to JS proxies, there isn't any such issue with xrays.130 //document.location.toString = function foo() {};131 document.location.toString.foo = "bar";132 if ('UNWRAP_ACCESS_KEY' in window)133 assert(!("foo" in document.location.toString), "document.location.toString can't be modified");134 else135 assert("foo" in document.location.toString, "document.location.toString can be modified");136 assert(document.location.toString() == "data:text/html;charset=utf-8,",137 "First document.location.toString()");138 self.postMessage("next");139 }140 );141 worker.on("message", function () {142 helper.createWorker(143 'new ' + function ContentScriptScope2() {144 assert(!("foo" in document.location.toString),145 "document.location.toString is different for each content script");146 assert(document.location.toString() == "data:text/html;charset=utf-8,",147 "Second document.location.toString()");148 done();149 }150 );151 });152});153// Ensure that postMessage is working correctly across documents with an iframe154let html = '<iframe id="iframe" name="test" src="data:text/html;charset=utf-8," />';155exports["test postMessage"] = createProxyTest(html, function (helper, assert) {156 let ifWindow = helper.xrayWindow.document.getElementById("iframe").contentWindow;157 // Listen without proxies, to check that it will work in regular case158 // simulate listening from a web document.159 ifWindow.addEventListener("message", function listener(event) {160 ifWindow.removeEventListener("message", listener, false);161 // As we are in system principal, event is an XrayWrapper162 if (USE_JS_PROXIES) {163 assert.equal(event.source, ifWindow,164 "event.source is the iframe window");165 }166 else {167 // JS proxies had different behavior than xrays, xrays use current168 // compartments when calling postMessage method. Whereas js proxies169 // was using postMessage method compartment, not the caller one.170 assert.equal(event.source, helper.xrayWindow,171 "event.source is the top window");172 }173 assert.equal(event.origin, "null", "origin is null");174 assert.equal(event.data, "{\"foo\":\"bar\\n \\\"escaped\\\".\"}",175 "message data is correct");176 helper.done();177 }, false);178 helper.createWorker(179 'new ' + function ContentScriptScope() {180 assert(postMessage === postMessage,181 "verify that we doesn't generate multiple functions for the same method");182 var json = JSON.stringify({foo : "bar\n \"escaped\"."});183 document.getElementById("iframe").contentWindow.postMessage(json, "*");184 }185 );186});187let html = '<input id="input2" type="checkbox" />';188exports["test Object Listener"] = createProxyTest(html, function (helper) {189 helper.createWorker(190 'new ' + function ContentScriptScope() {191 // Test objects being given as event listener192 let input = document.getElementById("input2");193 let myClickListener = {194 called: false,195 handleEvent: function(event) {196 assert(this === myClickListener, "`this` is the original object");197 assert(!this.called, "called only once");198 this.called = true;199 if ('UNWRAP_ACCESS_KEY' in window)200 assert(event.valueOf() !== event.valueOf(UNWRAP_ACCESS_KEY), "event is wrapped");201 assert(event.target, input, "event.target is the wrapped window");202 done();203 }204 };205 window.addEventListener("click", myClickListener, true);206 input.click();207 window.removeEventListener("click", myClickListener, true);208 }209 );210});211exports["test Object Listener 2"] = createProxyTest("", function (helper) {212 helper.createWorker(213 'new ' + function ContentScriptScope() {214 // Verify object as DOM event listener215 let myMessageListener = {216 called: false,217 handleEvent: function(event) {218 window.removeEventListener("message", myMessageListener, true);219 assert(this == myMessageListener, "`this` is the original object");220 assert(!this.called, "called only once");221 this.called = true;222 if ('UNWRAP_ACCESS_KEY' in window)223 assert(event.valueOf() !== event.valueOf(UNWRAP_ACCESS_KEY), "event is wrapped");224 assert(event.target == document.defaultView, "event.target is the wrapped window");225 assert(event.source == document.defaultView, "event.source is the wrapped window");226 assert(event.origin == "null", "origin is null");227 assert(event.data == "ok", "message data is correct");228 done();229 }230 };231 window.addEventListener("message", myMessageListener, true);232 document.defaultView.postMessage("ok", '*');233 }234 );235});236let html = '<input id="input" type="text" /><input id="input3" type="checkbox" />' +237 '<input id="input2" type="checkbox" />';238/* Disable test to keep tree green until Bug 756214 is fixed.239exports.testStringOverload = createProxyTest(html, function (helper, test) {240 // Proxy - toString error241 let originalString = "string";242 let p = Proxy.create({243 get: function(receiver, name) {244 if (name == "binded")245 return originalString.toString.bind(originalString);246 return originalString[name];247 }248 });249 assert.okRaises(function () {250 p.toString();251 },252 /String.prototype.toString called on incompatible Proxy/,253 "toString can't be called with this being the proxy");254 assert.equal(p.binded(), "string", "but it works if we bind this to the original string");255 helper.createWorker(256 'new ' + function ContentScriptScope() {257 // RightJS is hacking around String.prototype, and do similar thing:258 // Pass `this` from a String prototype method.259 // It is funny because typeof this == "object"!260 // So that when we pass `this` to a native method,261 // our proxy code can fail on another even more crazy thing.262 // See following test to see what fails around proxies.263 String.prototype.update = function () {264 assert(typeof this == "object", "in update, `this` is an object");265 assert(this.toString() == "input", "in update, `this.toString works");266 return document.querySelectorAll(this);267 };268 assert("input".update().length == 3, "String.prototype overload works");269 done();270 }271 );272});273*/274exports["test MozMatchedSelector"] = createProxyTest("", function (helper) {275 helper.createWorker(276 'new ' + function ContentScriptScope() {277 // Check mozMatchesSelector XrayWrappers bug:278 // mozMatchesSelector returns bad results when we are not calling it from the node itself279 // SEE BUG 658909: mozMatchesSelector returns incorrect results with XrayWrappers280 assert(document.createElement( "div" ).mozMatchesSelector("div"),281 "mozMatchesSelector works while being called from the node");282 assert(document.documentElement.mozMatchesSelector.call(283 document.createElement( "div" ),284 "div"285 ),286 "mozMatchesSelector works while being called from a " +287 "function reference to " +288 "document.documentElement.mozMatchesSelector.call");289 done();290 }291 );292});293exports["test Events Overload"] = createProxyTest("", function (helper) {294 helper.createWorker(295 'new ' + function ContentScriptScope() {296 // If we add a "____proxy" attribute on XrayWrappers in order to store297 // the related proxy to create an unique proxy for each wrapper;298 // we end up setting this attribute to prototype objects :x299 // And so, instances created with such prototype will be considered300 // as equal to the prototype ...301 // // Internal method that return the proxy for a given XrayWrapper302 // function proxify(obj) {303 // if (obj._proxy) return obj._proxy;304 // return obj._proxy = Proxy.create(...);305 // }306 //307 // // Get a proxy of an XrayWrapper prototype object308 // let proto = proxify(xpcProto);309 //310 // // Use this proxy as a prototype311 // function Constr() {}312 // Constr.proto = proto;313 //314 // // Try to create an instance using this prototype315 // let xpcInstance = new Constr();316 // let wrapper = proxify(xpcInstance)317 //318 // xpcProto._proxy = proto and as xpcInstance.__proto__ = xpcProto,319 // xpcInstance._proxy = proto ... and profixy(xpcInstance) = proto :(320 //321 let proto = window.document.createEvent('HTMLEvents').__proto__;322 window.Event.prototype = proto;323 let event = document.createEvent('HTMLEvents');324 assert(event !== proto, "Event should not be equal to its prototype");325 event.initEvent('dataavailable', true, true);326 assert(event.type === 'dataavailable', "Events are working fine");327 done();328 }329 );330});331exports["test Nested Attributes"] = createProxyTest("", function (helper) {332 helper.createWorker(333 'new ' + function ContentScriptScope() {334 // XrayWrappers has a bug when you set an attribute on it,335 // in some cases, it creates an unnecessary wrapper that introduces336 // a different object that refers to the same original object337 // Check that our wrappers don't reproduce this bug338 // SEE BUG 658560: Fix identity problem with CrossOriginWrappers339 let o = {sandboxObject:true};340 window.nested = o;341 o.foo = true;342 assert(o === window.nested, "Nested attribute to sandbox object should not be proxified");343 window.nested = document;344 assert(window.nested === document, "Nested attribute to proxy should not be double proxified");345 done();346 }347 );348});349exports["test Form nodeName"] = createProxyTest("", function (helper) {350 helper.createWorker(351 'new ' + function ContentScriptScope() {352 let body = document.body;353 // Check form[nodeName]354 let form = document.createElement("form");355 let input = document.createElement("input");356 input.setAttribute("name", "test");357 form.appendChild(input);358 body.appendChild(form);359 assert(form.test == input, "form[nodeName] is valid");360 body.removeChild(form);361 done();362 }363 );364});365exports["test localStorage"] = createProxyTest("", function (helper, assert) {366 let worker = helper.createWorker(367 'new ' + function ContentScriptScope() {368 // Check localStorage:369 assert(window.localStorage, "has access to localStorage");370 window.localStorage.name = 1;371 assert(window.localStorage.name == 1, "localStorage appears to work");372 self.port.on("step2", function () {373 window.localStorage.clear();374 assert(window.localStorage.name == undefined, "localStorage really, really works");375 done();376 });377 self.port.emit("step1");378 }379 );380 worker.port.on("step1", function () {381 assert.equal(helper.rawWindow.localStorage.name, 1, "localStorage really works");382 worker.port.emit("step2");383 });384});385exports["test Auto Unwrap Custom Attributes"] = createProxyTest("", function (helper) {386 helper.createWorker(387 'new ' + function ContentScriptScope() {388 let body = document.body;389 // Setting a custom object to a proxy attribute is not wrapped when we get it afterward390 let object = {custom: true, enumerable: false};391 body.customAttribute = object;392 if ('UNWRAP_ACCESS_KEY' in window)393 assert(body.customAttribute.valueOf() === body.customAttribute.valueOf(UNWRAP_ACCESS_KEY), "custom JS attributes are not wrapped");394 assert(object === body.customAttribute, "custom JS attributes are not wrapped");395 done();396 }397 );398});399exports["test Object Tag"] = createProxyTest("", function (helper) {400 helper.createWorker(401 'new ' + function ContentScriptScope() {402 // <object>, <embed> and other tags return typeof 'function'403 let flash = document.createElement("object");404 assert(typeof flash == "function", "<object> is typeof 'function'");405 assert(flash.toString().match(/\[object HTMLObjectElement.*\]/), "<object> is HTMLObjectElement");406 assert("setAttribute" in flash, "<object> has a setAttribute method");407 done();408 }409 );410});411exports["test Highlight toString Behavior"] = createProxyTest("", function (helper, assert) {412 // We do not have any workaround this particular use of toString413 // applied on <object> elements. So disable this test until we found one!414 //assert.equal(helper.rawWindow.Object.prototype.toString.call(flash), "[object HTMLObjectElement]", "<object> is HTMLObjectElement");415 function f() {};416 let funToString = Object.prototype.toString.call(f);417 assert.ok(/\[object Function.*\]/.test(funToString), "functions are functions 1");418 // This is how jquery call toString:419 let strToString = helper.rawWindow.Object.prototype.toString.call("");420 assert.ok(/\[object String.*\]/.test(strToString), "strings are strings");421 let o = {__exposedProps__:{}};422 let objToString = helper.rawWindow.Object.prototype.toString.call(o);423 assert.ok(/\[object Object.*\]/.test(objToString), "objects are objects");424 // Make sure to pass a function from the same compartments425 // or toString will return [object Object] on FF8+426 let f2 = helper.rawWindow.eval("(function () {})");427 let funToString2 = helper.rawWindow.Object.prototype.toString.call(f2);428 assert.ok(/\[object Function.*\]/.test(funToString2), "functions are functions 2");429 helper.done();430});431exports["test Document TagName"] = createProxyTest("", function (helper) {432 helper.createWorker(433 'new ' + function ContentScriptScope() {434 let body = document.body;435 // Check document[tagName]436 let div = document.createElement("div");437 div.setAttribute("name", "test");438 body.appendChild(div);439 assert(!document.test, "document[divName] is undefined");440 body.removeChild(div);441 let form = document.createElement("form");442 form.setAttribute("name", "test");443 body.appendChild(form);444 assert(document.test == form, "document[formName] is valid");445 body.removeChild(form);446 let img = document.createElement("img");447 img.setAttribute("name", "test");448 body.appendChild(img);449 assert(document.test == img, "document[imgName] is valid");450 body.removeChild(img);451 done();452 }453 );454});455let html = '<iframe id="iframe" name="test" src="data:text/html;charset=utf-8," />';456exports["test Window Frames"] = createProxyTest(html, function (helper) {457 helper.createWorker(458 'let glob = this; new ' + function ContentScriptScope() {459 // Check window[frameName] and window.frames[i]460 let iframe = document.getElementById("iframe");461 //assert(window.frames.length == 1, "The iframe is reported in window.frames check1");462 //assert(window.frames[0] == iframe.contentWindow, "The iframe is reported in window.frames check2");463 //console.log(window.test+ "-"+iframe.contentWindow);464 //console.log(window);465 assert(window.test == iframe.contentWindow, "window[frameName] is valid");466 done();467 }468 );469});470exports["test Collections"] = createProxyTest("", function (helper) {471 helper.createWorker(472 'new ' + function ContentScriptScope() {473 // Highlight XPCNativeWrapper bug with HTMLCollection474 // tds[0] is only defined on first access :o475 let body = document.body;476 let div = document.createElement("div");477 body.appendChild(div);478 div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";479 let tds = div.getElementsByTagName("td");480 assert(tds[0] == tds[0], "We can get array element multiple times");481 body.removeChild(div);482 done();483 }484 );485});486let html = '<input id="input" type="text" /><input id="input3" type="checkbox" />' +487 '<input id="input2" type="checkbox" />';488exports["test Collections 2"] = createProxyTest(html, function (helper) {489 helper.createWorker(490 'new ' + function ContentScriptScope() {491 // Verify that NodeList/HTMLCollection are working fine492 let body = document.body;493 let inputs = body.getElementsByTagName("input");494 assert(body.childNodes.length == 3, "body.childNodes length is correct");495 assert(inputs.length == 3, "inputs.length is correct");496 assert(body.childNodes[0] == inputs[0], "body.childNodes[0] is correct");497 assert(body.childNodes[1] == inputs[1], "body.childNodes[1] is correct");498 assert(body.childNodes[2] == inputs[2], "body.childNodes[2] is correct");499 let count = 0;500 for(let i in body.childNodes) {501 count++;502 }503 // JS proxies were broken, we can iterate over some other items:504 // length, item and iterator505 let expectedCount;506 if ('UNWRAP_ACCESS_KEY' in window)507 expectedCount = 3;508 else509 expectedCount = 6;510 assert(count == expectedCount, "body.childNodes is iterable");511 done();512 }513 );514});515exports["test valueOf"] = createProxyTest("", function (helper) {516 if (USE_JS_PROXIES) {517 helper.createWorker(518 'new ' + function ContentScriptScope() {519 // Check internal use of valueOf() for JS proxies API520 assert(/\[object Window.*\]/.test(window.valueOf().toString()),521 "proxy.valueOf() returns the wrapped version");522 assert(/\[object Window.*\]/.test(window.valueOf({}).toString()),523 "proxy.valueOf({}) returns the wrapped version");524 done();525 }526 );527 }528 else {529 helper.createWorker(530 'new ' + function ContentScriptScope() {531 // Bug 787013: Until this bug is fixed, we are missing some methods532 // on JS objects that comes from global `Object` object533 assert(!('valueOf' in window), "valueOf is missing");534 assert(!('toLocateString' in window), "toLocaleString is missing");535 done();536 }537 );538 }539});540exports["test XMLHttpRequest"] = createProxyTest("", function (helper) {541 helper.createWorker(542 'new ' + function ContentScriptScope() {543 // XMLHttpRequest doesn't support XMLHttpRequest.apply,544 // that may break our proxy code545 assert(window.XMLHttpRequest(), "we are able to instantiate XMLHttpRequest object");546 done();547 }548 );549});550exports["test XPathResult"] = createProxyTest("", function (helper, assert) {551 const XPathResultTypes = ["ANY_TYPE",552 "NUMBER_TYPE", "STRING_TYPE", "BOOLEAN_TYPE",553 "UNORDERED_NODE_ITERATOR_TYPE",554 "ORDERED_NODE_ITERATOR_TYPE",555 "UNORDERED_NODE_SNAPSHOT_TYPE",556 "ORDERED_NODE_SNAPSHOT_TYPE",557 "ANY_UNORDERED_NODE_TYPE",558 "FIRST_ORDERED_NODE_TYPE"];559 // Check XPathResult bug with constants being undefined on XPCNativeWrapper560 let xpcXPathResult = helper.xrayWindow.XPathResult;561 XPathResultTypes.forEach(function(type, i) {562 assert.equal(xpcXPathResult.wrappedJSObject[type],563 helper.rawWindow.XPathResult[type],564 "XPathResult's constants are valid on unwrapped node");565 assert.equal(xpcXPathResult[type], i,566 "XPathResult's constants are defined on " +567 "XPCNativeWrapper (platform bug #)");568 });569 let value = helper.rawWindow.XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE;570 let worker = helper.createWorker(571 'new ' + function ContentScriptScope() {572 self.port.on("value", function (value) {573 // Check that our work around is working:574 assert(window.XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE === value,575 "XPathResult works correctly on Proxies");576 done();577 });578 }579 );580 worker.port.emit("value", value);581});582exports["test Prototype Inheritance"] = createProxyTest("", function (helper) {583 helper.createWorker(584 'new ' + function ContentScriptScope() {585 // Verify that inherited prototype function like initEvent586 // are handled correctly. (e2.type will return an error if it's not the case)587 let event1 = document.createEvent( 'MouseEvents' );588 event1.initEvent( "click", true, true );589 let event2 = document.createEvent( 'MouseEvents' );590 event2.initEvent( "click", true, true );591 assert(event2.type == "click", "We are able to create an event");592 done();593 }594 );595});596exports["test Functions"] = createProxyTest("", function (helper) {597 helper.rawWindow.callFunction = function callFunction(f) f();598 helper.rawWindow.isEqual = function isEqual(a, b) a == b;599 // bug 784116: workaround in order to allow proxy code to cache proxies on600 // these functions:601 helper.rawWindow.callFunction.__exposedProps__ = {__proxy: 'rw'};602 helper.rawWindow.isEqual.__exposedProps__ = {__proxy: 'rw'};603 helper.createWorker(604 'new ' + function ContentScriptScope() {605 // Check basic usage of functions606 let closure2 = function () {return "ok";};607 assert(window.wrappedJSObject.callFunction(closure2) == "ok", "Function references work");608 // Ensure that functions are cached when being wrapped to native code609 let closure = function () {};610 assert(window.wrappedJSObject.isEqual(closure, closure), "Function references are cached before being wrapped to native");611 done();612 }613 );614});615let html = '<input id="input2" type="checkbox" />';616exports["test Listeners"] = createProxyTest(html, function (helper) {617 helper.createWorker(618 'new ' + function ContentScriptScope() {619 // Verify listeners:620 let input = document.getElementById("input2");621 assert(input, "proxy.getElementById works");622 function onclick() {};623 input.onclick = onclick;624 assert(input.onclick === onclick, "on* attributes are equal to original function set");625 let addEventListenerCalled = false;626 let expandoCalled = false;627 input.addEventListener("click", function onclick(event) {628 input.removeEventListener("click", onclick, true);629 assert(!addEventListenerCalled, "closure given to addEventListener is called once");630 if (addEventListenerCalled)631 return;632 addEventListenerCalled = true;633 assert(!event.target.ownerDocument.defaultView.documentGlobal, "event object is still wrapped and doesn't expose document globals");634 if ('UNWRAP_ACCESS_KEY' in window)635 assert("__isWrappedProxy" in event.target, "event object is a proxy");636 let input2 = document.getElementById("input2");637 input.onclick = function (event) {638 input.onclick = null;639 assert(!expandoCalled, "closure set to expando is called once");640 if (expandoCalled) return;641 expandoCalled = true;642 assert(!event.target.ownerDocument.defaultView.documentGlobal, "event object is still wrapped and doesn't expose document globals");643 if ('UNWRAP_ACCESS_KEY' in window)644 assert("__isWrappedProxy" in event.target, "event object is a proxy");645 setTimeout(function () {646 input.click();647 done();648 }, 0);649 }650 setTimeout(function () {651 input.click();652 }, 0);653 }, true);654 input.click();655 }656 );657});658exports["test MozRequestAnimationFrame"] = createProxyTest("", function (helper) {659 helper.createWorker(660 'new ' + function ContentScriptScope() {661 window.mozRequestAnimationFrame(function callback() {662 assert(callback == this, "callback is equal to `this`");663 done();664 });665 }666 );667});668exports["testGlobalScope"] = createProxyTest("", function (helper) {669 helper.createWorker(670 'let toplevelScope = true;' +671 'assert(window.toplevelScope, "variables in toplevel scope are set to `window` object");' +672 'assert(this.toplevelScope, "variables in toplevel scope are set to `this` object");' +673 'done();'674 );675});676if (USE_JS_PROXIES) {677 // Bug 671016: Typed arrays should not be proxified678 exports["test Typed ArraysX"] = createProxyTest("", function (helper) {679 helper.createWorker(680 'new ' + function ContentScriptScope() {681 let canvas = document.createElement("canvas");682 let context = canvas.getContext("2d");683 let imageData = context.getImageData(0,0, 1, 1);684 let unwrappedData;685 if ('UNWRAP_ACCESS_KEY' in window)686 unwrappedData = imageData.valueOf(UNWRAP_ACCESS_KEY).data687 else688 unwrappedData = imageData.wrappedJSObject.data;689 let data = imageData.data;690 dump(unwrappedData+" === "+data+"\n");691 assert(unwrappedData === data, "Typed array isn't proxified")692 done();693 }694 );695 });696}697// Bug 715755: proxy code throw an exception on COW698// Create an http server in order to simulate real cross domain documents699exports["test Cross Domain Iframe"] = createProxyTest("", function (helper) {700 let serverPort = 8099;701 let server = require("sdk/test/httpd").startServerAsync(serverPort);702 server.registerPathHandler("/", function handle(request, response) {703 // Returns the webpage that receive a message and forward it back to its704 // parent document by appending ' world'.705 let content = "<html><head><meta charset='utf-8'></head>\n";706 content += "<script>\n";707 content += " window.addEventListener('message', function (event) {\n";708 content += " parent.postMessage(event.data + ' world', '*');\n";709 content += " }, true);\n";710 content += "</script>\n";711 content += "<body></body>\n";712 content += "</html>\n";713 response.write(content);714 });715 let worker = helper.createWorker(716 'new ' + function ContentScriptScope() {717 // Waits for the server page url718 self.on("message", function (url) {719 // Creates an iframe with this page720 let iframe = document.createElement("iframe");721 iframe.addEventListener("load", function onload() {722 iframe.removeEventListener("load", onload, true);723 try {724 // Try to communicate with iframe's content725 window.addEventListener("message", function onmessage(event) {726 window.removeEventListener("message", onmessage, true);727 assert(event.data == "hello world", "COW works properly");728 self.port.emit("end");729 }, true);730 iframe.contentWindow.postMessage("hello", "*");731 } catch(e) {732 assert(false, "COW fails : "+e.message);733 }734 }, true);735 iframe.setAttribute("src", url);736 document.body.appendChild(iframe);737 });738 }739 );740 worker.port.on("end", function () {741 server.stop(helper.done);742 });743 worker.postMessage("http://localhost:" + serverPort + "/");744});745// Bug 769006: Ensure that MutationObserver works fine with proxies746let html = '<a href="foo">link</a>';747exports["test MutationObvserver"] = createProxyTest(html, function (helper) {748 helper.createWorker(749 'new ' + function ContentScriptScope() {750 if (typeof MutationObserver == "undefined") {751 assert(true, "No MutationObserver for this FF version");752 done();753 return;754 }755 let link = document.getElementsByTagName("a")[0];756 // Register a Mutation observer757 let obs = new MutationObserver(function(mutations){758 // Ensure that mutation data are valid759 assert(mutations.length == 1, "only one attribute mutation");760 let mutation = mutations[0];761 assert(mutation.type == "attributes", "check `type`");762 assert(mutation.target == link, "check `target`");...

Full Screen

Full Screen

test-content-script.js

Source:test-content-script.js Github

copy

Full Screen

...40 let helper = {41 xrayWindow: xrayWindow,42 rawWindow: rawWindow,43 createWorker: function (contentScript) {44 return createWorker(assert, xrayWindow, contentScript, helper.done);45 },46 done: function () {47 if (isDone)48 return;49 isDone = true;50 element.remove();51 done();52 }53 };54 callback(helper, assert);55 }56 };57}58function createWorker(assert, xrayWindow, contentScript, done) {59 let loader = Loader(module);60 let Worker = loader.require("sdk/content/worker").Worker;61 let worker = Worker({62 window: xrayWindow,63 contentScript: [64 'new ' + function () {65 assert = function assert(v, msg) {66 self.port.emit("assert", {assertion:v, msg:msg});67 }68 done = function done() {69 self.port.emit("done");70 }71 },72 contentScript73 ]74 });75 worker.port.on("done", done);76 worker.port.on("assert", function (data) {77 assert.ok(data.assertion, data.msg);78 });79 return worker;80}81/* Examples for the `createProxyTest` uses */82var html = "<script>var documentGlobal = true</script>";83exports["test Create Proxy Test"] = createProxyTest(html, function (helper, assert) {84 // You can get access to regular `test` object in second argument of85 // `createProxyTest` method:86 assert.ok(helper.rawWindow.documentGlobal,87 "You have access to a raw window reference via `helper.rawWindow`");88 assert.ok(!("documentGlobal" in helper.xrayWindow),89 "You have access to an XrayWrapper reference via `helper.xrayWindow`");90 // If you do not create a Worker, you have to call helper.done(),91 // in order to say when your test is finished92 helper.done();93});94exports["test Create Proxy Test With Worker"] = createProxyTest("", function (helper) {95 helper.createWorker(96 "new " + function WorkerScope() {97 assert(true, "You can do assertions in your content script");98 // And if you create a worker, you either have to call `done`99 // from content script or helper.done()100 done();101 }102 );103});104exports["test Create Proxy Test With Events"] = createProxyTest("", function (helper, assert) {105 let worker = helper.createWorker(106 "new " + function WorkerScope() {107 self.port.emit("foo");108 }109 );110 worker.port.on("foo", function () {111 assert.pass("You can use events");112 // And terminate your test with helper.done:113 helper.done();114 });115});116/* Disabled due to bug 1038432117// Bug 714778: There was some issue around `toString` functions118// that ended up being shared between content scripts119exports["test Shared To String Proxies"] = createProxyTest("", function(helper) {120 let worker = helper.createWorker(121 'new ' + function ContentScriptScope() {122 // We ensure that `toString` can't be modified so that nothing could123 // leak to/from the document and between content scripts124 // It only applies to JS proxies, there isn't any such issue with xrays.125 //document.location.toString = function foo() {};126 document.location.toString.foo = "bar";127 assert("foo" in document.location.toString, "document.location.toString can be modified");128 assert(document.location.toString() == "data:text/html;charset=utf-8,",129 "First document.location.toString()");130 self.postMessage("next");131 }132 );133 worker.on("message", function () {134 helper.createWorker(135 'new ' + function ContentScriptScope2() {136 assert(!("foo" in document.location.toString),137 "document.location.toString is different for each content script");138 assert(document.location.toString() == "data:text/html;charset=utf-8,",139 "Second document.location.toString()");140 done();141 }142 );143 });144});145*/146// Ensure that postMessage is working correctly across documents with an iframe147var html = '<iframe id="iframe" name="test" src="data:text/html;charset=utf-8," />';148exports["test postMessage"] = createProxyTest(html, function (helper, assert) {149 let ifWindow = helper.xrayWindow.document.getElementById("iframe").contentWindow;150 // Listen without proxies, to check that it will work in regular case151 // simulate listening from a web document.152 ifWindow.addEventListener("message", function(event) {153 // As we are in system principal, event is an XrayWrapper154 // xrays use current compartments when calling postMessage method.155 // Whereas js proxies was using postMessage method compartment,156 // not the caller one.157 assert.strictEqual(event.source, helper.xrayWindow,158 "event.source is the top window");159 assert.equal(event.origin, testHost, "origin matches testHost");160 assert.equal(event.data, "{\"foo\":\"bar\\n \\\"escaped\\\".\"}",161 "message data is correct");162 helper.done();163 }, {once: true});164 helper.createWorker(165 'new ' + function ContentScriptScope() {166 var json = JSON.stringify({foo : "bar\n \"escaped\"."});167 document.getElementById("iframe").contentWindow.postMessage(json, "*");168 }169 );170});171var html = '<input id="input2" type="checkbox" />';172exports["test Object Listener"] = createProxyTest(html, function (helper) {173 helper.createWorker(174 'new ' + function ContentScriptScope() {175 // Test objects being given as event listener176 let input = document.getElementById("input2");177 let myClickListener = {178 called: false,179 handleEvent: function(event) {180 assert(this === myClickListener, "`this` is the original object");181 assert(!this.called, "called only once");182 this.called = true;183 assert(event.target, input, "event.target is the wrapped window");184 done();185 }186 };187 window.addEventListener("click", myClickListener, true);188 input.click();189 window.removeEventListener("click", myClickListener, true);190 }191 );192});193exports["test Object Listener 2"] = createProxyTest("", function (helper) {194 helper.createWorker(195 ('new ' + function ContentScriptScope() {196 // variable replaced with `testHost`197 let testHost = "TOKEN";198 // Verify object as DOM event listener199 let myMessageListener = {200 called: false,201 handleEvent: function(event) {202 window.removeEventListener("message", myMessageListener, true);203 assert(this == myMessageListener, "`this` is the original object");204 assert(!this.called, "called only once");205 this.called = true;206 assert(event.target == document.defaultView, "event.target is the wrapped window");207 assert(event.source == document.defaultView, "event.source is the wrapped window");208 assert(event.origin == testHost, "origin matches testHost");209 assert(event.data == "ok", "message data is correct");210 done();211 }212 };213 window.addEventListener("message", myMessageListener, true);214 document.defaultView.postMessage("ok", '*');215 }216 ).replace("TOKEN", testHost));217});218var html = '<input id="input" type="text" /><input id="input3" type="checkbox" />' +219 '<input id="input2" type="checkbox" />';220exports.testStringOverload = createProxyTest(html, function (helper, assert) {221 helper.createWorker(222 'new ' + function ContentScriptScope() {223 // RightJS is hacking around String.prototype, and do similar thing:224 // Pass `this` from a String prototype method.225 // It is funny because typeof this == "object"!226 // So that when we pass `this` to a native method,227 // our proxy code can fail on another even more crazy thing.228 // See following test to see what fails around proxies.229 String.prototype.update = function () {230 assert(typeof this == "object", "in update, `this` is an object");231 assert(this.toString() == "input", "in update, `this.toString works");232 return document.querySelectorAll(this);233 };234 assert("input".update().length == 3, "String.prototype overload works");235 done();236 }237 );238});239exports["test Element.matches()"] = createProxyTest("", function (helper) {240 helper.createWorker(241 'new ' + function ContentScriptScope() {242 // Check matches XrayWrappers bug (Bug 658909):243 // Test that Element.matches() does not return bad results when we are244 // not calling it from the node itself.245 assert(document.createElement( "div" ).matches("div"),246 "matches works while being called from the node");247 assert(document.documentElement.matches.call(248 document.createElement( "div" ),249 "div"250 ),251 "matches works while being called from a " +252 "function reference to " +253 "document.documentElement.matches.call");254 done();255 }256 );257});258exports["test Events Overload"] = createProxyTest("", function (helper) {259 helper.createWorker(260 'new ' + function ContentScriptScope() {261 // If we add a "____proxy" attribute on XrayWrappers in order to store262 // the related proxy to create an unique proxy for each wrapper;263 // we end up setting this attribute to prototype objects :x264 // And so, instances created with such prototype will be considered265 // as equal to the prototype ...266 // // Internal method that return the proxy for a given XrayWrapper267 // function proxify(obj) {268 // if (obj._proxy) return obj._proxy;269 // return obj._proxy = Proxy.create(...);270 // }271 //272 // // Get a proxy of an XrayWrapper prototype object273 // let proto = proxify(xpcProto);274 //275 // // Use this proxy as a prototype276 // function Constr() {}277 // Constr.proto = proto;278 //279 // // Try to create an instance using this prototype280 // let xpcInstance = new Constr();281 // let wrapper = proxify(xpcInstance)282 //283 // xpcProto._proxy = proto and as xpcInstance.__proto__ = xpcProto,284 // xpcInstance._proxy = proto ... and profixy(xpcInstance) = proto :(285 //286 let proto = window.document.createEvent('HTMLEvents').__proto__;287 window.Event.prototype = proto;288 let event = document.createEvent('HTMLEvents');289 assert(event !== proto, "Event should not be equal to its prototype");290 event.initEvent('dataavailable', true, true);291 assert(event.type === 'dataavailable', "Events are working fine");292 done();293 }294 );295});296exports["test Nested Attributes"] = createProxyTest("", function (helper) {297 helper.createWorker(298 'new ' + function ContentScriptScope() {299 // XrayWrappers has a bug when you set an attribute on it,300 // in some cases, it creates an unnecessary wrapper that introduces301 // a different object that refers to the same original object302 // Check that our wrappers don't reproduce this bug303 // SEE BUG 658560: Fix identity problem with CrossOriginWrappers304 let o = {sandboxObject:true};305 window.nested = o;306 o.foo = true;307 assert(o === window.nested, "Nested attribute to sandbox object should not be proxified");308 window.nested = document;309 assert(window.nested === document, "Nested attribute to proxy should not be double proxified");310 done();311 }312 );313});314exports["test Form nodeName"] = createProxyTest("", function (helper) {315 helper.createWorker(316 'new ' + function ContentScriptScope() {317 let body = document.body;318 // Check form[nodeName]319 let form = document.createElement("form");320 let input = document.createElement("input");321 input.setAttribute("name", "test");322 form.appendChild(input);323 body.appendChild(form);324 assert(form.test == input, "form[nodeName] is valid");325 body.removeChild(form);326 done();327 }328 );329});330exports["test localStorage"] = createProxyTest("", function (helper, assert) {331 let worker = helper.createWorker(332 'new ' + function ContentScriptScope() {333 // Check localStorage:334 assert(window.localStorage, "has access to localStorage");335 window.localStorage.name = 1;336 assert(window.localStorage.name == 1, "localStorage appears to work");337 self.port.on("step2", function () {338 window.localStorage.clear();339 assert(window.localStorage.name == undefined, "localStorage really, really works");340 done();341 });342 self.port.emit("step1");343 }344 );345 worker.port.on("step1", function () {346 assert.equal(helper.rawWindow.localStorage.name, 1, "localStorage really works");347 worker.port.emit("step2");348 });349});350exports["test Auto Unwrap Custom Attributes"] = createProxyTest("", function (helper) {351 helper.createWorker(352 'new ' + function ContentScriptScope() {353 let body = document.body;354 // Setting a custom object to a proxy attribute is not wrapped when we get it afterward355 let object = {custom: true, enumerable: false};356 body.customAttribute = object;357 assert(object === body.customAttribute, "custom JS attributes are not wrapped");358 done();359 }360 );361});362exports["test Object Tag"] = createProxyTest("", function (helper) {363 helper.createWorker(364 'new ' + function ContentScriptScope() {365 // <object>, <embed> and other tags return typeof 'object'366 let flash = document.createElement("object");367 assert(typeof flash == "object", "<object> is typeof 'function'");368 assert(flash.toString().match(/\[object HTMLObjectElement.*\]/), "<object> is HTMLObjectElement");369 assert("setAttribute" in flash, "<object> has a setAttribute method");370 done();371 }372 );373});374exports["test Highlight toString Behavior"] = createProxyTest("", function (helper, assert) {375 // We do not have any workaround this particular use of toString376 // applied on <object> elements. So disable this test until we found one!377 //assert.equal(helper.rawWindow.Object.prototype.toString.call(flash), "[object HTMLObjectElement]", "<object> is HTMLObjectElement");378 function f() {};379 let funToString = Object.prototype.toString.call(f);380 assert.ok(/\[object Function.*\]/.test(funToString), "functions are functions 1");381 // This is how jquery call toString:382 let strToString = helper.rawWindow.Object.prototype.toString.call("");383 assert.ok(/\[object String.*\]/.test(strToString), "strings are strings");384 let o = {__exposedProps__:{}};385 let objToString = helper.rawWindow.Object.prototype.toString.call(o);386 assert.ok(/\[object Object.*\]/.test(objToString), "objects are objects");387 // Make sure to pass a function from the same compartments388 // or toString will return [object Object] on FF8+389 let f2 = helper.rawWindow.eval("(function () {})");390 let funToString2 = helper.rawWindow.Object.prototype.toString.call(f2);391 assert.ok(/\[object Function.*\]/.test(funToString2), "functions are functions 2");392 helper.done();393});394exports["test Document TagName"] = createProxyTest("", function (helper) {395 helper.createWorker(396 'new ' + function ContentScriptScope() {397 let body = document.body;398 // Check document[tagName]399 let div = document.createElement("div");400 div.setAttribute("name", "test");401 body.appendChild(div);402 assert(!document.test, "document[divName] is undefined");403 body.removeChild(div);404 let form = document.createElement("form");405 form.setAttribute("name", "test");406 body.appendChild(form);407 assert(document.test == form, "document[formName] is valid");408 body.removeChild(form);409 let img = document.createElement("img");410 img.setAttribute("name", "test");411 body.appendChild(img);412 assert(document.test == img, "document[imgName] is valid");413 body.removeChild(img);414 done();415 }416 );417});418var html = '<iframe id="iframe" name="test" src="data:text/html;charset=utf-8," />';419exports["test Window Frames"] = createProxyTest(html, function (helper) {420 helper.createWorker(421 'let glob = this; new ' + function ContentScriptScope() {422 // Check window[frameName] and window.frames[i]423 let iframe = document.getElementById("iframe");424 //assert(window.frames.length == 1, "The iframe is reported in window.frames check1");425 //assert(window.frames[0] == iframe.contentWindow, "The iframe is reported in window.frames check2");426 assert(window.test == iframe.contentWindow, "window[frameName] is valid");427 done();428 }429 );430});431exports["test Collections"] = createProxyTest("", function (helper) {432 helper.createWorker(433 'new ' + function ContentScriptScope() {434 // Highlight XPCNativeWrapper bug with HTMLCollection435 // tds[0] is only defined on first access :o436 let body = document.body;437 let div = document.createElement("div");438 body.appendChild(div);439 div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";440 let tds = div.getElementsByTagName("td");441 assert(tds[0] == tds[0], "We can get array element multiple times");442 body.removeChild(div);443 done();444 }445 );446});447var html = '<input id="input" type="text" /><input id="input3" type="checkbox" />' +448 '<input id="input2" type="checkbox" />';449exports["test Collections 2"] = createProxyTest(html, function (helper) {450 helper.createWorker(451 'new ' + function ContentScriptScope() {452 // Verify that NodeList/HTMLCollection are working fine453 let body = document.body;454 let inputs = body.getElementsByTagName("input");455 assert(body.childNodes.length == 3, "body.childNodes length is correct");456 assert(inputs.length == 3, "inputs.length is correct");457 assert(body.childNodes[0] == inputs[0], "body.childNodes[0] is correct");458 assert(body.childNodes[1] == inputs[1], "body.childNodes[1] is correct");459 assert(body.childNodes[2] == inputs[2], "body.childNodes[2] is correct");460 let count = 0;461 for(let i in body.childNodes) {462 count++;463 }464 assert(count >= 3, "body.childNodes is iterable");465 done();466 }467 );468});469exports["test XMLHttpRequest"] = createProxyTest("", function (helper) {470 helper.createWorker(471 'new ' + function ContentScriptScope() {472 // XMLHttpRequest doesn't support XMLHttpRequest.apply,473 // that may break our proxy code474 assert(new window.XMLHttpRequest(), "we are able to instantiate XMLHttpRequest object");475 done();476 }477 );478});479exports["test XPathResult"] = createProxyTest("", function (helper, assert) {480 const XPathResultTypes = ["ANY_TYPE",481 "NUMBER_TYPE", "STRING_TYPE", "BOOLEAN_TYPE",482 "UNORDERED_NODE_ITERATOR_TYPE",483 "ORDERED_NODE_ITERATOR_TYPE",484 "UNORDERED_NODE_SNAPSHOT_TYPE",485 "ORDERED_NODE_SNAPSHOT_TYPE",486 "ANY_UNORDERED_NODE_TYPE",487 "FIRST_ORDERED_NODE_TYPE"];488 // Check XPathResult bug with constants being undefined on XPCNativeWrapper489 let xpcXPathResult = helper.xrayWindow.XPathResult;490 XPathResultTypes.forEach(function(type, i) {491 assert.equal(xpcXPathResult.wrappedJSObject[type],492 helper.rawWindow.XPathResult[type],493 "XPathResult's constants are valid on unwrapped node");494 assert.equal(xpcXPathResult[type], i,495 "XPathResult's constants are defined on " +496 "XPCNativeWrapper (platform bug #)");497 });498 let value = helper.rawWindow.XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE;499 let worker = helper.createWorker(500 'new ' + function ContentScriptScope() {501 self.port.on("value", function (value) {502 // Check that our work around is working:503 assert(window.XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE === value,504 "XPathResult works correctly on Proxies");505 done();506 });507 }508 );509 worker.port.emit("value", value);510});511exports["test Prototype Inheritance"] = createProxyTest("", function (helper) {512 helper.createWorker(513 'new ' + function ContentScriptScope() {514 // Verify that inherited prototype function like initEvent515 // are handled correctly. (e2.type will return an error if it's not the case)516 let event1 = document.createEvent( 'MouseEvents' );517 event1.initEvent( "click", true, true );518 let event2 = document.createEvent( 'MouseEvents' );519 event2.initEvent( "click", true, true );520 assert(event2.type == "click", "We are able to create an event");521 done();522 }523 );524});525exports["test Functions"] = createProxyTest("", function (helper) {526 helper.rawWindow.callFunction = function callFunction(f) {527 return f();528 };529 helper.rawWindow.isEqual = function isEqual(a, b) {530 return a == b;531 };532 // bug 784116: workaround in order to allow proxy code to cache proxies on533 // these functions:534 helper.rawWindow.callFunction.__exposedProps__ = {__proxy: 'rw'};535 helper.rawWindow.isEqual.__exposedProps__ = {__proxy: 'rw'};536 helper.createWorker(537 'new ' + function ContentScriptScope() {538 // Check basic usage of functions539 let closure2 = function () {return "ok";};540 assert(window.wrappedJSObject.callFunction(closure2) == "ok", "Function references work");541 // Ensure that functions are cached when being wrapped to native code542 let closure = function () {};543 assert(window.wrappedJSObject.isEqual(closure, closure), "Function references are cached before being wrapped to native");544 done();545 }546 );547});548var html = '<input id="input2" type="checkbox" />';549exports["test Listeners"] = createProxyTest(html, function (helper) {550 helper.createWorker(551 'new ' + function ContentScriptScope() {552 // Verify listeners:553 let input = document.getElementById("input2");554 assert(input, "proxy.getElementById works");555 function onclick() {};556 input.onclick = onclick;557 assert(input.onclick === onclick, "on* attributes are equal to original function set");558 let addEventListenerCalled = false;559 let expandoCalled = false;560 input.addEventListener("click", function onclick(event) {561 assert(!addEventListenerCalled, "closure given to addEventListener is called once");562 if (addEventListenerCalled)563 return;564 addEventListenerCalled = true;565 assert(!event.target.ownerDocument.defaultView.documentGlobal, "event object is still wrapped and doesn't expose document globals");566 let input2 = document.getElementById("input2");567 input.onclick = function (event) {568 input.onclick = null;569 assert(!expandoCalled, "closure set to expando is called once");570 if (expandoCalled) return;571 expandoCalled = true;572 assert(!event.target.ownerDocument.defaultView.documentGlobal, "event object is still wrapped and doesn't expose document globals");573 setTimeout(function () {574 input.click();575 done();576 }, 0);577 }578 setTimeout(function () {579 input.click();580 }, 0);581 }, {capture: true, once: true});582 input.click();583 }584 );585});586exports["test requestAnimationFrame"] = createProxyTest("", function (helper) {587 helper.createWorker(588 'new ' + function ContentScriptScope() {589 var self = (function() { return this; })();590 window.requestAnimationFrame(function callback() {591 assert(self == this, "self is equal to `this`");592 done();593 });594 }595 );596});597exports["testGlobalScope"] = createProxyTest("", function (helper) {598 helper.createWorker(599 'var toplevelScope = true;' +600 'assert(window.toplevelScope, "variables in toplevel scope are set to `window` object");' +601 'assert(this.toplevelScope, "variables in toplevel scope are set to `this` object");' +602 'done();'603 );604});605// Bug 715755: proxy code throw an exception on COW606// Create an http server in order to simulate real cross domain documents607exports["test Cross Domain Iframe"] = createProxyTest("", function (helper) {608 let serverPort = 8099;609 let server = require("./lib/httpd").startServerAsync(serverPort);610 server.registerPathHandler("/", function handle(request, response) {611 // Returns the webpage that receive a message and forward it back to its612 // parent document by appending ' world'.613 let content = "<html><head><meta charset='utf-8'></head>\n";614 content += "<script>\n";615 content += " window.addEventListener('message', function (event) {\n";616 content += " parent.postMessage(event.data + ' world', '*');\n";617 content += " }, true);\n";618 content += "</script>\n";619 content += "<body></body>\n";620 content += "</html>\n";621 response.write(content);622 });623 let worker = helper.createWorker(624 'new ' + function ContentScriptScope() {625 // Waits for the server page url626 self.on("message", function (url) {627 // Creates an iframe with this page628 let iframe = document.createElement("iframe");629 iframe.addEventListener("load", function() {630 try {631 // Try to communicate with iframe's content632 window.addEventListener("message", function(event) {633 assert(event.data == "hello world", "COW works properly");634 self.port.emit("end");635 }, {capture: true, once: true});636 iframe.contentWindow.postMessage("hello", "*");637 } catch(e) {638 assert(false, "COW fails : "+e.message);639 }640 }, {capture: true, once: true});641 iframe.setAttribute("src", url);642 document.body.appendChild(iframe);643 });644 }645 );646 worker.port.on("end", function () {647 server.stop(helper.done);648 });649 worker.postMessage("http://localhost:" + serverPort + "/");650});651// Bug 769006: Ensure that MutationObserver works fine with proxies652var html = '<a href="foo">link</a>';653exports["test MutationObvserver"] = createProxyTest(html, function (helper) {654 helper.createWorker(655 'new ' + function ContentScriptScope() {656 if (typeof MutationObserver == "undefined") {657 assert(true, "No MutationObserver for this FF version");658 done();659 return;660 }661 let link = document.getElementsByTagName("a")[0];662 // Register a Mutation observer663 let obs = new MutationObserver(function(mutations){664 // Ensure that mutation data are valid665 assert(mutations.length == 1, "only one attribute mutation");666 let mutation = mutations[0];667 assert(mutation.type == "attributes", "check `type`");668 assert(mutation.target == link, "check `target`");669 assert(mutation.attributeName == "href", "check `attributeName`");670 assert(mutation.oldValue == "foo", "check `oldValue`");671 obs.disconnect();672 done();673 });674 obs.observe(document, {675 subtree: true,676 attributes: true,677 attributeOldValue: true,678 attributeFilter: ["href"]679 });680 // Modify the DOM681 link.setAttribute("href", "bar");682 }683 );684});685var html = '<script>' +686 'var accessCheck = function() {' +687 ' assert(true, "exporting function works");' +688 ' try{' +689 ' exportedObj.prop;' +690 ' assert(false, "content should not have access to content-script");' +691 ' } catch(e) {' +692 ' assert(e.toString().indexOf("Permission denied") != -1,' +693 ' "content should not have access to content-script");' +694 ' }' +695 '}</script>';696exports["test nsEp for content-script"] = createProxyTest(html, function (helper) {697 helper.createWorker(698 'let glob = this; new ' + function ContentScriptScope() {699 exportFunction(assert, unsafeWindow, { defineAs: "assert" });700 window.wrappedJSObject.assert(true, "assert exported");701 window.wrappedJSObject.exportedObj = { prop: 42 };702 window.wrappedJSObject.accessCheck();703 done();704 }705 );706});...

Full Screen

Full Screen

WorkPool.test.js

Source:WorkPool.test.js Github

copy

Full Screen

1/*2 * Copyright (c) 2002-2019 "Neo4j,"3 * Neo4j Sweden AB [http://neo4j.com]4 *5 * This file is part of Neo4j.6 *7 * Neo4j is free software: you can redistribute it and/or modify8 * it under the terms of the GNU General Public License as published by9 * the Free Software Foundation, either version 3 of the License, or10 * (at your option) any later version.11 *12 * This program is distributed in the hope that it will be useful,13 * but WITHOUT ANY WARRANTY; without even the implied warranty of14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the15 * GNU General Public License for more details.16 *17 * You should have received a copy of the GNU General Public License18 * along with this program. If not, see <http://www.gnu.org/licenses/>.19 */20/* global jest, beforeEach */21import { v4 as uuid } from 'uuid'22import WorkPool from './WorkPool'23describe('Workpool', () => {24 let createWorker25 let register26 let id27 let postMessage28 beforeEach(() => {29 postMessage = jest.fn()30 createWorker = jest.fn(() => {31 return {32 postMessage33 }34 })35 register = new WorkPool(createWorker)36 id = uuid()37 })38 test('can do and finish work', () => {39 // Given40 const work = {41 id42 }43 // When44 const workObj = register.doWork(work)45 // Then46 expect(register.getQueueSize()).toEqual(0)47 expect(register.getPoolSize()).toEqual(1)48 expect(register.getPoolSize(WorkPool.workerStates.BUSY)).toEqual(1)49 expect(register.getPoolSize(WorkPool.workerStates.FREE)).toEqual(0)50 expect(createWorker).toHaveBeenCalledTimes(1)51 expect(workObj.id).toEqual(id)52 // When53 workObj.finish()54 // Then55 expect(register.getQueueSize()).toEqual(0)56 expect(register.getPoolSize()).toEqual(1)57 expect(register.getPoolSize(WorkPool.workerStates.BUSY)).toEqual(0)58 expect(register.getPoolSize(WorkPool.workerStates.FREE)).toEqual(1)59 expect(createWorker).toHaveBeenCalledTimes(1)60 })61 test('can have onFinish ques', () => {62 // Given63 const id1 = { id: uuid() }64 const id2 = { id: uuid() }65 const id3 = { id: uuid() }66 const onFinishFn1 = jest.fn()67 const onFinishFn2 = jest.fn()68 const onFinishFn3 = jest.fn()69 // When70 const workObj1 = register.doWork(id1)71 const workObj2 = register.doWork(id2)72 workObj1.onFinish(onFinishFn1)73 workObj2.onFinish(onFinishFn2)74 // Then75 expect(createWorker).toHaveBeenCalledTimes(2)76 expect(onFinishFn1).toHaveBeenCalledTimes(0)77 expect(onFinishFn2).toHaveBeenCalledTimes(0)78 // When79 workObj1.finish()80 // Then81 expect(createWorker).toHaveBeenCalledTimes(2)82 expect(onFinishFn1).toHaveBeenCalledTimes(1)83 expect(onFinishFn2).toHaveBeenCalledTimes(0)84 // When85 const workObj3 = register.doWork(id3)86 workObj3.onFinish(onFinishFn3)87 workObj2.finish()88 // Then89 expect(onFinishFn1).toHaveBeenCalledTimes(1)90 expect(onFinishFn2).toHaveBeenCalledTimes(1)91 expect(onFinishFn3).toHaveBeenCalledTimes(0)92 // When93 workObj3.finish()94 // Then95 expect(onFinishFn1).toHaveBeenCalledTimes(1)96 expect(onFinishFn2).toHaveBeenCalledTimes(1)97 expect(onFinishFn3).toHaveBeenCalledTimes(1)98 })99 test('creates new workers if all are busy (not reaching pool size limit)', () => {100 // Given101 const id1 = { id: uuid() }102 const id2 = { id: uuid() }103 // When104 const workObj1 = register.doWork(id1)105 const workObj2 = register.doWork(id2)106 // Then107 expect(register.getPoolSize()).toEqual(2)108 expect(createWorker).toHaveBeenCalledTimes(2)109 expect(workObj1.id).toEqual(id1.id)110 expect(workObj2.id).toEqual(id2.id)111 expect(register.getPoolSize(WorkPool.workerStates.BUSY)).toEqual(2)112 expect(register.getPoolSize(WorkPool.workerStates.FREE)).toEqual(0)113 })114 test('re-uses workers if there are available ones', () => {115 // Given116 const id1 = { id: uuid() }117 const id2 = { id: uuid() }118 const id3 = { id: uuid() }119 const id4 = { id: uuid() }120 // When121 const workObj1 = register.doWork(id1)122 const workObj2 = register.doWork(id2)123 register.doWork(id3)124 workObj1.finish()125 workObj2.finish()126 // When127 register.doWork(id4)128 // Then129 expect(createWorker).toHaveBeenCalledTimes(3)130 expect(register.getPoolSize()).toEqual(3)131 expect(register.getPoolSize(WorkPool.workerStates.FREE)).toEqual(1)132 expect(register.getPoolSize(WorkPool.workerStates.BUSY)).toEqual(2)133 })134 it('exposes getWorkById and finds queued and ongoing work', () => {135 // Given136 const localRegister = new WorkPool(createWorker, 1)137 const initialWorkId = 'initial'138 // When139 // Just do some work so queue pool limit is reached140 const initialWorkObj = localRegister.doWork({ id: initialWorkId })141 const work = { id }142 const workObj = localRegister.doWork(work)143 // Then144 expect(createWorker).toHaveBeenCalledTimes(1)145 expect(workObj.id).toEqual(id)146 // When147 const workObj1 = localRegister.getWorkById(initialWorkId)148 const workObj2 = localRegister.getWorkById(id)149 // Then150 expect(workObj).toBe(workObj2) // same obj in memory151 expect(workObj1).toBe(initialWorkObj) // same obj in memory152 // When153 // Try something that's not there154 const notWorkObj = localRegister.getWorkById('not-present-id')155 // Then156 expect(notWorkObj).toEqual(null)157 })158 it('respcts the maxPoolSize and put jobs in queue', () => {159 // Given160 const poolSize = 2161 const localRegister = new WorkPool(createWorker, poolSize)162 const id1 = { id: uuid() }163 const id2 = { id: uuid() }164 const id3 = { id: uuid() }165 const id4 = { id: uuid() }166 // When167 const workObj1 = localRegister.doWork(id1)168 const workObj2 = localRegister.doWork(id2)169 const workObj3 = localRegister.doWork(id3)170 // Then171 expect(localRegister.getPoolSize()).toEqual(poolSize)172 expect(localRegister.getPoolSize(WorkPool.workerStates.BUSY)).toEqual(173 poolSize174 )175 expect(localRegister.getPoolSize(WorkPool.workerStates.FREE)).toEqual(0)176 expect(localRegister.getQueueSize()).toEqual(1)177 // When178 workObj1.finish()179 // Then180 expect(localRegister.getPoolSize()).toEqual(poolSize)181 expect(localRegister.getPoolSize(WorkPool.workerStates.BUSY)).toEqual(182 poolSize183 )184 expect(localRegister.getPoolSize(WorkPool.workerStates.FREE)).toEqual(0)185 expect(localRegister.getQueueSize()).toEqual(0)186 // When187 const workObj4 = localRegister.doWork(id4)188 // Then189 expect(localRegister.getPoolSize()).toEqual(poolSize)190 expect(localRegister.getPoolSize(WorkPool.workerStates.BUSY)).toEqual(191 poolSize192 )193 expect(localRegister.getPoolSize(WorkPool.workerStates.FREE)).toEqual(0)194 expect(localRegister.getQueueSize()).toEqual(1)195 // When196 workObj2.finish()197 workObj3.finish()198 workObj4.finish()199 // Then200 expect(createWorker).toHaveBeenCalledTimes(poolSize)201 expect(localRegister.getPoolSize()).toEqual(poolSize)202 expect(localRegister.getPoolSize(WorkPool.workerStates.FREE)).toEqual(203 poolSize204 )205 expect(localRegister.getPoolSize(WorkPool.workerStates.BUSY)).toEqual(0)206 })207 test('Can message all workers at once', () => {208 const message = { type: 'hello all' }209 const postMessage1 = jest.fn()210 const postMessage2 = jest.fn()211 const postMessage3 = jest.fn()212 const createWorker = jest213 .fn()214 .mockImplementationOnce(() => {215 return {216 postMessage: postMessage1217 }218 })219 .mockImplementationOnce(() => {220 return {221 postMessage: postMessage2222 }223 })224 .mockImplementationOnce(() => {225 return {226 postMessage: postMessage3227 }228 })229 const localRegister = new WorkPool(createWorker)230 const id1 = { id: uuid() } // No work, just to create workers231 const id2 = { id: uuid() } // No work, just to create workers232 const id3 = { id: uuid() } // No work, just to create workers233 // When234 localRegister.doWork(id1)235 localRegister.doWork(id2)236 localRegister.doWork(id3)237 localRegister.messageAllWorkers(message)238 // Then239 expect(postMessage1).toHaveBeenCalledTimes(1)240 expect(postMessage1).toHaveBeenCalledWith(message)241 expect(postMessage2).toHaveBeenCalledTimes(1)242 expect(postMessage2).toHaveBeenCalledWith(message)243 expect(postMessage3).toHaveBeenCalledTimes(1)244 expect(postMessage3).toHaveBeenCalledWith(message)245 })...

Full Screen

Full Screen

test-Worker.js

Source:test-Worker.js Github

copy

Full Screen

...7expect.extend({ toBeType });8let worker;9beforeEach(() => worker && !worker.closed && worker.close());10afterEach(() => worker && !worker.closed && worker.close());11test('createWorker() succeeds', async () =>12{13 const onObserverNewWorker = jest.fn();14 observer.once('newworker', onObserverNewWorker);15 worker = await createWorker();16 expect(onObserverNewWorker).toHaveBeenCalledTimes(1);17 expect(onObserverNewWorker).toHaveBeenCalledWith(worker);18 expect(worker).toBeType('object');19 expect(worker.pid).toBeType('number');20 expect(worker.closed).toBe(false);21 worker.close();22 expect(worker.closed).toBe(true);23 // eslint-disable-next-line require-atomic-updates24 worker = await createWorker(25 {26 logLevel : 'debug',27 logTags : [ 'info' ],28 rtcMinPort : 0,29 rtcMaxPort : 9999,30 dtlsCertificateFile : 'test/data/dtls-cert.pem',31 dtlsPrivateKeyFile : 'test/data/dtls-key.pem',32 appData : { bar: 456 }33 });34 expect(worker).toBeType('object');35 expect(worker.pid).toBeType('number');36 expect(worker.closed).toBe(false);37 expect(worker.appData).toEqual({ bar: 456 });38 worker.close();39 expect(worker.closed).toBe(true);40}, 2000);41test('createWorker() with wrong settings rejects with TypeError', async () =>42{43 await expect(createWorker({ logLevel: 'chicken' }))44 .rejects45 .toThrow(TypeError);46 await expect(createWorker({ rtcMinPort: 1000, rtcMaxPort: 999 }))47 .rejects48 .toThrow(TypeError);49 // Port is from 0 to 65535.50 await expect(createWorker({ rtcMinPort: 1000, rtcMaxPort: 65536 }))51 .rejects52 .toThrow(TypeError);53 await expect(createWorker({ dtlsCertificateFile: '/notfound/cert.pem' }))54 .rejects55 .toThrow(TypeError);56 await expect(createWorker({ dtlsPrivateKeyFile: '/notfound/priv.pem' }))57 .rejects58 .toThrow(TypeError);59 await expect(createWorker({ appData: 'NOT-AN-OBJECT' }))60 .rejects61 .toThrow(TypeError);62}, 2000);63test('worker.updateSettings() succeeds', async () =>64{65 worker = await createWorker();66 await expect(worker.updateSettings({ logLevel: 'debug', logTags: [ 'ice' ] }))67 .resolves68 .toBeUndefined();69 worker.close();70}, 2000);71test('worker.updateSettings() with wrong settings rejects with TypeError', async () =>72{73 worker = await createWorker();74 await expect(worker.updateSettings({ logLevel: 'chicken' }))75 .rejects76 .toThrow(TypeError);77 worker.close();78}, 2000);79test('worker.updateSettings() rejects with InvalidStateError if closed', async () =>80{81 worker = await createWorker();82 worker.close();83 await expect(worker.updateSettings({ logLevel: 'error' }))84 .rejects85 .toThrow(InvalidStateError);86 worker.close();87}, 2000);88test('worker.dump() succeeds', async () =>89{90 worker = await createWorker();91 await expect(worker.dump())92 .resolves93 .toEqual({ pid: worker.pid, routerIds: [] });94 worker.close();95}, 2000);96test('worker.dump() rejects with InvalidStateError if closed', async () =>97{98 worker = await createWorker();99 worker.close();100 await expect(worker.dump())101 .rejects102 .toThrow(InvalidStateError);103 worker.close();104}, 2000);105test('worker.getResourceUsage() succeeds', async () =>106{107 worker = await createWorker();108 await expect(worker.getResourceUsage())109 .resolves110 .toMatchObject({});111 worker.close();112}, 2000);113test('worker.close() succeeds', async () =>114{115 worker = await createWorker({ logLevel: 'warn' });116 const onObserverClose = jest.fn();117 worker.observer.once('close', onObserverClose);118 worker.close();119 expect(onObserverClose).toHaveBeenCalledTimes(1);120 expect(worker.closed).toBe(true);121}, 2000);122test('Worker emits "died" if worker process died unexpectedly', async () =>123{124 let onObserverClose;125 worker = await createWorker({ logLevel: 'warn' });126 onObserverClose = jest.fn();127 worker.observer.once('close', onObserverClose);128 await new Promise((resolve) =>129 {130 worker.on('died', resolve);131 process.kill(worker.pid, 'SIGINT');132 });133 expect(onObserverClose).toHaveBeenCalledTimes(1);134 expect(worker.closed).toBe(true);135 // eslint-disable-next-line require-atomic-updates136 worker = await createWorker({ logLevel: 'warn' });137 onObserverClose = jest.fn();138 worker.observer.once('close', onObserverClose);139 await new Promise((resolve) =>140 {141 worker.on('died', resolve);142 process.kill(worker.pid, 'SIGTERM');143 });144 expect(onObserverClose).toHaveBeenCalledTimes(1);145 expect(worker.closed).toBe(true);146 // eslint-disable-next-line require-atomic-updates147 worker = await createWorker({ logLevel: 'warn' });148 onObserverClose = jest.fn();149 worker.observer.once('close', onObserverClose);150 await new Promise((resolve) =>151 {152 worker.on('died', resolve);153 process.kill(worker.pid, 'SIGKILL');154 });155 expect(onObserverClose).toHaveBeenCalledTimes(1);156 expect(worker.closed).toBe(true);157}, 5000);158test('worker process ignores PIPE, HUP, ALRM, USR1 and USR2 signals', async () =>159{160 // Windows doesn't have some signals such as SIGPIPE, SIGALRM, SIGUSR1, SIGUSR2161 // so we just skip this test in Windows.162 if (os.platform() === 'win32')163 return;164 worker = await createWorker({ logLevel: 'warn' });165 await new Promise((resolve, reject) =>166 {167 worker.on('died', reject);168 process.kill(worker.pid, 'SIGPIPE');169 process.kill(worker.pid, 'SIGHUP');170 process.kill(worker.pid, 'SIGALRM');171 process.kill(worker.pid, 'SIGUSR1');172 process.kill(worker.pid, 'SIGUSR2');173 setTimeout(() =>174 {175 expect(worker.closed).toBe(false);176 worker.close();177 resolve();178 }, 2000);...

Full Screen

Full Screen

wk06d03.inheritance.test.js

Source:wk06d03.inheritance.test.js Github

copy

Full Screen

...40 });41 /*42 * Wrapper functions43 */44 async function createWorker(boss, worker, from) {45 const createWorkersFrom = bossCreatesWorkers ?46 boss : worker.account;47 return instance.createWorker(48 worker.name,49 worker.age,50 worker.height,51 worker.salary,52 worker.account,53 { from: from || createWorkersFrom }54 );55 }56 async function getSalary(address) {57 return instance.salary(address);58 }59 async function fire(worker, from) {60 return instance.fire(61 worker.account,62 { from: from || worker.boss }63 );64 }65 async function getBoss(address) {66 return instance.bossOf(address);67 }68 describe('create worker', () => {69 it('should set the worker salary', async () => {70 await createWorker(bossAccount, worker);71 const result = await getSalary(worker.account);72 expect(result.toString(10)).to.equal(worker.salary.toString(10));73 });74 it('should create a person with the supplied values', async () => {75 await createWorker(bossAccount, worker);76 const result = await getPerson(instance, worker.account);77 expectPerson(result, worker);78 });79 it('should REVERT if the worker age is over 75', async () => {80 worker.age = 76;81 worker.senior = true;82 await truffleAssert.reverts(83 createWorker(bossAccount, worker),84 truffleAssert.ErrorType.REVERT85 );86 });87 describe('bonus', () => {88 it('should store the boss of the worker', async () => {89 await createWorker(bossAccount, worker);90 const result = await getBoss(worker.account);91 expect(result).to.equal(bossAccount);92 });93 it('should REVERT if sender and boss are the same', async () => {94 await truffleAssert.reverts(95 createWorker(worker.account, worker, worker.account),96 truffleAssert.ErrorType.REVERT97 );98 });99 });100 });101 describe('fire', () => {102 beforeEach(async () => {103 await createWorker(bossAccount, worker);104 });105 it('should remove the worker salary', async () => {106 await fire(worker);107 const result = await getSalary(worker.account);108 expect(result.toString(10)).to.equal('0');109 });110 it('should delete the person', async () => {111 await fire(worker);112 const person = await getPerson(instance, worker.account);113 expect(person.name).to.equal('');114 });115 describe('bonus', () => {116 it('should REVERT if the sender is not the workers boss', async () => {117 const angryCowokerker = accounts[3];...

Full Screen

Full Screen

handler.js

Source:handler.js Github

copy

Full Screen

...15 case 'POST':16 const zbc = new zb.ZBClient(zeebe_credentials, { loglevel: 'INFO' });17 const orderid = uuid.v4()18 // DECLARATION OF ANY PROCESS:19 zbc.createWorker('order-activity', async (job, complete) => {20 const { key, variables } = job;21 console.info(`* Starting Order...: ${variables}`);22 //const stock = 100; //Aqui se revisa el stock con una request23 complete.success({variables: variables, orderid: orderid });24 console.info(`* Passing to next task: ${variables}`);25 });26 zbc.createWorker('arrive-activity', async (job, complete) => {27 const { key, variables } = job;28 console.info(`* Arriving Order...: ${variables}`);29 complete.success({variables: variables, orderid: orderid });30 console.info(`* Passing to next task: ${variables}`);31 });32 zbc.createWorker('delivery-activity', async (job, complete) => { 33 const { key, variables } = job;34 console.info(`* Delivering Order...: ${variables}`);35 complete.success({variables: variables, orderid: orderid });36 console.info(`* Passing to next task: ${variables}`);37 });38 zbc.createWorker('on-warehouse-activity', async (job, complete) => { 39 const { key, variables } = job;40 console.info(`* Order On Warehouse...: ${variables}`);41 complete.success({variables: variables, orderid: orderid });42 console.info(`* Passing to next task: ${variables}`);43 });44 zbc.createWorker('process-pay-activity', async (job, complete) => { 45 const { key, variables } = job;46 console.info(`* Process pay order...: ${variables}`);47 complete.success({variables: variables, orderid: orderid });48 console.info(`* Passing to next task: ${variables}`);49 });50 zbc.createWorker('receive-activity', async (job, complete) => { 51 const { key, variables } = job;52 console.info(`* Receiving Order...: ${variables}`);53 complete.success({variables: variables, orderid: orderid });54 console.info(`* Passing to next task: ${variables}`);55 });56 zbc.createWorker('send-alert-admin-activity', async (job, complete) => { 57 const { key, variables } = job;58 console.info(`* Sending Alert to Admin ...: ${variables}`);59 complete.success({variables: variables, orderid: orderid });60 console.info(`* Passing to next task: ${variables}`);61 });62 zbc.createWorker('send-alert-client-activity', async (job, complete) => { 63 const { key, variables } = job;64 console.info(`* Sending Alert to Client ...: ${variables}`);65 complete.success({variables: variables, orderid: orderid });66 console.info(`* Passing to next task: ${variables}`);67 });68 zbc.createWorker('cancel-order-activity', async (job, complete) => { 69 const { key, variables } = job;70 console.info(`* Canceling Order ...: ${variables}`);71 complete.success({variables: variables, orderid: orderid });72 console.info(`* Passing to next task: ${variables}`);73 });74 zbc.createWorker('send-activity', async (job, complete) => { 75 const { key, variables } = job;76 console.info(`* Sending Package ...: ${variables}`);77 complete.success({variables: variables, orderid: orderid });78 console.info(`* Passing to next task: ${variables}`);79 });80 zbc.createWorker('on-ship-activity', async (job, complete) => { 81 const { key, variables } = job;82 console.info(`* Shipping Package ...: ${variables}`);83 complete.success({variables: variables, orderid: orderid });84 console.info(`* Passing to next task: ${variables}`);85 });86 //const newsbc = createWorkers(zbc);87 const wfi = await zbc.createWorkflowInstance("process-orders", data);88 wfi.orderid = orderid;89 context.succeed({ res: data , wfi });90 break;91 default:92 context.status(405).succeed({ res: false });93 break;94 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...21 const zbc = new zb.ZBClient(zeebe_credentials, { loglevel: 'INFO' });22 2324 // DECLARATION OF ANY PROCESS:25 zbc.createWorker('order-activity', async (job, complete) => {26 const { key, variables } = job;27 console.info(`* Starting Order...: ${variables}`);28 29 //const stock = 100; //Aqui se revisa el stock con una request30 complete.success({variables: variables});31 console.info(`* Passing to next task: ${variables}`);32 });3334 35 zbc.createWorker('on-warehouse-activity', async (job, complete) => { 36 const { key, variables } = job;37 console.info(`* Order On Warehouse...: ${variables}`);38 complete.success({variables: variables});39 console.info(`* Passing to next task: ${variables}`);40 });4142 4344 zbc.createWorker('arrive-activity', async (job, complete) => {45 const { key, variables } = job;46 console.info(`* Arriving Order...: ${variables}`);47 complete.success({variables: variables});48 console.info(`* Passing to next task: ${variables}`);49 });5051 zbc.createWorker('delivery-activity', async (job, complete) => { 52 const { key, variables } = job;53 console.info(`* Delivering Order...: ${variables}`);54 complete.success({variables: variables });55 console.info(`* Passing to next task: ${variables}`);56 });5758 59 zbc.createWorker('process-pay-activity', async (job, complete) => { 60 const { key, variables } = job;61 console.info(`* Process pay order...: ${variables}`);62 complete.success({variables: variables });63 console.info(`* Passing to next task: ${variables}`);64 });6566 zbc.createWorker('receive-activity', async (job, complete) => { 67 const { key, variables } = job;68 console.info(`* Receiving Order...: ${variables}`);69 complete.success({variables: variables});70 console.info(`* Passing to next task: ${variables}`);71 });7273 zbc.createWorker('send-alert-admin-activity', async (job, complete) => { 74 const { key, variables } = job;75 console.info(`* Sending Alert to Admin ...: ${variables}`);76 complete.success({variables: variables });77 console.info(`* Passing to next task: ${variables}`);78 });7980 zbc.createWorker('send-alert-client-activity', async (job, complete) => { 81 const { key, variables } = job;82 console.info(`* Sending Alert to Client ...: ${variables}`);83 complete.success({variables: variables});84 console.info(`* Passing to next task: ${variables}`);85 });8687 zbc.createWorker('cancel-order-activity', async (job, complete) => { 88 const { key, variables } = job;89 console.info(`* Canceling Order ...: ${variables}`);90 complete.success({variables: variables });91 console.info(`* Passing to next task: ${variables}`);92 });9394 zbc.createWorker('send-activity', async (job, complete) => { 95 const { key, variables } = job;96 console.info(`* Sending Package ...: ${variables}`);97 complete.success({variables: variables});98 console.info(`* Passing to next task: ${variables}`);99 });100101 zbc.createWorker('on-ship-activity', async (job, complete) => { 102 const { key, variables } = job;103 console.info(`* Shipping Package ...: ${variables}`);104 complete.success({variables: variables });105 console.info(`* Passing to next task: ${variables}`);106 });107108109 //const newsbc = createWorkers(zbc);110 data.orderid = uuid.v4()111 const wfi = await zbc.createWorkflowInstance("process-orders", data);112 //wfi.orderid = orderid;113 return {status: 200,114 body : { res: data , wfi },115 headers: { ...

Full Screen

Full Screen

workers.js

Source:workers.js Github

copy

Full Screen

1'use strict';2import { createReducer } from '../util';3import { F } from '~/common/util';4const STATE = F({5 delreq: createWorker()6});7function createWorker(opts) {8 let {9 tasks = [],10 id = null11 } = opts || {};12 tasks = F(tasks || []);13 return F({ tasks, id });14}15export default createReducer(STATE, {16 'SET_APP_WORKERS': reduce,17 'CLEAR_APP_WORKER_ID': clearWorkerId18});19function reduce(state = STATE, action) {20 let { delreq } = action;21 delreq = reduceWorker(state.delreq, delreq);22 let newState = {23 delreq24 };25 return F(newState);26}27function clearWorkerId(state = STATE, action) {28 let { worker } = action;29 let newState = { ...state };30 newState[worker] = createWorker({ ...state[worker], id: null });31 return F(newState);32}33const WORKER = createWorker();34function reduceWorker(prev = WORKER, next) {35 if (next == null) return prev;36 if (prev.id != null && prev.id !== next.id) return prev;37 let newState = { ...prev, ...next };38 return createWorker(newState);39}40export const internal = {41 createWorker,42 reduce,43 clearWorkerId...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createWorker } = require('@playwright/test');2const worker = await createWorker();3const browser = await worker.createBrowser();4const context = await browser.newContext();5const page = await context.newPage();6await page.screenshot({ path: 'screenshot.png' });7await browser.close();8await worker.close();9const { test, expect } = require('@playwright/test');10test('should display "Learn more"', async ({ page }) => {11 const text = await page.textContent('.navbar__title');12 expect(text).toBe('Learn more');13});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createWorker } = require('playwright');2const worker = await createWorker();3const browser = await worker.launchBrowser();4const context = await browser.newContext();5const page = await context.newPage();6await page.screenshot({ path: 'example.png' });7await browser.close();8await worker.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createWorker } = require('@playwright/test');2const worker = await createWorker();3const context = await worker.createBrowserContext();4const page = await context.newPage();5await page.screenshot({ path: 'example.png' });6await context.close();7await worker.terminate();8const { createWorker } = require('@playwright/test');9const worker = await createWorker();10const context = await worker.createBrowserContext();11const page = await context.newPage();12await page.screenshot({ path: 'example.png' });13await context.close();14await worker.terminate();15const { createWorker } = require('@playwright/test');16const worker = await createWorker();17const context = await worker.createBrowserContext();18const page = await context.newPage();19await page.screenshot({ path: 'example.png' });20await context.close();21await worker.terminate();22const { createWorker } = require('@playwright/test');23const worker = await createWorker();24const context = await worker.createBrowserContext();25const page = await context.newPage();26await page.screenshot({ path: 'example.png' });27await context.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createWorker } = require('playwright-core/lib/server/worker');2const worker = await createWorker({3});4const page = await worker.newPage();5await page.screenshot({ path: 'example.png' });6await worker.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright-internal');2const worker = playwright.createWorker();3(async () => {4 await worker.run(async ({ chromium }) => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'example.png' });9 await browser.close();10 });11})();12#### playwright.createWorker([options])13#### playwright.executablePath()14#### playwright.selectBrowser(options)15#### worker.run([options], callback)16#### worker.stop()17#### browserType.launch([options])

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createWorker } = require('@playwright/test');2const worker = await createWorker();3const worker = await createWorker();4const page = await worker.newPage();5await page.screenshot({ path: 'example.png' });6await worker.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createWorker } = require('@playwright/test');2const worker = await createWorker();3const browser = await worker.createBrowser();4await browser.close();5await worker.destroy();6### `worker.createBrowser(options)`

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createWorker } = require("playwright-core/lib/server/worker");2const path = require("path");3(async () => {4 const worker = await createWorker({5 playwrightPath: path.join(__dirname, "node_modules", "playwright-core"),6 });7 const browser = await worker.createBrowser({8 env: {},9 });10 const context = await browser.newContext({11 });12 const page = await context.newPage();13 const title = await page.title();14 console.log(title);15 await browser.close();16 await worker.stop();17})();18[Apache-2.0](LICENSE)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createWorker } = require('@playwright/test');2const worker = await createWorker({3});4const browser = await worker.launchBrowser();5const page = await browser.newPage();6await page.screenshot({ path: 'example.png' });7await browser.close();8await worker.close();9import { test, expect } from '@playwright/test';10test('basic test', async ({ page }) => {11 await page.screenshot({ path: 'example.png' });12 expect(page).toHaveText('Get started');13});14import { test, expect } from '@playwright/test';15test('basic test', async ({ page }) => {16 await page.screenshot({ path: 'example.png' });17 expect(page).toHaveText('Get started');18});19import { test, expect } from '@playwright/test';20test('basic test', async ({ page }) => {

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful