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