Merge "SiteStats::jobs fix when there is a single job"
[lhc/web/wiklou.git] / tests / qunit / data / testrunner.js
1 /* global sinon */
2 ( function ( $, mw, QUnit ) {
3 'use strict';
4
5 var addons;
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;
81 if ( QUnit.config.moduleStack.length ) {
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
90 localEnv = localEnv || {};
91 orgBeforeEach = localEnv.beforeEach;
92 orgAfterEach = localEnv.afterEach;
93 localEnv.beforeEach = function () {
94 var config = sinon.getConfig( sinon.config );
95 config.injectInto = this;
96 sinon.sandbox.create( config );
97
98 if ( orgBeforeEach ) {
99 return orgBeforeEach.apply( this, arguments );
100 }
101 };
102 localEnv.afterEach = function () {
103 var ret;
104 if ( orgAfterEach ) {
105 ret = orgAfterEach.apply( this, arguments );
106 }
107
108 this.sandbox.verifyAndRestore();
109 return ret;
110 };
111 return orgModule( name, localEnv, executeNow );
112 };
113 }() );
114
115 // Extend QUnit.module to provide a fixture element.
116 ( function () {
117 var orgModule = QUnit.module;
118 QUnit.module = function ( name, localEnv, executeNow ) {
119 var orgBeforeEach, orgAfterEach;
120 if ( QUnit.config.moduleStack.length ) {
121 // In a nested module, don't re-run our handlers.
122 return orgModule.apply( this, arguments );
123 }
124 if ( arguments.length === 2 && typeof localEnv === 'function' ) {
125 executeNow = localEnv;
126 localEnv = undefined;
127 }
128
129 localEnv = localEnv || {};
130 orgBeforeEach = localEnv.beforeEach;
131 orgAfterEach = localEnv.afterEach;
132 localEnv.beforeEach = function () {
133 this.fixture = document.createElement( 'div' );
134 this.fixture.id = 'qunit-fixture';
135 document.body.appendChild( this.fixture );
136
137 if ( orgBeforeEach ) {
138 return orgBeforeEach.apply( this, arguments );
139 }
140 };
141 localEnv.afterEach = function () {
142 var ret;
143 if ( orgAfterEach ) {
144 ret = orgAfterEach.apply( this, arguments );
145 }
146
147 this.fixture.parentNode.removeChild( this.fixture );
148 return ret;
149 };
150 return orgModule( name, localEnv, executeNow );
151 };
152 }() );
153
154 // Extend QUnit.module to normalise localEnv.
155 // NOTE: This MUST be the last QUnit.module extension so that the above extensions
156 // may safely modify the object and assume beforeEach/afterEach.
157 ( function () {
158 var orgModule = QUnit.module;
159 QUnit.module = function ( name, localEnv, executeNow ) {
160 if ( typeof localEnv === 'object' ) {
161 localEnv = makeSafeEnv( localEnv );
162 }
163 return orgModule( name, localEnv, executeNow );
164 };
165 }() );
166
167 /**
168 * Reset mw.config and others to a fresh copy of the live config for each test(),
169 * and restore it back to the live one afterwards.
170 *
171 * @param {Object} [localEnv]
172 * @example (see test suite at the bottom of this file)
173 * </code>
174 */
175 QUnit.newMwEnvironment = ( function () {
176 var warn, error, liveConfig, liveMessages,
177 MwMap = mw.config.constructor, // internal use only
178 ajaxRequests = [];
179
180 liveConfig = mw.config;
181 liveMessages = mw.messages;
182
183 function suppressWarnings() {
184 if ( warn === undefined ) {
185 warn = mw.log.warn;
186 error = mw.log.error;
187 mw.log.warn = mw.log.error = $.noop;
188 }
189 }
190
191 function restoreWarnings() {
192 // Guard against calls not balanced with suppressWarnings()
193 if ( warn !== undefined ) {
194 mw.log.warn = warn;
195 mw.log.error = error;
196 warn = error = 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.get(), custom );
212 restoreWarnings();
213
214 return copy;
215 }
216
217 function freshMessagesCopy( custom ) {
218 return $.extend( /* deep */true, {}, liveMessages.get(), 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 return function ( orgEnv ) {
231 var localEnv = orgEnv ? makeSafeEnv( orgEnv ) : {};
232 // MediaWiki env testing
233 localEnv.config = orgEnv && orgEnv.config || {};
234 localEnv.messages = orgEnv && orgEnv.messages || {};
235
236 return {
237 beforeEach: function () {
238 // Greetings, mock environment!
239 mw.config = new MwMap();
240 mw.config.set( freshConfigCopy( localEnv.config ) );
241 mw.messages = new MwMap();
242 mw.messages.set( freshMessagesCopy( localEnv.messages ) );
243 // Update reference to mw.messages
244 mw.jqueryMsg.setParserDefaults( {
245 messages: mw.messages
246 } );
247
248 this.suppressWarnings = suppressWarnings;
249 this.restoreWarnings = restoreWarnings;
250
251 // Start tracking ajax requests
252 $( document ).on( 'ajaxSend', trackAjax );
253
254 if ( localEnv.beforeEach ) {
255 return localEnv.beforeEach.apply( this, arguments );
256 }
257 },
258
259 afterEach: function () {
260 var timers, pending, $activeLen, ret;
261
262 if ( localEnv.afterEach ) {
263 ret = localEnv.afterEach.apply( this, arguments );
264 }
265
266 // Stop tracking ajax requests
267 $( document ).off( 'ajaxSend', trackAjax );
268
269 // As a convenience feature, automatically restore warnings if they're
270 // still suppressed by the end of the test.
271 restoreWarnings();
272
273 // Farewell, mock environment!
274 mw.config = liveConfig;
275 mw.messages = liveMessages;
276 // Restore reference to mw.messages
277 mw.jqueryMsg.setParserDefaults( {
278 messages: liveMessages
279 } );
280
281 // Tests should use fake timers or wait for animations to complete
282 // Check for incomplete animations/requests/etc and throw if there are any.
283 if ( $.timers && $.timers.length !== 0 ) {
284 timers = $.timers.length;
285 $.each( $.timers, function ( i, timer ) {
286 var node = timer.elem;
287 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
288 mw.html.element( node.nodeName.toLowerCase(), $( node ).getAttrs() )
289 );
290 } );
291 // Force animations to stop to give the next test a clean start
292 $.timers = [];
293 $.fx.stop();
294
295 throw new Error( 'Unfinished animations: ' + timers );
296 }
297
298 // Test should use fake XHR, wait for requests, or call abort()
299 $activeLen = $.active;
300 if ( $activeLen !== undefined && $activeLen !== 0 ) {
301 pending = $.grep( ajaxRequests, function ( ajax ) {
302 return ajax.xhr.state() === 'pending';
303 } );
304 if ( pending.length !== $activeLen ) {
305 mw.log.warn( 'Pending requests does not match jQuery.active count' );
306 }
307 // Force requests to stop to give the next test a clean start
308 $.each( ajaxRequests, function ( i, ajax ) {
309 mw.log.warn(
310 'AJAX request #' + i + ' (state: ' + ajax.xhr.state() + ')',
311 ajax.options
312 );
313 ajax.xhr.abort();
314 } );
315 ajaxRequests = [];
316
317 throw new Error( 'Pending AJAX requests: ' + pending.length + ' (active: ' + $activeLen + ')' );
318 }
319
320 return ret;
321 }
322 };
323 };
324 }() );
325
326 // $.when stops as soon as one fails, which makes sense in most
327 // practical scenarios, but not in a unit test where we really do
328 // need to wait until all of them are finished.
329 QUnit.whenPromisesComplete = function () {
330 var altPromises = [];
331
332 $.each( arguments, function ( i, arg ) {
333 var alt = $.Deferred();
334 altPromises.push( alt );
335
336 // Whether this one fails or not, forwards it to
337 // the 'done' (resolve) callback of the alternative promise.
338 arg.always( alt.resolve );
339 } );
340
341 return $.when.apply( $, altPromises );
342 };
343
344 /**
345 * Recursively convert a node to a plain object representing its structure.
346 * Only considers attributes and contents (elements and text nodes).
347 * Attribute values are compared strictly and not normalised.
348 *
349 * @param {Node} node
350 * @return {Object|string} Plain JavaScript value representing the node.
351 */
352 function getDomStructure( node ) {
353 var $node, children, processedChildren, i, len, el;
354 $node = $( node );
355 if ( node.nodeType === Node.ELEMENT_NODE ) {
356 children = $node.contents();
357 processedChildren = [];
358 for ( i = 0, len = children.length; i < len; i++ ) {
359 el = children[ i ];
360 if ( el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.TEXT_NODE ) {
361 processedChildren.push( getDomStructure( el ) );
362 }
363 }
364
365 return {
366 tagName: node.tagName,
367 attributes: $node.getAttrs(),
368 contents: processedChildren
369 };
370 } else {
371 // Should be text node
372 return $node.text();
373 }
374 }
375
376 /**
377 * Gets structure of node for this HTML.
378 *
379 * @param {string} html HTML markup for one or more nodes.
380 */
381 function getHtmlStructure( html ) {
382 var el = $( '<div>' ).append( html )[ 0 ];
383 return getDomStructure( el );
384 }
385
386 /**
387 * Add-on assertion helpers
388 */
389 // Define the add-ons
390 addons = {
391
392 // Expect boolean true
393 assertTrue: function ( actual, message ) {
394 this.pushResult( {
395 result: actual === true,
396 actual: actual,
397 expected: true,
398 message: message
399 } );
400 },
401
402 // Expect boolean false
403 assertFalse: function ( actual, message ) {
404 this.pushResult( {
405 result: actual === false,
406 actual: actual,
407 expected: false,
408 message: message
409 } );
410 },
411
412 // Expect numerical value less than X
413 lt: function ( actual, expected, message ) {
414 this.pushResult( {
415 result: actual < expected,
416 actual: actual,
417 expected: 'less than ' + expected,
418 message: message
419 } );
420 },
421
422 // Expect numerical value less than or equal to X
423 ltOrEq: function ( actual, expected, message ) {
424 this.pushResult( {
425 result: actual <= expected,
426 actual: actual,
427 expected: 'less than or equal to ' + expected,
428 message: message
429 } );
430 },
431
432 // Expect numerical value greater than X
433 gt: function ( actual, expected, message ) {
434 this.pushResult( {
435 result: actual > expected,
436 actual: actual,
437 expected: 'greater than ' + expected,
438 message: message
439 } );
440 },
441
442 // Expect numerical value greater than or equal to X
443 gtOrEq: function ( actual, expected, message ) {
444 this.pushResult( {
445 result: actual >= true,
446 actual: actual,
447 expected: 'greater than or equal to ' + expected,
448 message: message
449 } );
450 },
451
452 /**
453 * Asserts that two HTML strings are structurally equivalent.
454 *
455 * @param {string} actualHtml Actual HTML markup.
456 * @param {string} expectedHtml Expected HTML markup
457 * @param {string} message Assertion message.
458 */
459 htmlEqual: function ( actualHtml, expectedHtml, message ) {
460 var actual = getHtmlStructure( actualHtml ),
461 expected = getHtmlStructure( expectedHtml );
462 this.pushResult( {
463 result: QUnit.equiv( actual, expected ),
464 actual: actual,
465 expected: expected,
466 message: message
467 } );
468 },
469
470 /**
471 * Asserts that two HTML strings are not structurally equivalent.
472 *
473 * @param {string} actualHtml Actual HTML markup.
474 * @param {string} expectedHtml Expected HTML markup.
475 * @param {string} message Assertion message.
476 */
477 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
478 var actual = getHtmlStructure( actualHtml ),
479 expected = getHtmlStructure( expectedHtml );
480
481 this.pushResult( {
482 result: !QUnit.equiv( actual, expected ),
483 actual: actual,
484 expected: expected,
485 message: message,
486 negative: true
487 } );
488 }
489 };
490
491 $.extend( QUnit.assert, addons );
492
493 /**
494 * Small test suite to confirm proper functionality of the utilities and
495 * initializations defined above in this file.
496 */
497 QUnit.module( 'testrunner', QUnit.newMwEnvironment( {
498 setup: function () {
499 this.mwHtmlLive = mw.html;
500 mw.html = {
501 escape: function () {
502 return 'mocked';
503 }
504 };
505 },
506 teardown: function () {
507 mw.html = this.mwHtmlLive;
508 },
509 config: {
510 testVar: 'foo'
511 },
512 messages: {
513 testMsg: 'Foo.'
514 }
515 } ) );
516
517 QUnit.test( 'Setup', function ( assert ) {
518 assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
519 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
520 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
521
522 mw.config.set( 'testVar', 'bar' );
523 mw.messages.set( 'testMsg', 'Bar.' );
524 } );
525
526 QUnit.test( 'Teardown', function ( assert ) {
527 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
528 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
529 } );
530
531 QUnit.test( 'Loader status', function ( assert ) {
532 var i, len, state,
533 modules = mw.loader.getModuleNames(),
534 error = [],
535 missing = [];
536
537 for ( i = 0, len = modules.length; i < len; i++ ) {
538 state = mw.loader.getState( modules[ i ] );
539 if ( state === 'error' ) {
540 error.push( modules[ i ] );
541 } else if ( state === 'missing' ) {
542 missing.push( modules[ i ] );
543 }
544 }
545
546 assert.deepEqual( error, [], 'Modules in error state' );
547 assert.deepEqual( missing, [], 'Modules in missing state' );
548 } );
549
550 QUnit.test( 'assert.htmlEqual', function ( assert ) {
551 assert.htmlEqual(
552 '<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>',
553 '<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>',
554 'Attribute order, spacing and quotation marks (equal)'
555 );
556
557 assert.notHtmlEqual(
558 '<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>',
559 '<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>',
560 'Attribute order, spacing and quotation marks (not equal)'
561 );
562
563 assert.htmlEqual(
564 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
565 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
566 'Multiple root nodes (equal)'
567 );
568
569 assert.notHtmlEqual(
570 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
571 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
572 'Multiple root nodes (not equal, last label node is different)'
573 );
574
575 assert.htmlEqual(
576 'fo&quot;o<br/>b&gt;ar',
577 'fo"o<br/>b>ar',
578 'Extra escaping is equal'
579 );
580 assert.notHtmlEqual(
581 'foo&lt;br/&gt;bar',
582 'foo<br/>bar',
583 'Text escaping (not equal)'
584 );
585
586 assert.htmlEqual(
587 'foo<a href="http://example.com">example</a>bar',
588 'foo<a href="http://example.com">example</a>bar',
589 'Outer text nodes are compared (equal)'
590 );
591
592 assert.notHtmlEqual(
593 'foo<a href="http://example.com">example</a>bar',
594 'foo<a href="http://example.com">example</a>quux',
595 'Outer text nodes are compared (last text node different)'
596 );
597 } );
598
599 QUnit.module( 'testrunner-after', QUnit.newMwEnvironment() );
600
601 QUnit.test( 'Teardown', function ( assert ) {
602 assert.equal( mw.html.escape( '<' ), '&lt;', 'teardown() callback was ran.' );
603 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
604 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
605 } );
606
607 QUnit.module( 'testrunner-each', {
608 beforeEach: function () {
609 this.mwHtmlLive = mw.html;
610 },
611 afterEach: function () {
612 mw.html = this.mwHtmlLive;
613 }
614 } );
615 QUnit.test( 'beforeEach', function ( assert ) {
616 assert.ok( this.mwHtmlLive, 'setup() ran' );
617 mw.html = null;
618 } );
619 QUnit.test( 'afterEach', function ( assert ) {
620 assert.equal( mw.html.escape( '<' ), '&lt;', 'afterEach() ran' );
621 } );
622
623 QUnit.module( 'testrunner-each-compat', {
624 setup: function () {
625 this.mwHtmlLive = mw.html;
626 },
627 teardown: function () {
628 mw.html = this.mwHtmlLive;
629 }
630 } );
631 QUnit.test( 'setup', function ( assert ) {
632 assert.ok( this.mwHtmlLive, 'setup() ran' );
633 mw.html = null;
634 } );
635 QUnit.test( 'teardown', function ( assert ) {
636 assert.equal( mw.html.escape( '<' ), '&lt;', 'teardown() ran' );
637 } );
638
639 // Regression test for 'this.sandbox undefined' error, fixed by
640 // ensuring Sinon setup/teardown is not re-run on inner module.
641 QUnit.module( 'testrunner-nested', function () {
642 QUnit.module( 'testrunner-nested-inner', function () {
643 QUnit.test( 'Dummy', function ( assert ) {
644 assert.ok( true, 'Nested modules supported' );
645 } );
646 } );
647 } );
648
649 }( jQuery, mediaWiki, QUnit ) );