qunit: Abort unfinished AJAX requests in test teardown
[lhc/web/wiklou.git] / tests / qunit / data / testrunner.js
1 /*global CompletenessTest, sinon */
2 /*jshint evil: true */
3 ( function ( $, mw, QUnit ) {
4 'use strict';
5
6 var mwTestIgnore, mwTester,
7 addons,
8 ELEMENT_NODE = 1,
9 TEXT_NODE = 3;
10
11 /**
12 * Add bogus to url to prevent IE crazy caching
13 *
14 * @param value {String} a relative path (eg. 'data/foo.js'
15 * or 'data/test.php?foo=bar').
16 * @return {String} Such as 'data/foo.js?131031765087663960'
17 */
18 QUnit.fixurl = function ( value ) {
19 return value + (/\?/.test( value ) ? '&' : '?')
20 + String( new Date().getTime() )
21 + String( parseInt( Math.random() * 100000, 10 ) );
22 };
23
24 /**
25 * Configuration
26 */
27
28 // When a test() indicates asynchronicity with stop(),
29 // allow 30 seconds to pass before killing the test(),
30 // and assuming failure.
31 QUnit.config.testTimeout = 30 * 1000;
32
33 QUnit.config.requireExpects = true;
34
35 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
36 QUnit.config.urlConfig.push( {
37 id: 'debug',
38 label: 'Enable ResourceLoaderDebug',
39 tooltip: 'Enable debug mode in ResourceLoader',
40 value: 'true'
41 } );
42
43 /**
44 * CompletenessTest
45 *
46 * Adds toggle checkbox to header
47 */
48 QUnit.config.urlConfig.push( {
49 id: 'completenesstest',
50 label: 'Run CompletenessTest',
51 tooltip: 'Run the completeness test'
52 } );
53
54 /**
55 * SinonJS
56 *
57 * Glue code for nicer integration with QUnit setup/teardown
58 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
59 * Fixes:
60 * - Work properly with asynchronous QUnit by using module setup/teardown
61 * instead of synchronously wrapping QUnit.test.
62 */
63 sinon.assert.fail = function ( msg ) {
64 QUnit.assert.ok( false, msg );
65 };
66 sinon.assert.pass = function ( msg ) {
67 QUnit.assert.ok( true, msg );
68 };
69 sinon.config = {
70 injectIntoThis: true,
71 injectInto: null,
72 properties: ['spy', 'stub', 'mock', 'sandbox'],
73 // Don't fake timers by default
74 useFakeTimers: false,
75 useFakeServer: false
76 };
77 ( function () {
78 var orgModule = QUnit.module;
79
80 QUnit.module = function ( name, localEnv ) {
81 localEnv = localEnv || {};
82 orgModule( name, {
83 setup: function () {
84 var config = sinon.getConfig( sinon.config );
85 config.injectInto = this;
86 sinon.sandbox.create( config );
87
88 if ( localEnv.setup ) {
89 localEnv.setup.call( this );
90 }
91 },
92 teardown: function () {
93 this.sandbox.verifyAndRestore();
94
95 if ( localEnv.teardown ) {
96 localEnv.teardown.call( this );
97 }
98 }
99 } );
100 };
101 }() );
102
103 // Extend QUnit.module to provide a fixture element.
104 ( function () {
105 var orgModule = QUnit.module;
106
107 QUnit.module = function ( name, localEnv ) {
108 var fixture;
109 localEnv = localEnv || {};
110 orgModule( name, {
111 setup: function () {
112 fixture = document.createElement( 'div' );
113 fixture.id = 'qunit-fixture';
114 document.body.appendChild( fixture );
115
116 if ( localEnv.setup ) {
117 localEnv.setup.call( this );
118 }
119 },
120 teardown: function () {
121 if ( localEnv.teardown ) {
122 localEnv.teardown.call( this );
123 }
124
125 fixture.parentNode.removeChild( fixture );
126 }
127 } );
128 };
129 }() );
130
131 // Initiate when enabled
132 if ( QUnit.urlParams.completenesstest ) {
133
134 // Return true to ignore
135 mwTestIgnore = function ( val, tester ) {
136
137 // Don't record methods of the properties of constructors,
138 // to avoid getting into a loop (prototype.constructor.prototype..).
139 // Since we're therefor skipping any injection for
140 // "new mw.Foo()", manually set it to true here.
141 if ( val instanceof mw.Map ) {
142 tester.methodCallTracker.Map = true;
143 return true;
144 }
145 if ( val instanceof mw.Title ) {
146 tester.methodCallTracker.Title = true;
147 return true;
148 }
149
150 // Don't record methods of the properties of a jQuery object
151 if ( val instanceof $ ) {
152 return true;
153 }
154
155 // Don't iterate over the module registry (the 'script' references would
156 // be listed as untested methods otherwise)
157 if ( val === mw.loader.moduleRegistry ) {
158 return true;
159 }
160
161 return false;
162 };
163
164 mwTester = new CompletenessTest( mw, mwTestIgnore );
165 }
166
167 /**
168 * Test environment recommended for all QUnit test modules
169 *
170 * Whether to log environment changes to the console
171 */
172 QUnit.config.urlConfig.push( 'mwlogenv' );
173
174 /**
175 * Reset mw.config and others to a fresh copy of the live config for each test(),
176 * and restore it back to the live one afterwards.
177 * @param localEnv {Object} [optional]
178 * @example (see test suite at the bottom of this file)
179 * </code>
180 */
181 QUnit.newMwEnvironment = ( function () {
182 var warn, log, liveConfig, liveMessages,
183 ajaxRequests = [];
184
185 liveConfig = mw.config.values;
186 liveMessages = mw.messages.values;
187
188 function suppressWarnings() {
189 warn = mw.log.warn;
190 mw.log.warn = $.noop;
191 }
192
193 function restoreWarnings() {
194 if ( warn !== undefined ) {
195 mw.log.warn = warn;
196 warn = undefined;
197 }
198 }
199
200 function freshConfigCopy( custom ) {
201 var copy;
202 // Tests should mock all factors that directly influence the tested code.
203 // For backwards compatibility though we set mw.config to a fresh copy of the live
204 // config. This way any modifications made to mw.config during the test will not
205 // affect other tests, nor the global scope outside the test runner.
206 // This is a shallow copy, since overriding an array or object value via "custom"
207 // should replace it. Setting a config property means you override it, not extend it.
208 // NOTE: It is important that we suppress warnings because extend() will also access
209 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
210 suppressWarnings();
211 copy = $.extend( {}, liveConfig, custom );
212 restoreWarnings();
213
214 return copy;
215 }
216
217 function freshMessagesCopy( custom ) {
218 return $.extend( /*deep=*/true, {}, liveMessages, custom );
219 }
220
221 /**
222 * @param {jQuery.Event} event
223 * @param {jqXHR} jqXHR
224 * @param {Object} ajaxOptions
225 */
226 function trackAjax( event, jqXHR, ajaxOptions ) {
227 ajaxRequests.push( { xhr: jqXHR, options: ajaxOptions } );
228 }
229
230 log = QUnit.urlParams.mwlogenv ? mw.log : function () {};
231
232 return function ( localEnv ) {
233 localEnv = $.extend( {
234 // QUnit
235 setup: $.noop,
236 teardown: $.noop,
237 // MediaWiki
238 config: {},
239 messages: {}
240 }, localEnv );
241
242 return {
243 setup: function () {
244 log( 'MwEnvironment> SETUP for "' + QUnit.config.current.module
245 + ': ' + QUnit.config.current.testName + '"' );
246
247 // Greetings, mock environment!
248 mw.config.values = freshConfigCopy( localEnv.config );
249 mw.messages.values = freshMessagesCopy( localEnv.messages );
250 this.suppressWarnings = suppressWarnings;
251 this.restoreWarnings = restoreWarnings;
252
253 // Start tracking ajax requests
254 $( document ).on( 'ajaxSend', trackAjax );
255
256 localEnv.setup.call( this );
257 },
258
259 teardown: function () {
260 var timers, active;
261 log( 'MwEnvironment> TEARDOWN for "' + QUnit.config.current.module
262 + ': ' + QUnit.config.current.testName + '"' );
263
264 localEnv.teardown.call( this );
265
266 // Stop tracking ajax requests
267 $( document ).off( 'ajaxSend', trackAjax );
268
269 // Farewell, mock environment!
270 mw.config.values = liveConfig;
271 mw.messages.values = liveMessages;
272
273 // As a convenience feature, automatically restore warnings if they're
274 // still suppressed by the end of the test.
275 restoreWarnings();
276
277 // Tests should use fake timers or wait for animations to complete
278 // Check for incomplete animations/requests/etc and throw if there are any.
279 if ( $.timers && $.timers.length !== 0 ) {
280 timers = $.timers.length;
281 $.each( $.timers, function ( i, timer ) {
282 var node = timer.elem;
283 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
284 mw.html.element( node.nodeName.toLowerCase(), $(node).getAttrs() )
285 );
286 } );
287 // Force animations to stop to give the next test a clean start
288 $.fx.stop();
289
290 throw new Error( 'Unfinished animations: ' + timers );
291 }
292
293 // Test should use fake XHR, wait for requests, or call abort()
294 if ( $.active !== undefined && $.active !== 0 ) {
295 active = $.grep( ajaxRequests, function ( ajax ) {
296 return ajax.xhr.state() === 'pending';
297 } );
298 if ( active.length !== $.active ) {
299 mw.log.warn( 'Pending requests does not match jQuery.active count' );
300 }
301 // Force requests to stop to give the next test a clean start
302 $.each( active, function ( i, ajax ) {
303 mw.log.warn( 'Unfinished AJAX request #' + i, ajax.options );
304 ajax.xhr.abort();
305 } );
306 ajaxRequests = [];
307
308 throw new Error( 'Unfinished AJAX requests: ' + active.length );
309 }
310 }
311 };
312 };
313 }() );
314
315 // $.when stops as soon as one fails, which makes sense in most
316 // practical scenarios, but not in a unit test where we really do
317 // need to wait until all of them are finished.
318 QUnit.whenPromisesComplete = function () {
319 var altPromises = [];
320
321 $.each( arguments, function ( i, arg ) {
322 var alt = $.Deferred();
323 altPromises.push( alt );
324
325 // Whether this one fails or not, forwards it to
326 // the 'done' (resolve) callback of the alternative promise.
327 arg.always( alt.resolve );
328 } );
329
330 return $.when.apply( $, altPromises );
331 };
332
333 /**
334 * Recursively convert a node to a plain object representing its structure.
335 * Only considers attributes and contents (elements and text nodes).
336 * Attribute values are compared strictly and not normalised.
337 *
338 * @param {Node} node
339 * @return {Object|string} Plain JavaScript value representing the node.
340 */
341 function getDomStructure( node ) {
342 var $node, children, processedChildren, i, len, el;
343 $node = $( node );
344 if ( node.nodeType === ELEMENT_NODE ) {
345 children = $node.contents();
346 processedChildren = [];
347 for ( i = 0, len = children.length; i < len; i++ ) {
348 el = children[i];
349 if ( el.nodeType === ELEMENT_NODE || el.nodeType === TEXT_NODE ) {
350 processedChildren.push( getDomStructure( el ) );
351 }
352 }
353
354 return {
355 tagName: node.tagName,
356 attributes: $node.getAttrs(),
357 contents: processedChildren
358 };
359 } else {
360 // Should be text node
361 return $node.text();
362 }
363 }
364
365 /**
366 * Gets structure of node for this HTML.
367 *
368 * @param {string} html HTML markup for one or more nodes.
369 */
370 function getHtmlStructure( html ) {
371 var el = $( '<div>' ).append( html )[0];
372 return getDomStructure( el );
373 }
374
375 /**
376 * Add-on assertion helpers
377 */
378 // Define the add-ons
379 addons = {
380
381 // Expect boolean true
382 assertTrue: function ( actual, message ) {
383 QUnit.push( actual === true, actual, true, message );
384 },
385
386 // Expect boolean false
387 assertFalse: function ( actual, message ) {
388 QUnit.push( actual === false, actual, false, message );
389 },
390
391 // Expect numerical value less than X
392 lt: function ( actual, expected, message ) {
393 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
394 },
395
396 // Expect numerical value less than or equal to X
397 ltOrEq: function ( actual, expected, message ) {
398 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
399 },
400
401 // Expect numerical value greater than X
402 gt: function ( actual, expected, message ) {
403 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
404 },
405
406 // Expect numerical value greater than or equal to X
407 gtOrEq: function ( actual, expected, message ) {
408 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
409 },
410
411 /**
412 * Asserts that two HTML strings are structurally equivalent.
413 *
414 * @param {string} actualHtml Actual HTML markup.
415 * @param {string} expectedHtml Expected HTML markup
416 * @param {string} message Assertion message.
417 */
418 htmlEqual: function ( actualHtml, expectedHtml, message ) {
419 var actual = getHtmlStructure( actualHtml ),
420 expected = getHtmlStructure( expectedHtml );
421
422 QUnit.push(
423 QUnit.equiv(
424 actual,
425 expected
426 ),
427 actual,
428 expected,
429 message
430 );
431 },
432
433 /**
434 * Asserts that two HTML strings are not structurally equivalent.
435 *
436 * @param {string} actualHtml Actual HTML markup.
437 * @param {string} expectedHtml Expected HTML markup.
438 * @param {string} message Assertion message.
439 */
440 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
441 var actual = getHtmlStructure( actualHtml ),
442 expected = getHtmlStructure( expectedHtml );
443
444 QUnit.push(
445 !QUnit.equiv(
446 actual,
447 expected
448 ),
449 actual,
450 expected,
451 message
452 );
453 }
454 };
455
456 $.extend( QUnit.assert, addons );
457
458 /**
459 * Small test suite to confirm proper functionality of the utilities and
460 * initializations defined above in this file.
461 */
462 QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
463 setup: function () {
464 this.mwHtmlLive = mw.html;
465 mw.html = {
466 escape: function () {
467 return 'mocked';
468 }
469 };
470 },
471 teardown: function () {
472 mw.html = this.mwHtmlLive;
473 },
474 config: {
475 testVar: 'foo'
476 },
477 messages: {
478 testMsg: 'Foo.'
479 }
480 } ) );
481
482 QUnit.test( 'Setup', 3, function ( assert ) {
483 assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
484 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
485 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
486
487 mw.config.set( 'testVar', 'bar' );
488 mw.messages.set( 'testMsg', 'Bar.' );
489 } );
490
491 QUnit.test( 'Teardown', 2, function ( assert ) {
492 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
493 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
494 } );
495
496 QUnit.test( 'Loader status', 2, function ( assert ) {
497 var i, len, state,
498 modules = mw.loader.getModuleNames(),
499 error = [],
500 missing = [];
501
502 for ( i = 0, len = modules.length; i < len; i++ ) {
503 state = mw.loader.getState( modules[i] );
504 if ( state === 'error' ) {
505 error.push( modules[i] );
506 } else if ( state === 'missing' ) {
507 missing.push( modules[i] );
508 }
509 }
510
511 assert.deepEqual( error, [], 'Modules in error state' );
512 assert.deepEqual( missing, [], 'Modules in missing state' );
513 } );
514
515 QUnit.test( 'htmlEqual', 8, function ( assert ) {
516 assert.htmlEqual(
517 '<div><p class="some classes" data-length="10">Child paragraph with <a href="http://example.com">A link</a></p>Regular text<span>A span</span></div>',
518 '<div><p data-length=\'10\' class=\'some classes\'>Child paragraph with <a href=\'http://example.com\' >A link</a></p>Regular text<span>A span</span></div>',
519 'Attribute order, spacing and quotation marks (equal)'
520 );
521
522 assert.notHtmlEqual(
523 '<div><p class="some classes" data-length="10">Child paragraph with <a href="http://example.com">A link</a></p>Regular text<span>A span</span></div>',
524 '<div><p data-length=\'10\' class=\'some more classes\'>Child paragraph with <a href=\'http://example.com\' >A link</a></p>Regular text<span>A span</span></div>',
525 'Attribute order, spacing and quotation marks (not equal)'
526 );
527
528 assert.htmlEqual(
529 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
530 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
531 'Multiple root nodes (equal)'
532 );
533
534 assert.notHtmlEqual(
535 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
536 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
537 'Multiple root nodes (not equal, last label node is different)'
538 );
539
540 assert.htmlEqual(
541 'fo&quot;o<br/>b&gt;ar',
542 'fo"o<br/>b>ar',
543 'Extra escaping is equal'
544 );
545 assert.notHtmlEqual(
546 'foo&lt;br/&gt;bar',
547 'foo<br/>bar',
548 'Text escaping (not equal)'
549 );
550
551 assert.htmlEqual(
552 'foo<a href="http://example.com">example</a>bar',
553 'foo<a href="http://example.com">example</a>bar',
554 'Outer text nodes are compared (equal)'
555 );
556
557 assert.notHtmlEqual(
558 'foo<a href="http://example.com">example</a>bar',
559 'foo<a href="http://example.com">example</a>quux',
560 'Outer text nodes are compared (last text node different)'
561 );
562
563 } );
564
565 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
566
567 QUnit.test( 'Teardown', 3, function ( assert ) {
568 assert.equal( mw.html.escape( '<' ), '&lt;', 'teardown() callback was ran.' );
569 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
570 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
571 } );
572
573 }( jQuery, mediaWiki, QUnit ) );