worker_driver.js (2845B)
1 // Any copyright is dedicated to the Public Domain. 2 // http://creativecommons.org/publicdomain/zero/1.0/ 3 // 4 // Utility script for writing worker tests. In your main document do: 5 // 6 // <script type="text/javascript" src="worker_driver.js"></script> 7 // <script type="text/javascript"> 8 // workerTestExec('myWorkerTestCase.js') 9 // </script> 10 // 11 // This will then spawn a worker, define some utility functions, and then 12 // execute the code in myWorkerTestCase.js. You can then use these 13 // functions in your worker-side test: 14 // 15 // ok() - like the SimpleTest assert 16 // is() - like the SimpleTest assert 17 // workerTestDone() - like SimpleTest.finish() indicating the test is complete 18 // 19 // There are also some functions for requesting information that requires 20 // SpecialPowers or other main-thread-only resources: 21 // 22 // workerTestGetPrefs() - request an array of prefs value from the main thread 23 // workerTestGetPermissions() - request an array permissions from the MT 24 // workerTestGetVersion() - request the current version string from the MT 25 // workerTestGetUserAgent() - request the user agent string from the MT 26 // 27 // For an example see test_worker_interfaces.html and test_worker_interfaces.js. 28 29 function workerTestExec(script) { 30 return new Promise(function (resolve, reject) { 31 var worker = new Worker("worker_wrapper.js"); 32 worker.onmessage = function (event) { 33 is( 34 event.data.context, 35 "Worker", 36 "Correct context for messages received on the worker" 37 ); 38 if (event.data.type == "finish") { 39 worker.terminate(); 40 SpecialPowers.forceGC(); 41 resolve(); 42 } else if (event.data.type == "status") { 43 ok(event.data.status, event.data.context + ": " + event.data.msg); 44 } else if (event.data.type == "getPrefs") { 45 let result = {}; 46 event.data.prefs.forEach(function (pref) { 47 result[pref] = SpecialPowers.Services.prefs.getBoolPref(pref); 48 }); 49 worker.postMessage({ 50 type: "returnPrefs", 51 prefs: event.data.prefs, 52 result, 53 }); 54 } else if (event.data.type == "getPermissions") { 55 let result = {}; 56 event.data.permissions.forEach(function (permission) { 57 result[permission] = SpecialPowers.hasPermission( 58 permission, 59 window.document 60 ); 61 }); 62 worker.postMessage({ 63 type: "returnPermissions", 64 permissions: event.data.permissions, 65 result, 66 }); 67 } else if (event.data.type == "getUserAgent") { 68 worker.postMessage({ 69 type: "returnUserAgent", 70 result: navigator.userAgent, 71 }); 72 } 73 }; 74 75 worker.onerror = function (event) { 76 reject("Worker had an error: " + event.data); 77 }; 78 79 worker.postMessage({ script }); 80 }); 81 }