PageRenderTime 54ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/thunderbird-14.0/comm-release/mail/test/resources/mozmill/mozmill/extension/resource/modules/utils.js

#
JavaScript | 543 lines | 266 code | 53 blank | 224 comment | 43 complexity | 22efbe0aa2cfb54a2fb1b51717101170 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, JSON, LGPL-3.0, AGPL-1.0, CC-BY-SA-3.0, LGPL-2.1, BSD-3-Clause, GPL-2.0, Apache-2.0, 0BSD, MIT
  1. // ***** BEGIN LICENSE BLOCK *****
  2. // Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. //
  4. // The contents of this file are subject to the Mozilla Public License Version
  5. // 1.1 (the "License"); you may not use this file except in compliance with
  6. // the License. You may obtain a copy of the License at
  7. // http://www.mozilla.org/MPL/
  8. //
  9. // Software distributed under the License is distributed on an "AS IS" basis,
  10. // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. // for the specific language governing rights and limitations under the
  12. // License.
  13. //
  14. // The Original Code is Mozilla Corporation Code.
  15. //
  16. // The Initial Developer of the Original Code is
  17. // Adam Christian.
  18. // Portions created by the Initial Developer are Copyright (C) 2008
  19. // the Initial Developer. All Rights Reserved.
  20. //
  21. // Contributor(s):
  22. // Adam Christian <adam.christian@gmail.com>
  23. // Mikeal Rogers <mikeal.rogers@gmail.com>
  24. // Henrik Skupin <hskupin@mozilla.com>
  25. //
  26. // Alternatively, the contents of this file may be used under the terms of
  27. // either the GNU General Public License Version 2 or later (the "GPL"), or
  28. // the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  29. // in which case the provisions of the GPL or the LGPL are applicable instead
  30. // of those above. If you wish to allow use of your version of this file only
  31. // under the terms of either the GPL or the LGPL, and not to allow others to
  32. // use your version of this file under the terms of the MPL, indicate your
  33. // decision by deleting the provisions above and replace them with the notice
  34. // and other provisions required by the GPL or the LGPL. If you do not delete
  35. // the provisions above, a recipient may use your version of this file under
  36. // the terms of any one of the MPL, the GPL or the LGPL.
  37. //
  38. // ***** END LICENSE BLOCK *****
  39. var EXPORTED_SYMBOLS = ["openFile", "saveFile", "saveAsFile", "genBoiler",
  40. "getFile", "Copy", "getChromeWindow", "getWindows", "runEditor",
  41. "runFile", "getWindowByTitle", "getWindowByType", "tempfile",
  42. "getMethodInWindows", "getPreference", "setPreference",
  43. "sleep", "assert", "unwrapNode", "TimeoutError", "waitFor", "waitForEval"];
  44. var hwindow = Components.classes["@mozilla.org/appshell/appShellService;1"]
  45. .getService(Components.interfaces.nsIAppShellService)
  46. .hiddenDOMWindow;
  47. var uuidgen = Components.classes["@mozilla.org/uuid-generator;1"]
  48. .getService(Components.interfaces.nsIUUIDGenerator);
  49. function Copy (obj) {
  50. for (var n in obj) {
  51. this[n] = obj[n];
  52. }
  53. }
  54. function getChromeWindow(aWindow) {
  55. var chromeWin = aWindow
  56. .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  57. .getInterface(Components.interfaces.nsIWebNavigation)
  58. .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
  59. .rootTreeItem
  60. .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  61. .getInterface(Components.interfaces.nsIDOMWindow)
  62. .QueryInterface(Components.interfaces.nsIDOMChromeWindow);
  63. return chromeWin;
  64. }
  65. function getWindows(type) {
  66. if (type == undefined) {
  67. type = "";
  68. }
  69. var windows = []
  70. var enumerator = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  71. .getService(Components.interfaces.nsIWindowMediator)
  72. .getEnumerator(type);
  73. while(enumerator.hasMoreElements()) {
  74. windows.push(enumerator.getNext());
  75. }
  76. if (type == "") {
  77. windows.push(hwindow);
  78. }
  79. return windows;
  80. }
  81. function getMethodInWindows (methodName) {
  82. for each(w in getWindows()) {
  83. if (w[methodName] != undefined) {
  84. return w[methodName];
  85. }
  86. }
  87. throw new Error("Method with name: '" + methodName + "' is not in any open window.");
  88. }
  89. function getWindowByTitle(title) {
  90. for each(w in getWindows()) {
  91. if (w.document.title && w.document.title == title) {
  92. return w;
  93. }
  94. }
  95. }
  96. function getWindowByType(type) {
  97. var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  98. .getService(Components.interfaces.nsIWindowMediator);
  99. return wm.getMostRecentWindow(type);
  100. }
  101. function tempfile(appention) {
  102. if (appention == undefined) {
  103. var appention = "mozmill.utils.tempfile"
  104. }
  105. var tempfile = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("TmpD", Components.interfaces.nsIFile);
  106. tempfile.append(uuidgen.generateUUID().toString().replace('-', '').replace('{', '').replace('}',''))
  107. tempfile.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
  108. tempfile.append(appention);
  109. tempfile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0666);
  110. // do whatever you need to the created file
  111. return tempfile.clone()
  112. }
  113. var checkChrome = function() {
  114. var loc = window.document.location.href;
  115. try {
  116. loc = window.top.document.location.href;
  117. } catch (e) {}
  118. if (/^chrome:\/\//.test(loc)) { return true; }
  119. else { return false; }
  120. }
  121. /*var openFile = function(){
  122. const nsIFilePicker = Components.interfaces.nsIFilePicker;
  123. var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  124. fp.init(window, "Select a Test Directory", nsIFilePicker.modeGetFolder);
  125. var rv = fp.show();
  126. if (rv == Components.interfaces.nsIFilePicker.returnOK){
  127. // file is the given directory (nsIFile)
  128. var array = [];
  129. //iterate directories recursively
  130. recurseDir = function(ent){
  131. var entries = ent;
  132. while(entries.hasMoreElements())
  133. {
  134. var entry = entries.getNext();
  135. entry.QueryInterface(Components.interfaces.nsIFile);
  136. if ((entry.isDirectory()) && (entry.path.indexOf('.svn') == -1)){
  137. recurseDir(entry.directoryEntries);
  138. }
  139. //push js files onto the array
  140. if (entry.path.indexOf('.js') != -1){
  141. array.push(entry.path);
  142. }
  143. }
  144. }
  145. //build the files array
  146. recurseDir(fp.file.directoryEntries);
  147. paramObj = {};
  148. paramObj.files = array;
  149. mozmill.MozMillController.commands.jsTests(paramObj);
  150. }*/
  151. var runFile = function(w){
  152. //define the interface
  153. var nsIFilePicker = Components.interfaces.nsIFilePicker;
  154. var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  155. //define the file picker window
  156. fp.init(w, "Select a File", nsIFilePicker.modeOpen);
  157. fp.appendFilter("JavaScript Files","*.js");
  158. //show the window
  159. var res = fp.show();
  160. //if we got a file
  161. if (res == nsIFilePicker.returnOK){
  162. var thefile = fp.file;
  163. //create the paramObj with a files array attrib
  164. var paramObj = {};
  165. paramObj.files = [];
  166. paramObj.files.push(thefile.path);
  167. //Move focus to output tab
  168. //w.document.getElementById('mmtabs').setAttribute("selectedIndex", 2);
  169. //send it into the JS test framework to run the file
  170. // jstest.runFromFile(thefile.path);
  171. }
  172. };
  173. var saveFile = function(w, content, filename){
  174. //define the file interface
  175. var file = Components.classes["@mozilla.org/file/local;1"]
  176. .createInstance(Components.interfaces.nsILocalFile);
  177. //point it at the file we want to get at
  178. file.initWithPath(filename);
  179. // file is nsIFile, data is a string
  180. var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
  181. .createInstance(Components.interfaces.nsIFileOutputStream);
  182. // use 0x02 | 0x10 to open file for appending.
  183. foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);
  184. // write, create, truncate
  185. // In a c file operation, we have no need to set file mode with or operation,
  186. // directly using "r" or "w" usually.
  187. foStream.write(content, content.length);
  188. foStream.close();
  189. };
  190. var saveAsFile = function(w, content){
  191. //define the interface
  192. var nsIFilePicker = Components.interfaces.nsIFilePicker;
  193. var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  194. //define the file picker window
  195. fp.init(w, "Select a File", nsIFilePicker.modeSave);
  196. fp.appendFilter("JavaScript Files","*.js");
  197. //show the window
  198. var res = fp.show();
  199. //if we got a file
  200. if ((res == nsIFilePicker.returnOK) || (res == nsIFilePicker.returnReplace)){
  201. var thefile = fp.file;
  202. //forcing the user to save as a .js file
  203. if (thefile.path.indexOf(".js") == -1){
  204. //define the file interface
  205. var file = Components.classes["@mozilla.org/file/local;1"]
  206. .createInstance(Components.interfaces.nsILocalFile);
  207. //point it at the file we want to get at
  208. file.initWithPath(thefile.path+".js");
  209. var thefile = file;
  210. }
  211. // file is nsIFile, data is a string
  212. var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
  213. .createInstance(Components.interfaces.nsIFileOutputStream);
  214. // use 0x02 | 0x10 to open file for appending.
  215. foStream.init(thefile, 0x02 | 0x08 | 0x20, 0666, 0);
  216. // write, create, truncate
  217. // In a c file operation, we have no need to set file mode with or operation,
  218. // directly using "r" or "w" usually.
  219. foStream.write(content, content.length);
  220. foStream.close();
  221. return thefile.path;
  222. }
  223. };
  224. var openFile = function(w){
  225. //define the interface
  226. var nsIFilePicker = Components.interfaces.nsIFilePicker;
  227. var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  228. //define the file picker window
  229. fp.init(w, "Select a File", nsIFilePicker.modeOpen);
  230. fp.appendFilter("JavaScript Files","*.js");
  231. //show the window
  232. var res = fp.show();
  233. //if we got a file
  234. if (res == nsIFilePicker.returnOK){
  235. var thefile = fp.file;
  236. //create the paramObj with a files array attrib
  237. var data = getFile(thefile.path);
  238. //w.document.getElementById('editorInput').value = data;
  239. //Move focus to output tab
  240. //$('mmtabs').setAttribute("selectedIndex", 2);
  241. //send it into the JS test framework to run the file
  242. //mozmill.utils.jsTests(paramObj);
  243. //jsTest.runFromString(thefile.path);
  244. return {path:thefile.path, data:data};
  245. }
  246. };
  247. var getFile = function(path){
  248. //define the file interface
  249. var file = Components.classes["@mozilla.org/file/local;1"]
  250. .createInstance(Components.interfaces.nsILocalFile);
  251. //point it at the file we want to get at
  252. file.initWithPath(path);
  253. // define file stream interfaces
  254. var data = "";
  255. var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  256. .createInstance(Components.interfaces.nsIFileInputStream);
  257. var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
  258. .createInstance(Components.interfaces.nsIScriptableInputStream);
  259. fstream.init(file, -1, 0, 0);
  260. sstream.init(fstream);
  261. //pull the contents of the file out
  262. var str = sstream.read(4096);
  263. while (str.length > 0) {
  264. data += str;
  265. str = sstream.read(4096);
  266. }
  267. sstream.close();
  268. fstream.close();
  269. //data = data.replace(/\r|\n|\r\n/g, "");
  270. return data;
  271. };
  272. /**
  273. * Called to get the state of an individual preference.
  274. *
  275. * @param aPrefName string The preference to get the state of.
  276. * @param aDefaultValue any The default value if preference was not found.
  277. *
  278. * @returns any The value of the requested preference
  279. *
  280. * @see setPref
  281. * Code by Henrik Skupin: <hskupin@gmail.com>
  282. */
  283. function getPreference(aPrefName, aDefaultValue) {
  284. try {
  285. var branch = Components.classes["@mozilla.org/preferences-service;1"].
  286. getService(Components.interfaces.nsIPrefBranch);
  287. switch (typeof aDefaultValue) {
  288. case ('boolean'):
  289. return branch.getBoolPref(aPrefName);
  290. case ('string'):
  291. return branch.getCharPref(aPrefName);
  292. case ('number'):
  293. return branch.getIntPref(aPrefName);
  294. default:
  295. return branch.getComplexValue(aPrefName);
  296. }
  297. } catch(e) {
  298. return aDefaultValue;
  299. }
  300. }
  301. /**
  302. * Called to set the state of an individual preference.
  303. *
  304. * @param aPrefName string The preference to set the state of.
  305. * @param aValue any The value to set the preference to.
  306. *
  307. * @returns boolean Returns true if value was successfully set.
  308. *
  309. * @see getPref
  310. * Code by Henrik Skupin: <hskupin@gmail.com>
  311. */
  312. function setPreference(aName, aValue) {
  313. try {
  314. var branch = Components.classes["@mozilla.org/preferences-service;1"].
  315. getService(Components.interfaces.nsIPrefBranch);
  316. switch (typeof aValue) {
  317. case ('boolean'):
  318. branch.setBoolPref(aName, aValue);
  319. break;
  320. case ('string'):
  321. branch.setCharPref(aName, aValue);
  322. break;
  323. case ('number'):
  324. branch.setIntPref(aName, aValue);
  325. break;
  326. default:
  327. branch.setComplexValue(aName, aValue);
  328. }
  329. } catch(e) {
  330. return false;
  331. }
  332. return true;
  333. }
  334. /**
  335. * Sleep for the given amount of milliseconds
  336. *
  337. * @param {number} milliseconds
  338. * Sleeps the given number of milliseconds
  339. */
  340. function sleep(milliseconds) {
  341. // We basically just call this once after the specified number of milliseconds
  342. var timeup = false;
  343. function wait() { timeup = true; }
  344. hwindow.setTimeout(wait, milliseconds);
  345. var thread = Components.classes["@mozilla.org/thread-manager;1"].
  346. getService().currentThread;
  347. while(!timeup) {
  348. thread.processNextEvent(true);
  349. }
  350. }
  351. /**
  352. * Check if the callback function evaluates to true
  353. */
  354. function assert(callback, message, thisObject) {
  355. var result = callback.call(thisObject);
  356. if (!result) {
  357. throw new Error(message || arguments.callee.name + ": Failed for '" + callback + "'");
  358. }
  359. return true;
  360. }
  361. /**
  362. * Unwraps a node which is wrapped into a XPCNativeWrapper or XrayWrapper
  363. *
  364. * @param {DOMnode} Wrapped DOM node
  365. * @returns {DOMNode} Unwrapped DOM node
  366. */
  367. function unwrapNode(aNode) {
  368. var node = aNode;
  369. if (node) {
  370. // unwrap is not available on older branches (3.5 and 3.6) - Bug 533596
  371. if ("unwrap" in XPCNativeWrapper) {
  372. node = XPCNativeWrapper.unwrap(node);
  373. }
  374. else if (node.wrappedJSObject != null) {
  375. node = node.wrappedJSObject;
  376. }
  377. }
  378. return node;
  379. }
  380. /**
  381. * TimeoutError
  382. *
  383. * Error object used for timeouts
  384. */
  385. function TimeoutError(message, fileName, lineNumber) {
  386. var err = new Error();
  387. if (err.stack) {
  388. this.stack = err.stack;
  389. }
  390. this.message = message === undefined ? err.message : message;
  391. this.fileName = fileName === undefined ? err.fileName : fileName;
  392. this.lineNumber = lineNumber === undefined ? err.lineNumber : lineNumber;
  393. };
  394. TimeoutError.prototype = new Error();
  395. TimeoutError.prototype.constructor = TimeoutError;
  396. TimeoutError.prototype.name = 'TimeoutError';
  397. /**
  398. * Waits for the callback evaluates to true
  399. */
  400. function waitFor(callback, message, timeout, interval, thisObject) {
  401. timeout = timeout || 5000;
  402. interval = interval || 100;
  403. var self = {counter: 0, result: callback.call(thisObject)};
  404. function wait() {
  405. self.counter += interval;
  406. self.result = callback.call(thisObject);
  407. }
  408. var timeoutInterval = hwindow.setInterval(wait, interval);
  409. var thread = Components.classes["@mozilla.org/thread-manager;1"].
  410. getService().currentThread;
  411. while((self.result != true) && (self.counter < timeout)) {
  412. thread.processNextEvent(true);
  413. }
  414. hwindow.clearInterval(timeoutInterval);
  415. if (self.counter >= timeout) {
  416. message = message || arguments.callee.name + ": Timeout exceeded for '" + callback + "'";
  417. throw new TimeoutError(message);
  418. }
  419. return true;
  420. }
  421. /**
  422. * Waits until the expression evaluates to true
  423. */
  424. function waitForEval(expression, timeout, interval, subject) {
  425. waitFor(function() {
  426. return eval(expression);
  427. }, arguments.callee.name + ": Timeout exceeded for '" + expression + "'", timeout, interval);
  428. return true;
  429. }
  430. //
  431. // //Function to start the running of jsTests
  432. // var jsTests = function (paramObj) {
  433. // //Setup needed variables
  434. // mozmill.jsTest.actions.loadActions();
  435. // var wm = mozmill.jsTest.actions;
  436. // var testFiles = paramObj.files;
  437. // if (!testFiles.length) {
  438. // throw new Error('No JavaScript tests to run.');
  439. // }
  440. // var _j = mozmill.jsTest;
  441. // //mozmill.MozMillController.stopLoop();
  442. //
  443. // //Timing the suite
  444. // var jsSuiteSummary = new TimeObj();
  445. // jsSuiteSummary.setName('jsSummary');
  446. // jsSuiteSummary.startTime();
  447. // _j.jsSuiteSummary = jsSuiteSummary;
  448. //
  449. // _j.run(paramObj);
  450. // };
  451. //
  452. // //Commands function to hande the test results of the js tests
  453. // var jsTestResults = function () {
  454. // var _j = mozmill.jsTest;
  455. // var jsSuiteSummary = _j.jsSuiteSummary;
  456. // var s = '';
  457. // s += 'Number of tests run: ' + _j.testCount + '\n';
  458. // s += '\nNumber of tests failures: ' + _j.testFailureCount;
  459. // if (_j.testFailureCount > 0) {
  460. // s += 'Test failures:<br/>';
  461. // var fails = _j.testFailures;
  462. // for (var i = 0; i < fails.length; i++) {
  463. // var fail = fails[i];
  464. // var msg = fail.message;
  465. // // Escape angle brackets for display in HTML
  466. // msg = msg.replace(/</g, '&lt;');
  467. // msg = msg.replace(/>/g, '&gt;');
  468. // s += msg + '<br/>';
  469. // }
  470. // };
  471. //
  472. // jsSuiteSummary.endTime();
  473. // var result = !(_j.testFailureCount > 0);
  474. //
  475. // if (result){
  476. // mozmill.results.writeResult(s, 'lightgreen');
  477. // }
  478. // else{
  479. // mozmill.results.writeResult(s, 'lightred');
  480. // }
  481. // //mozmill.results.writeResult(s);
  482. // //We want the summary to have a concept of success/failure
  483. // var result = !(_j.testFailureCount > 0);
  484. // var method = 'JS Test Suite Completion';
  485. // //mozmill.jsTest.sendJSReport(method, result, null, jsSuiteSummary);
  486. // // Fire the polling loop back up
  487. // //mozmill.MozMillController.continueLoop();
  488. // };