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