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