util.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. //
  2. // Utility functions for the HTML notebook's CasperJS tests.
  3. //
  4. casper.get_notebook_server = function () {
  5. // Get the URL of a notebook server on which to run tests.
  6. var port = casper.cli.get("port");
  7. port = (typeof port === 'undefined') ? '8888' : port;
  8. return casper.cli.get("url") || ('http://127.0.0.1:' + port);
  9. };
  10. // casper.thenClick doesn't seem to trigger click events properly
  11. casper.thenClick = function (selector) {
  12. return this.thenEvaluate(function(selector) {
  13. var el = $(selector);
  14. if (el.length === 0) {
  15. console.error("Missing element!", selector)
  16. }
  17. el.click();
  18. }, {selector: selector})
  19. }
  20. casper.open_new_notebook = function () {
  21. // Create and open a new notebook.
  22. var baseUrl = this.get_notebook_server();
  23. this.start(baseUrl);
  24. this.waitFor(this.page_loaded);
  25. this.waitForSelector('#kernel-python2 a, #kernel-python3 a');
  26. this.thenClick('#kernel-python2 a, #kernel-python3 a');
  27. this.waitForPopup('');
  28. this.withPopup('', function () {this.waitForSelector('.CodeMirror-code');});
  29. this.then(function () {
  30. this.open(this.popups[0].url);
  31. });
  32. this.waitFor(this.page_loaded);
  33. // Hook the log and error methods of the console, forcing them to
  34. // serialize their arguments before printing. This allows the
  35. // Objects to cross into the phantom/slimer regime for display.
  36. this.thenEvaluate(function(){
  37. var serialize_arguments = function(f, context) {
  38. return function() {
  39. var pretty_arguments = [];
  40. for (var i = 0; i < arguments.length; i++) {
  41. var value = arguments[i];
  42. if (value instanceof Object) {
  43. var name = value.name || 'Object';
  44. // Print a JSON string representation of the object.
  45. // If we don't do this, [Object object] gets printed
  46. // by casper, which is useless. The long regular
  47. // expression reduces the verbosity of the JSON.
  48. pretty_arguments.push(name + ' {' + JSON.stringify(value, null, ' ')
  49. .replace(/(\s+)?({)?(\s+)?(}(\s+)?,?)?(\s+)?(\s+)?\n/g, '\n')
  50. .replace(/\n(\s+)?\n/g, '\n'));
  51. } else {
  52. pretty_arguments.push(value);
  53. }
  54. }
  55. f.apply(context, pretty_arguments);
  56. };
  57. };
  58. console.log = serialize_arguments(console.log, console);
  59. console.error = serialize_arguments(console.error, console);
  60. });
  61. // Make sure the kernel has started
  62. this.waitFor(this.kernel_running);
  63. // track the IPython busy/idle state
  64. this.thenEvaluate(function () {
  65. require(['base/js/namespace', 'base/js/events'], function (IPython, events) {
  66. events.on('kernel_idle.Kernel',function () {
  67. IPython._status = 'idle';
  68. });
  69. events.on('kernel_busy.Kernel',function () {
  70. IPython._status = 'busy';
  71. });
  72. });
  73. });
  74. };
  75. casper.page_loaded = function() {
  76. // Return whether or not the page has been loaded.
  77. return this.evaluate(function() {
  78. return typeof IPython !== "undefined" &&
  79. IPython.page !== undefined;
  80. });
  81. };
  82. casper.kernel_running = function() {
  83. // Return whether or not the kernel is running.
  84. return this.evaluate(function() {
  85. return IPython &&
  86. IPython.notebook &&
  87. IPython.notebook.kernel &&
  88. IPython.notebook.kernel.is_connected();
  89. });
  90. };
  91. casper.kernel_disconnected = function() {
  92. return this.evaluate(function() {
  93. return IPython.notebook.kernel.is_fully_disconnected();
  94. });
  95. };
  96. casper.wait_for_kernel_ready = function () {
  97. this.waitFor(this.kernel_running);
  98. this.thenEvaluate(function () {
  99. IPython._kernel_ready = false;
  100. IPython.notebook.kernel.kernel_info(
  101. function () {
  102. IPython._kernel_ready = true;
  103. });
  104. });
  105. this.waitFor(function () {
  106. return this.evaluate(function () {
  107. return IPython._kernel_ready;
  108. });
  109. });
  110. };
  111. casper.shutdown_current_kernel = function () {
  112. // Shut down the current notebook's kernel.
  113. this.thenEvaluate(function() {
  114. IPython.notebook.session.delete();
  115. });
  116. // We close the page right after this so we need to give it time to complete.
  117. this.wait(1000);
  118. };
  119. casper.delete_current_notebook = function () {
  120. // Delete created notebook.
  121. // For some unknown reason, this doesn't work?!?
  122. this.thenEvaluate(function() {
  123. IPython.notebook.delete();
  124. });
  125. };
  126. casper.wait_for_busy = function () {
  127. // Waits for the notebook to enter a busy state.
  128. this.waitFor(function () {
  129. return this.evaluate(function () {
  130. return IPython._status == 'busy';
  131. });
  132. });
  133. };
  134. casper.wait_for_idle = function () {
  135. // Waits for the notebook to idle.
  136. this.waitFor(function () {
  137. return this.evaluate(function () {
  138. return IPython._status == 'idle';
  139. });
  140. });
  141. };
  142. casper.wait_for_output = function (cell_num, out_num) {
  143. // wait for the nth output in a given cell
  144. this.wait_for_idle();
  145. out_num = out_num || 0;
  146. this.then(function() {
  147. this.waitFor(function (c, o) {
  148. return this.evaluate(function get_output(c, o) {
  149. var cell = IPython.notebook.get_cell(c);
  150. return cell.output_area.outputs.length > o;
  151. },
  152. // pass parameter from the test suite js to the browser code js
  153. {c : cell_num, o : out_num});
  154. },
  155. function then() { },
  156. function timeout() {
  157. this.echo("wait_for_output timed out on cell "+cell_num+", waiting for "+out_num+" outputs .");
  158. var pn = this.evaluate(function get_prompt(c) {
  159. return (IPython.notebook.get_cell(c)|| {'input_prompt_number':'no cell'}).input_prompt_number;
  160. });
  161. this.echo("cell prompt was :'"+pn+"'.");
  162. });
  163. });
  164. };
  165. casper.wait_for_widget = function (widget_info) {
  166. // wait for a widget msg que to reach 0
  167. //
  168. // Parameters
  169. // ----------
  170. // widget_info : object
  171. // Object which contains info related to the widget. The model_id property
  172. // is used to identify the widget.
  173. // Clear the results of a previous query, if they exist. Make sure a
  174. // dictionary exists to store the async results in.
  175. this.thenEvaluate(function(model_id) {
  176. if (window.pending_msgs === undefined) {
  177. window.pending_msgs = {};
  178. } else {
  179. window.pending_msgs[model_id] = -1;
  180. }
  181. }, {model_id: widget_info.model_id});
  182. // Wait for the pending messages to be 0.
  183. this.waitFor(function () {
  184. var pending = this.evaluate(function (model_id) {
  185. // Get the model. Once the model is had, store it's pending_msgs
  186. // count in the window's dictionary.
  187. IPython.notebook.kernel.widget_manager.get_model(model_id)
  188. .then(function(model) {
  189. window.pending_msgs[model_id] = model.pending_msgs;
  190. });
  191. // Return the pending_msgs result.
  192. return window.pending_msgs[model_id];
  193. }, {model_id: widget_info.model_id});
  194. if (pending === 0) {
  195. return true;
  196. } else {
  197. return false;
  198. }
  199. });
  200. };
  201. casper.cell_has_outputs = function (cell_num) {
  202. var result = casper.evaluate(function (c) {
  203. var cell = IPython.notebook.get_cell(c);
  204. return cell.output_area.outputs.length;
  205. },
  206. {c : cell_num});
  207. return result > 0;
  208. };
  209. casper.get_output_cell = function (cell_num, out_num, message) {
  210. messsge = message+': ' ||'no category :'
  211. // return an output of a given cell
  212. out_num = out_num || 0;
  213. var result = casper.evaluate(function (c, o) {
  214. var cell = IPython.notebook.get_cell(c);
  215. return cell.output_area.outputs[o];
  216. },
  217. {c : cell_num, o : out_num});
  218. if (!result) {
  219. var num_outputs = casper.evaluate(function (c) {
  220. var cell = IPython.notebook.get_cell(c);
  221. return cell.output_area.outputs.length;
  222. },
  223. {c : cell_num});
  224. this.test.assertTrue(false,
  225. message+"Cell " + cell_num + " has no output #" + out_num + " (" + num_outputs + " total)"
  226. );
  227. } else {
  228. return result;
  229. }
  230. };
  231. casper.get_cells_length = function () {
  232. // return the number of cells in the notebook
  233. var result = casper.evaluate(function () {
  234. return IPython.notebook.get_cells().length;
  235. });
  236. return result;
  237. };
  238. casper.set_cell_text = function(index, text){
  239. // Set the text content of a cell.
  240. this.evaluate(function (index, text) {
  241. var cell = IPython.notebook.get_cell(index);
  242. cell.set_text(text);
  243. }, index, text);
  244. };
  245. casper.get_cell_text = function(index){
  246. // Get the text content of a cell.
  247. return this.evaluate(function (index) {
  248. var cell = IPython.notebook.get_cell(index);
  249. return cell.get_text();
  250. }, index);
  251. };
  252. casper.insert_cell_at_bottom = function(cell_type){
  253. // Inserts a cell at the bottom of the notebook
  254. // Returns the new cell's index.
  255. return this.evaluate(function (cell_type) {
  256. var cell = IPython.notebook.insert_cell_at_bottom(cell_type);
  257. return IPython.notebook.find_cell_index(cell);
  258. }, cell_type);
  259. };
  260. casper.append_cell = function(text, cell_type) {
  261. // Insert a cell at the bottom of the notebook and set the cells text.
  262. // Returns the new cell's index.
  263. var index = this.insert_cell_at_bottom(cell_type);
  264. if (text !== undefined) {
  265. this.set_cell_text(index, text);
  266. }
  267. return index;
  268. };
  269. casper.execute_cell = function(index, expect_failure){
  270. // Asynchronously executes a cell by index.
  271. // Returns the cell's index.
  272. if (expect_failure === undefined) expect_failure = false;
  273. var that = this;
  274. this.then(function(){
  275. that.evaluate(function (index) {
  276. var cell = IPython.notebook.get_cell(index);
  277. cell.execute();
  278. }, index);
  279. });
  280. this.wait_for_idle();
  281. this.then(function () {
  282. var error = that.evaluate(function (index) {
  283. var cell = IPython.notebook.get_cell(index);
  284. var outputs = cell.output_area.outputs;
  285. for (var i = 0; i < outputs.length; i++) {
  286. if (outputs[i].output_type == 'error') {
  287. return outputs[i];
  288. }
  289. }
  290. return false;
  291. }, index);
  292. if (error === null) {
  293. this.test.fail("Failed to check for error output");
  294. }
  295. if (expect_failure && error === false) {
  296. this.test.fail("Expected error while running cell");
  297. } else if (!expect_failure && error !== false) {
  298. this.test.fail("Error running cell:\n" + error.traceback.join('\n'));
  299. }
  300. });
  301. return index;
  302. };
  303. casper.execute_cell_then = function(index, then_callback, expect_failure) {
  304. // Synchronously executes a cell by index.
  305. // Optionally accepts a then_callback parameter. then_callback will get called
  306. // when the cell has finished executing.
  307. // Returns the cell's index.
  308. var return_val = this.execute_cell(index, expect_failure);
  309. this.wait_for_idle();
  310. var that = this;
  311. this.then(function(){
  312. if (then_callback!==undefined) {
  313. then_callback.apply(that, [index]);
  314. }
  315. });
  316. return return_val;
  317. };
  318. casper.append_cell_execute_then = function(text, then_callback, expect_failure) {
  319. // Append a code cell and execute it, optionally calling a then_callback
  320. var c = this.append_cell(text);
  321. return this.execute_cell_then(c, then_callback, expect_failure);
  322. };
  323. casper.assert_output_equals = function(text, output_text, message) {
  324. // Append a code cell with the text, then assert the output is equal to output_text
  325. this.append_cell_execute_then(text, function(index) {
  326. this.test.assertEquals(this.get_output_cell(index).text.trim(), output_text, message);
  327. });
  328. };
  329. casper.wait_for_element = function(index, selector){
  330. // Utility function that allows us to easily wait for an element
  331. // within a cell. Uses JQuery selector to look for the element.
  332. var that = this;
  333. this.waitFor(function() {
  334. return that.cell_element_exists(index, selector);
  335. });
  336. };
  337. casper.cell_element_exists = function(index, selector){
  338. // Utility function that allows us to easily check if an element exists
  339. // within a cell. Uses JQuery selector to look for the element.
  340. return casper.evaluate(function (index, selector) {
  341. var $cell = IPython.notebook.get_cell(index).element;
  342. return $cell.find(selector).length > 0;
  343. }, index, selector);
  344. };
  345. casper.cell_element_function = function(index, selector, function_name, function_args){
  346. // Utility function that allows us to execute a jQuery function on an
  347. // element within a cell.
  348. return casper.evaluate(function (index, selector, function_name, function_args) {
  349. var $cell = IPython.notebook.get_cell(index).element;
  350. var $el = $cell.find(selector);
  351. return $el[function_name].apply($el, function_args);
  352. }, index, selector, function_name, function_args);
  353. };
  354. casper.validate_notebook_state = function(message, mode, cell_index) {
  355. // Validate the entire dual mode state of the notebook. Make sure no more than
  356. // one cell is selected, focused, in edit mode, etc...
  357. // General tests.
  358. this.test.assertEquals(this.get_keyboard_mode(), this.get_notebook_mode(),
  359. message + '; keyboard and notebook modes match');
  360. // Is the selected cell the only cell that is selected?
  361. if (cell_index!==undefined) {
  362. this.test.assert(this.is_only_cell_selected(cell_index),
  363. message + '; expecting cell ' + cell_index + ' to be the only cell selected. Got selected cell(s):'+
  364. (function(){
  365. return casper.evaluate(function(){
  366. return IPython.notebook.get_selected_cells_indices();
  367. })
  368. })()
  369. );
  370. }
  371. // Mode specific tests.
  372. if (mode==='command') {
  373. // Are the notebook and keyboard manager in command mode?
  374. this.test.assertEquals(this.get_keyboard_mode(), 'command',
  375. message + '; in command mode');
  376. // Make sure there isn't a single cell in edit mode.
  377. this.test.assert(this.is_only_cell_edit(null),
  378. message + '; all cells in command mode');
  379. this.test.assert(this.is_cell_editor_focused(null),
  380. message + '; no cell editors are focused while in command mode');
  381. } else if (mode==='edit') {
  382. // Are the notebook and keyboard manager in edit mode?
  383. this.test.assertEquals(this.get_keyboard_mode(), 'edit',
  384. message + '; in edit mode');
  385. if (cell_index!==undefined) {
  386. // Is the specified cell the only cell in edit mode?
  387. this.test.assert(this.is_only_cell_edit(cell_index),
  388. message + '; cell ' + cell_index + ' is the only cell in edit mode '+ this.cells_modes());
  389. // Is the specified cell the only cell with a focused code mirror?
  390. this.test.assert(this.is_cell_editor_focused(cell_index),
  391. message + '; cell ' + cell_index + '\'s editor is appropriately focused');
  392. }
  393. } else {
  394. this.test.assert(false, message + '; ' + mode + ' is an unknown mode');
  395. }
  396. };
  397. casper.select_cell = function(index, moveanchor) {
  398. // Select a cell in the notebook.
  399. this.evaluate(function (i, moveanchor) {
  400. IPython.notebook.select(i, moveanchor);
  401. }, {i: index, moveanchor: moveanchor});
  402. };
  403. casper.select_cells = function(index, bound, moveanchor) {
  404. // Select a block of cells in the notebook.
  405. // like Python range, selects [index,bound)
  406. this.evaluate(function (i, n, moveanchor) {
  407. Jupyter.notebook.select(i, moveanchor);
  408. Jupyter.notebook.extend_selection_by(n);
  409. }, {i: index, n: (bound - index - 1), moveanchor: moveanchor});
  410. };
  411. casper.click_cell_editor = function(index) {
  412. // Emulate a click on a cell's editor.
  413. // Code Mirror does not play nicely with emulated brower events.
  414. // Instead of trying to emulate a click, here we run code similar to
  415. // the code used in Code Mirror that handles the mousedown event on a
  416. // region of codemirror that the user can focus.
  417. this.evaluate(function (i) {
  418. var cm = IPython.notebook.get_cell(i).code_mirror;
  419. if (cm.options.readOnly != "nocursor" && (document.activeElement != cm.display.input)){
  420. cm.display.input.focus();
  421. }
  422. }, {i: index});
  423. };
  424. casper.set_cell_editor_cursor = function(index, line_index, char_index) {
  425. // Set the Code Mirror instance cursor's location.
  426. this.evaluate(function (i, l, c) {
  427. IPython.notebook.get_cell(i).code_mirror.setCursor(l, c);
  428. }, {i: index, l: line_index, c: char_index});
  429. };
  430. casper.focus_notebook = function() {
  431. // Focus the notebook div.
  432. this.evaluate(function (){
  433. $('#notebook').focus();
  434. }, {});
  435. };
  436. casper.trigger_keydown = function() {
  437. // Emulate a keydown in the notebook.
  438. for (var i = 0; i < arguments.length; i++) {
  439. this.evaluate(function (k) {
  440. var element = $(document);
  441. var event = IPython.keyboard.shortcut_to_event(k, 'keydown');
  442. element.trigger(event);
  443. }, {k: arguments[i]});
  444. }
  445. };
  446. casper.get_keyboard_mode = function() {
  447. // Get the mode of the keyboard manager.
  448. return this.evaluate(function() {
  449. return IPython.keyboard_manager.mode;
  450. }, {});
  451. };
  452. casper.get_notebook_mode = function() {
  453. // Get the mode of the notebook.
  454. return this.evaluate(function() {
  455. return IPython.notebook.mode;
  456. }, {});
  457. };
  458. casper.get_cell = function(index) {
  459. // Get a single cell.
  460. //
  461. // Note: Handles to DOM elements stored in the cell will be useless once in
  462. // CasperJS context.
  463. return this.evaluate(function(i) {
  464. var cell = IPython.notebook.get_cell(i);
  465. if (cell) {
  466. return cell;
  467. }
  468. return null;
  469. }, {i : index});
  470. };
  471. casper.is_cell_editor_focused = function(index) {
  472. // Make sure a cell's editor is the only editor focused on the page.
  473. return this.evaluate(function(i) {
  474. var focused_textarea = $('#notebook .CodeMirror-focused textarea');
  475. if (focused_textarea.length > 1) { throw 'More than one Code Mirror editor is focused at once!'; }
  476. if (i === null) {
  477. return focused_textarea.length === 0;
  478. } else {
  479. var cell = IPython.notebook.get_cell(i);
  480. if (cell) {
  481. return cell.code_mirror.getInputField() == focused_textarea[0];
  482. }
  483. }
  484. return false;
  485. }, {i : index});
  486. };
  487. casper.is_only_cell_selected = function(index) {
  488. // Check if a cell is the only cell selected.
  489. // Pass null as the index to check if no cells are selected.
  490. return this.is_only_cell_on(index, 'selected', 'unselected');
  491. };
  492. casper.is_only_cell_edit = function(index) {
  493. // Check if a cell is the only cell in edit mode.
  494. // Pass null as the index to check if all of the cells are in command mode.
  495. var cells_length = this.get_cells_length();
  496. for (var j = 0; j < cells_length; j++) {
  497. if (j === index) {
  498. if (!this.cell_mode_is(j, 'edit')) {
  499. return false;
  500. }
  501. } else {
  502. if (this.cell_mode_is(j, 'edit')) {
  503. return false;
  504. }
  505. }
  506. }
  507. return true;
  508. };
  509. casper.is_only_cell_on = function(i, on_class, off_class) {
  510. // Check if a cell is the only cell with the `on_class` DOM class applied to it.
  511. // All of the other cells are checked for the `off_class` DOM class.
  512. // Pass null as the index to check if all of the cells have the `off_class`.
  513. var cells_length = this.get_cells_length();
  514. for (var j = 0; j < cells_length; j++) {
  515. if (j === i) {
  516. if (this.cell_has_class(j, off_class) || !this.cell_has_class(j, on_class)) {
  517. return false;
  518. }
  519. } else {
  520. if (!this.cell_has_class(j, off_class) || this.cell_has_class(j, on_class)) {
  521. return false;
  522. }
  523. }
  524. }
  525. return true;
  526. };
  527. casper.cells_modes = function(){
  528. return this.evaluate(function(){
  529. return IPython.notebook.get_cells().map(function(x,c){return x.mode})
  530. }, {});
  531. };
  532. casper.cell_mode_is = function(index, mode) {
  533. // Check if a cell is in a specific mode
  534. return this.evaluate(function(i, m) {
  535. var cell = IPython.notebook.get_cell(i);
  536. if (cell) {
  537. return cell.mode === m;
  538. }
  539. return false;
  540. }, {i : index, m: mode});
  541. };
  542. casper.cell_has_class = function(index, classes) {
  543. // Check if a cell has a class.
  544. return this.evaluate(function(i, c) {
  545. var cell = IPython.notebook.get_cell(i);
  546. if (cell) {
  547. return cell.element.hasClass(c);
  548. }
  549. return false;
  550. }, {i : index, c: classes});
  551. };
  552. casper.is_cell_rendered = function (index) {
  553. return this.evaluate(function(i) {
  554. return !!IPython.notebook.get_cell(i).rendered;
  555. }, {i:index});
  556. };
  557. casper.assert_colors_equal = function (hex_color, local_color, msg) {
  558. // Tests to see if two colors are equal.
  559. //
  560. // Parameters
  561. // hex_color: string
  562. // Hexadecimal color code, with or without preceeding hash character.
  563. // local_color: string
  564. // Local color representation. Can either be hexadecimal (default for
  565. // phantom) or rgb (default for slimer).
  566. // Remove parentheses, hashes, semi-colons, and space characters.
  567. hex_color = hex_color.replace(/[\(\); #]/, '');
  568. local_color = local_color.replace(/[\(\); #]/, '');
  569. // If the local color is rgb, clean it up and replace
  570. if (local_color.substr(0,3).toLowerCase() == 'rgb') {
  571. var components = local_color.substr(3).split(',');
  572. local_color = '';
  573. for (var i = 0; i < components.length; i++) {
  574. var part = parseInt(components[i]).toString(16);
  575. while (part.length < 2) part = '0' + part;
  576. local_color += part;
  577. }
  578. }
  579. this.test.assertEquals(hex_color.toUpperCase(), local_color.toUpperCase(), msg);
  580. };
  581. casper.notebook_test = function(test) {
  582. // Wrap a notebook test to reduce boilerplate.
  583. this.open_new_notebook();
  584. // Echo whether or not we are running this test using SlimerJS
  585. if (this.evaluate(function(){
  586. return typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
  587. })) {
  588. console.log('This test is running in SlimerJS.');
  589. this.slimerjs = true;
  590. }
  591. // Make sure to remove the onbeforeunload callback. This callback is
  592. // responsible for the "Are you sure you want to quit?" type messages.
  593. // PhantomJS ignores these prompts, SlimerJS does not which causes hangs.
  594. this.then(function(){
  595. this.evaluate(function(){
  596. window.onbeforeunload = function(){};
  597. });
  598. });
  599. this.then(test);
  600. // Kill the kernel and delete the notebook.
  601. this.shutdown_current_kernel();
  602. // This is still broken but shouldn't be a problem for now.
  603. // this.delete_current_notebook();
  604. // This is required to clean up the page we just finished with. If we don't call this
  605. // casperjs will leak file descriptors of all the open WebSockets in that page. We
  606. // have to set this.page=null so that next time casper.start runs, it will create a
  607. // new page from scratch.
  608. this.then(function () {
  609. this.page.close();
  610. this.page = null;
  611. });
  612. // Run the browser automation.
  613. this.run(function() {
  614. this.test.done();
  615. });
  616. };
  617. casper.wait_for_dashboard = function () {
  618. // Wait for the dashboard list to load.
  619. casper.waitForSelector('.list_item');
  620. };
  621. /**
  622. * Open the dashboard page
  623. * @param {bool} use_start - If true, will use casper.start(), otherwise
  624. * casper.open(). You should only set it to true if the dashboard
  625. * is the first URL to be opened in the test, because calling
  626. * casper.start() multiple times causes casper to skip subsequent then()
  627. */
  628. casper.open_dashboard = function (use_start) {
  629. if (use_start === undefined) {
  630. use_start = false;
  631. }
  632. // Start casper by opening the dashboard page.
  633. var baseUrl = this.get_notebook_server();
  634. if (use_start) {
  635. this.start(baseUrl);
  636. } else {
  637. this.open(baseUrl);
  638. }
  639. this.waitFor(this.page_loaded);
  640. this.wait_for_dashboard();
  641. };
  642. casper.dashboard_test = function (test) {
  643. // Open the dashboard page and run a test.
  644. this.open_dashboard(true);
  645. this.then(test);
  646. this.then(function () {
  647. this.page.close();
  648. this.page = null;
  649. });
  650. // Run the browser automation.
  651. this.run(function() {
  652. this.test.done();
  653. });
  654. };
  655. // note that this will only work for UNIQUE events -- if you want to
  656. // listen for the same event twice, this will not work!
  657. casper.event_test = function (name, events, action, timeout) {
  658. // set up handlers to listen for each of the events
  659. this.thenEvaluate(function (events) {
  660. var make_handler = function (event) {
  661. return function () {
  662. IPython._events_triggered.push(event);
  663. IPython.notebook.events.off(event, null, IPython._event_handlers[event]);
  664. delete IPython._event_handlers[event];
  665. };
  666. };
  667. IPython._event_handlers = {};
  668. IPython._events_triggered = [];
  669. for (var i=0; i < events.length; i++) {
  670. IPython._event_handlers[events[i]] = make_handler(events[i]);
  671. IPython.notebook.events.on(events[i], IPython._event_handlers[events[i]]);
  672. }
  673. }, [events]);
  674. // execute the requested action
  675. this.then(action);
  676. // wait for all the events to be triggered
  677. this.waitFor(function () {
  678. return this.evaluate(function (events) {
  679. return IPython._events_triggered.length >= events.length;
  680. }, [events]);
  681. }, undefined, undefined, timeout);
  682. // test that the events were triggered in the proper order
  683. this.then(function () {
  684. var triggered = this.evaluate(function () {
  685. return IPython._events_triggered;
  686. });
  687. var handlers = this.evaluate(function () {
  688. return Object.keys(IPython._event_handlers);
  689. });
  690. this.test.assertEquals(triggered.length, events.length, name + ': ' + events.length + ' events were triggered');
  691. this.test.assertEquals(handlers.length, 0, name + ': all handlers triggered');
  692. for (var i=0; i < events.length; i++) {
  693. this.test.assertEquals(triggered[i], events[i], name + ': ' + events[i] + ' was triggered');
  694. }
  695. });
  696. // turn off any remaining event listeners
  697. this.thenEvaluate(function () {
  698. for (var event in IPython._event_handlers) {
  699. IPython.notebook.events.off(event, null, IPython._event_handlers[event]);
  700. delete IPython._event_handlers[event];
  701. }
  702. });
  703. };
  704. casper.options.waitTimeout=10000;
  705. casper.on('waitFor.timeout', function onWaitForTimeout(timeout) {
  706. this.echo("Timeout for " + casper.get_notebook_server());
  707. this.echo("Is the notebook server running?");
  708. });
  709. casper.print_log = function () {
  710. // Pass `console.log` calls from page JS to casper.
  711. this.on('remote.message', function(msg) {
  712. this.echo('Remote message caught: ' + msg);
  713. });
  714. };
  715. casper.on("page.error", function onError(msg, trace) {
  716. // show errors in the browser
  717. this.echo("Page Error");
  718. this.echo(" Message: " + msg.split('\n').join('\n '));
  719. this.echo(" Call stack:");
  720. var local_path = this.get_notebook_server();
  721. for (var i = 0; i < trace.length; i++) {
  722. var frame = trace[i];
  723. var file = frame.file;
  724. // shorten common phantomjs evaluate url
  725. // this will have a different value on slimerjs
  726. if (file === "phantomjs://webpage.evaluate()") {
  727. file = "evaluate";
  728. }
  729. // remove the version tag from the path
  730. file = file.replace(/(\?v=[0-9abcdef]+)/, '');
  731. // remove the local address from the beginning of the path
  732. if (file.indexOf(local_path) === 0) {
  733. file = file.substr(local_path.length);
  734. }
  735. var frame_text = (frame.function.length > 0) ? " in " + frame.function : "";
  736. this.echo(" line " + frame.line + " of " + file + frame_text);
  737. }
  738. });
  739. casper.capture_log = function () {
  740. // show captured errors
  741. var captured_log = [];
  742. var seen_errors = 0;
  743. this.on('remote.message', function(msg) {
  744. captured_log.push(msg);
  745. });
  746. var that = this;
  747. this.test.on("test.done", function (result) {
  748. // test.done runs per-file,
  749. // but suiteResults is per-suite (directory)
  750. var current_errors;
  751. if (this.suiteResults) {
  752. // casper 1.1 has suiteResults
  753. current_errors = this.suiteResults.countErrors() + this.suiteResults.countFailed();
  754. } else {
  755. // casper 1.0 has testResults instead
  756. current_errors = this.testResults.failed;
  757. }
  758. if (current_errors > seen_errors && captured_log.length > 0) {
  759. casper.echo("\nCaptured console.log:");
  760. for (var i = 0; i < captured_log.length; i++) {
  761. var output = String(captured_log[i]).split('\n');
  762. for (var j = 0; j < output.length; j++) {
  763. casper.echo(" " + output[j]);
  764. }
  765. }
  766. }
  767. seen_errors = current_errors;
  768. captured_log = [];
  769. });
  770. };
  771. casper.interact = function() {
  772. // Start an interactive Javascript console.
  773. var system = require('system');
  774. system.stdout.writeLine('JS interactive console.');
  775. system.stdout.writeLine('Type `exit` to quit.');
  776. function read_line() {
  777. system.stdout.writeLine('JS: ');
  778. var line = system.stdin.readLine();
  779. return line;
  780. }
  781. var input = read_line();
  782. while (input.trim() != 'exit') {
  783. var output = this.evaluate(function(code) {
  784. return String(eval(code));
  785. }, {code: input});
  786. system.stdout.writeLine('\nOut: ' + output);
  787. input = read_line();
  788. }
  789. };
  790. casper.capture_log();