/testing/selenium-core/lib/scriptaculous/unittest.js

http://datanucleus-appengine.googlecode.com/ · JavaScript · 383 lines · 335 code · 15 blank · 33 comment · 63 complexity · 19e5e5117633a8bc41724d0bc67e4162 MD5 · raw file

  1. // Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
  2. // (c) 2005 Jon Tirsen (http://www.tirsen.com)
  3. // (c) 2005 Michael Schuerig (http://www.schuerig.de/michael/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining
  6. // a copy of this software and associated documentation files (the
  7. // "Software"), to deal in the Software without restriction, including
  8. // without limitation the rights to use, copy, modify, merge, publish,
  9. // distribute, sublicense, and/or sell copies of the Software, and to
  10. // permit persons to whom the Software is furnished to do so, subject to
  11. // the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. // experimental, Firefox-only
  24. Event.simulateMouse = function(element, eventName) {
  25. var options = Object.extend({
  26. pointerX: 0,
  27. pointerY: 0,
  28. buttons: 0
  29. }, arguments[2] || {});
  30. var oEvent = document.createEvent("MouseEvents");
  31. oEvent.initMouseEvent(eventName, true, true, document.defaultView,
  32. options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
  33. false, false, false, false, 0, $(element));
  34. if(this.mark) Element.remove(this.mark);
  35. this.mark = document.createElement('div');
  36. this.mark.appendChild(document.createTextNode(" "));
  37. document.body.appendChild(this.mark);
  38. this.mark.style.position = 'absolute';
  39. this.mark.style.top = options.pointerY + "px";
  40. this.mark.style.left = options.pointerX + "px";
  41. this.mark.style.width = "5px";
  42. this.mark.style.height = "5px;";
  43. this.mark.style.borderTop = "1px solid red;"
  44. this.mark.style.borderLeft = "1px solid red;"
  45. if(this.step)
  46. alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
  47. $(element).dispatchEvent(oEvent);
  48. };
  49. // Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
  50. // You need to downgrade to 1.0.4 for now to get this working
  51. // See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
  52. Event.simulateKey = function(element, eventName) {
  53. var options = Object.extend({
  54. ctrlKey: false,
  55. altKey: false,
  56. shiftKey: false,
  57. metaKey: false,
  58. keyCode: 0,
  59. charCode: 0
  60. }, arguments[2] || {});
  61. var oEvent = document.createEvent("KeyEvents");
  62. oEvent.initKeyEvent(eventName, true, true, window,
  63. options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
  64. options.keyCode, options.charCode );
  65. $(element).dispatchEvent(oEvent);
  66. };
  67. Event.simulateKeys = function(element, command) {
  68. for(var i=0; i<command.length; i++) {
  69. Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
  70. }
  71. };
  72. var Test = {}
  73. Test.Unit = {};
  74. // security exception workaround
  75. Test.Unit.inspect = Object.inspect;
  76. Test.Unit.Logger = Class.create();
  77. Test.Unit.Logger.prototype = {
  78. initialize: function(log) {
  79. this.log = $(log);
  80. if (this.log) {
  81. this._createLogTable();
  82. }
  83. },
  84. start: function(testName) {
  85. if (!this.log) return;
  86. this.testName = testName;
  87. this.lastLogLine = document.createElement('tr');
  88. this.statusCell = document.createElement('td');
  89. this.nameCell = document.createElement('td');
  90. this.nameCell.appendChild(document.createTextNode(testName));
  91. this.messageCell = document.createElement('td');
  92. this.lastLogLine.appendChild(this.statusCell);
  93. this.lastLogLine.appendChild(this.nameCell);
  94. this.lastLogLine.appendChild(this.messageCell);
  95. this.loglines.appendChild(this.lastLogLine);
  96. },
  97. finish: function(status, summary) {
  98. if (!this.log) return;
  99. this.lastLogLine.className = status;
  100. this.statusCell.innerHTML = status;
  101. this.messageCell.innerHTML = this._toHTML(summary);
  102. },
  103. message: function(message) {
  104. if (!this.log) return;
  105. this.messageCell.innerHTML = this._toHTML(message);
  106. },
  107. summary: function(summary) {
  108. if (!this.log) return;
  109. this.logsummary.innerHTML = this._toHTML(summary);
  110. },
  111. _createLogTable: function() {
  112. this.log.innerHTML =
  113. '<div id="logsummary"></div>' +
  114. '<table id="logtable">' +
  115. '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
  116. '<tbody id="loglines"></tbody>' +
  117. '</table>';
  118. this.logsummary = $('logsummary')
  119. this.loglines = $('loglines');
  120. },
  121. _toHTML: function(txt) {
  122. return txt.escapeHTML().replace(/\n/g,"<br/>");
  123. }
  124. }
  125. Test.Unit.Runner = Class.create();
  126. Test.Unit.Runner.prototype = {
  127. initialize: function(testcases) {
  128. this.options = Object.extend({
  129. testLog: 'testlog'
  130. }, arguments[1] || {});
  131. this.options.resultsURL = this.parseResultsURLQueryParameter();
  132. if (this.options.testLog) {
  133. this.options.testLog = $(this.options.testLog) || null;
  134. }
  135. if(this.options.tests) {
  136. this.tests = [];
  137. for(var i = 0; i < this.options.tests.length; i++) {
  138. if(/^test/.test(this.options.tests[i])) {
  139. this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
  140. }
  141. }
  142. } else {
  143. if (this.options.test) {
  144. this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
  145. } else {
  146. this.tests = [];
  147. for(var testcase in testcases) {
  148. if(/^test/.test(testcase)) {
  149. this.tests.push(new Test.Unit.Testcase(testcase, testcases[testcase], testcases["setup"], testcases["teardown"]));
  150. }
  151. }
  152. }
  153. }
  154. this.currentTest = 0;
  155. this.logger = new Test.Unit.Logger(this.options.testLog);
  156. setTimeout(this.runTests.bind(this), 1000);
  157. },
  158. parseResultsURLQueryParameter: function() {
  159. return window.location.search.parseQuery()["resultsURL"];
  160. },
  161. // Returns:
  162. // "ERROR" if there was an error,
  163. // "FAILURE" if there was a failure, or
  164. // "SUCCESS" if there was neither
  165. getResult: function() {
  166. var hasFailure = false;
  167. for(var i=0;i<this.tests.length;i++) {
  168. if (this.tests[i].errors > 0) {
  169. return "ERROR";
  170. }
  171. if (this.tests[i].failures > 0) {
  172. hasFailure = true;
  173. }
  174. }
  175. if (hasFailure) {
  176. return "FAILURE";
  177. } else {
  178. return "SUCCESS";
  179. }
  180. },
  181. postResults: function() {
  182. if (this.options.resultsURL) {
  183. new Ajax.Request(this.options.resultsURL,
  184. { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
  185. }
  186. },
  187. runTests: function() {
  188. var test = this.tests[this.currentTest];
  189. if (!test) {
  190. // finished!
  191. this.postResults();
  192. this.logger.summary(this.summary());
  193. return;
  194. }
  195. if(!test.isWaiting) {
  196. this.logger.start(test.name);
  197. }
  198. test.run();
  199. if(test.isWaiting) {
  200. this.logger.message("Waiting for " + test.timeToWait + "ms");
  201. setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
  202. } else {
  203. this.logger.finish(test.status(), test.summary());
  204. this.currentTest++;
  205. // tail recursive, hopefully the browser will skip the stackframe
  206. this.runTests();
  207. }
  208. },
  209. summary: function() {
  210. var assertions = 0;
  211. var failures = 0;
  212. var errors = 0;
  213. var messages = [];
  214. for(var i=0;i<this.tests.length;i++) {
  215. assertions += this.tests[i].assertions;
  216. failures += this.tests[i].failures;
  217. errors += this.tests[i].errors;
  218. }
  219. return (
  220. this.tests.length + " tests, " +
  221. assertions + " assertions, " +
  222. failures + " failures, " +
  223. errors + " errors");
  224. }
  225. }
  226. Test.Unit.Assertions = Class.create();
  227. Test.Unit.Assertions.prototype = {
  228. initialize: function() {
  229. this.assertions = 0;
  230. this.failures = 0;
  231. this.errors = 0;
  232. this.messages = [];
  233. },
  234. summary: function() {
  235. return (
  236. this.assertions + " assertions, " +
  237. this.failures + " failures, " +
  238. this.errors + " errors" + "\n" +
  239. this.messages.join("\n"));
  240. },
  241. pass: function() {
  242. this.assertions++;
  243. },
  244. fail: function(message) {
  245. this.failures++;
  246. this.messages.push("Failure: " + message);
  247. },
  248. info: function(message) {
  249. this.messages.push("Info: " + message);
  250. },
  251. error: function(error) {
  252. this.errors++;
  253. this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
  254. },
  255. status: function() {
  256. if (this.failures > 0) return 'failed';
  257. if (this.errors > 0) return 'error';
  258. return 'passed';
  259. },
  260. assert: function(expression) {
  261. var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
  262. try { expression ? this.pass() :
  263. this.fail(message); }
  264. catch(e) { this.error(e); }
  265. },
  266. assertEqual: function(expected, actual) {
  267. var message = arguments[2] || "assertEqual";
  268. try { (expected == actual) ? this.pass() :
  269. this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
  270. '", actual "' + Test.Unit.inspect(actual) + '"'); }
  271. catch(e) { this.error(e); }
  272. },
  273. assertEnumEqual: function(expected, actual) {
  274. var message = arguments[2] || "assertEnumEqual";
  275. try { $A(expected).length == $A(actual).length &&
  276. expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
  277. this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
  278. ', actual ' + Test.Unit.inspect(actual)); }
  279. catch(e) { this.error(e); }
  280. },
  281. assertNotEqual: function(expected, actual) {
  282. var message = arguments[2] || "assertNotEqual";
  283. try { (expected != actual) ? this.pass() :
  284. this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
  285. catch(e) { this.error(e); }
  286. },
  287. assertNull: function(obj) {
  288. var message = arguments[1] || 'assertNull'
  289. try { (obj==null) ? this.pass() :
  290. this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
  291. catch(e) { this.error(e); }
  292. },
  293. assertHidden: function(element) {
  294. var message = arguments[1] || 'assertHidden';
  295. this.assertEqual("none", element.style.display, message);
  296. },
  297. assertNotNull: function(object) {
  298. var message = arguments[1] || 'assertNotNull';
  299. this.assert(object != null, message);
  300. },
  301. assertInstanceOf: function(expected, actual) {
  302. var message = arguments[2] || 'assertInstanceOf';
  303. try {
  304. (actual instanceof expected) ? this.pass() :
  305. this.fail(message + ": object was not an instance of the expected type"); }
  306. catch(e) { this.error(e); }
  307. },
  308. assertNotInstanceOf: function(expected, actual) {
  309. var message = arguments[2] || 'assertNotInstanceOf';
  310. try {
  311. !(actual instanceof expected) ? this.pass() :
  312. this.fail(message + ": object was an instance of the not expected type"); }
  313. catch(e) { this.error(e); }
  314. },
  315. _isVisible: function(element) {
  316. element = $(element);
  317. if(!element.parentNode) return true;
  318. this.assertNotNull(element);
  319. if(element.style && Element.getStyle(element, 'display') == 'none')
  320. return false;
  321. return this._isVisible(element.parentNode);
  322. },
  323. assertNotVisible: function(element) {
  324. this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
  325. },
  326. assertVisible: function(element) {
  327. this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
  328. },
  329. benchmark: function(operation, iterations) {
  330. var startAt = new Date();
  331. (iterations || 1).times(operation);
  332. var timeTaken = ((new Date())-startAt);
  333. this.info((arguments[2] || 'Operation') + ' finished ' +
  334. iterations + ' iterations in ' + (timeTaken/1000)+'s' );
  335. return timeTaken;
  336. }
  337. }
  338. Test.Unit.Testcase = Class.create();
  339. Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
  340. initialize: function(name, test, setup, teardown) {
  341. Test.Unit.Assertions.prototype.initialize.bind(this)();
  342. this.name = name;
  343. this.test = test || function() {};
  344. this.setup = setup || function() {};
  345. this.teardown = teardown || function() {};
  346. this.isWaiting = false;
  347. this.timeToWait = 1000;
  348. },
  349. wait: function(time, nextPart) {
  350. this.isWaiting = true;
  351. this.test = nextPart;
  352. this.timeToWait = time;
  353. },
  354. run: function() {
  355. try {
  356. try {
  357. if (!this.isWaiting) this.setup.bind(this)();
  358. this.isWaiting = false;
  359. this.test.bind(this)();
  360. } finally {
  361. if(!this.isWaiting) {
  362. this.teardown.bind(this)();
  363. }
  364. }
  365. }
  366. catch(e) { this.error(e); }
  367. }
  368. });