Merge "API: Expose $wgGalleryOptions in the meta=siteinfo"
[lhc/web/wiklou.git] / tests / qunit / data / testrunner.js
1 /*global CompletenessTest, sinon */
2 ( function ( $, mw, QUnit ) {
3 'use strict';
4
5 var mwTestIgnore, mwTester, 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 $.fx.speeds._default = 0;
30
31 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
32 QUnit.config.urlConfig.push( {
33 id: 'debug',
34 label: 'Enable ResourceLoaderDebug',
35 tooltip: 'Enable debug mode in ResourceLoader',
36 value: 'true'
37 } );
38
39 /**
40 * CompletenessTest
41 *
42 * Adds toggle checkbox to header
43 */
44 QUnit.config.urlConfig.push( {
45 id: 'completenesstest',
46 label: 'Run CompletenessTest',
47 tooltip: 'Run the completeness test'
48 } );
49
50 /**
51 * SinonJS
52 *
53 * Glue code for nicer integration with QUnit setup/teardown
54 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
55 * Fixes:
56 * - Work properly with asynchronous QUnit by using module setup/teardown
57 * instead of synchronously wrapping QUnit.test.
58 */
59 sinon.assert.fail = function ( msg ) {
60 QUnit.assert.ok( false, msg );
61 };
62 sinon.assert.pass = function ( msg ) {
63 QUnit.assert.ok( true, msg );
64 };
65 sinon.config = {
66 injectIntoThis: true,
67 injectInto: null,
68 properties: [ 'spy', 'stub', 'mock', 'sandbox' ],
69 // Don't fake timers by default
70 useFakeTimers: false,
71 useFakeServer: false
72 };
73 ( function () {
74 var orgModule = QUnit.module;
75
76 QUnit.module = function ( name, localEnv ) {
77 localEnv = localEnv || {};
78 orgModule( name, {
79 setup: function () {
80 var config = sinon.getConfig( sinon.config );
81 config.injectInto = this;
82 sinon.sandbox.create( config );
83
84 if ( localEnv.setup ) {
85 localEnv.setup.call( this );
86 }
87 },
88 teardown: function () {
89 if ( localEnv.teardown ) {
90 localEnv.teardown.call( this );
91 }
92
93 this.sandbox.verifyAndRestore();
94 }
95 } );
96 };
97 }() );
98
99 // Extend QUnit.module to provide a fixture element.
100 ( function () {
101 var orgModule = QUnit.module;
102
103 QUnit.module = function ( name, localEnv ) {
104 var fixture;
105 localEnv = localEnv || {};
106 orgModule( name, {
107 setup: function () {
108 fixture = document.createElement( 'div' );
109 fixture.id = 'qunit-fixture';
110 document.body.appendChild( fixture );
111
112 if ( localEnv.setup ) {
113 localEnv.setup.call( this );
114 }
115 },
116 teardown: function () {
117 if ( localEnv.teardown ) {
118 localEnv.teardown.call( this );
119 }
120
121 fixture.parentNode.removeChild( fixture );
122 }
123 } );
124 };
125 }() );
126
127 // Initiate when enabled
128 if ( QUnit.urlParams.completenesstest ) {
129
130 // Return true to ignore
131 mwTestIgnore = function ( val, tester ) {
132
133 // Don't record methods of the properties of constructors,
134 // to avoid getting into a loop (prototype.constructor.prototype..).
135 // Since we're therefor skipping any injection for
136 // "new mw.Foo()", manually set it to true here.
137 if ( val instanceof mw.Map ) {
138 tester.methodCallTracker.Map = true;
139 return true;
140 }
141 if ( val instanceof mw.Title ) {
142 tester.methodCallTracker.Title = true;
143 return true;
144 }
145
146 // Don't record methods of the properties of a jQuery object
147 if ( val instanceof $ ) {
148 return true;
149 }
150
151 // Don't iterate over the module registry (the 'script' references would
152 // be listed as untested methods otherwise)
153 if ( val === mw.loader.moduleRegistry ) {
154 return true;
155 }
156
157 return false;
158 };
159
160 mwTester = new CompletenessTest( mw, mwTestIgnore );
161 }
162
163 /**
164 * Reset mw.config and others to a fresh copy of the live config for each test(),
165 * and restore it back to the live one afterwards.
166 *
167 * @param {Object} [localEnv]
168 * @example (see test suite at the bottom of this file)
169 * </code>
170 */
171 QUnit.newMwEnvironment = ( function () {
172 var warn, error, liveConfig, liveMessages,
173 MwMap = mw.config.constructor, // internal use only
174 ajaxRequests = [];
175
176 liveConfig = mw.config;
177 liveMessages = mw.messages;
178
179 function suppressWarnings() {
180 warn = mw.log.warn;
181 error = mw.log.error;
182 mw.log.warn = mw.log.error = $.noop;
183 }
184
185 function restoreWarnings() {
186 // Guard against calls not balanced with suppressWarnings()
187 if ( warn !== undefined ) {
188 mw.log.warn = warn;
189 mw.log.error = error;
190 warn = error = undefined;
191 }
192 }
193
194 function freshConfigCopy( custom ) {
195 var copy;
196 // Tests should mock all factors that directly influence the tested code.
197 // For backwards compatibility though we set mw.config to a fresh copy of the live
198 // config. This way any modifications made to mw.config during the test will not
199 // affect other tests, nor the global scope outside the test runner.
200 // This is a shallow copy, since overriding an array or object value via "custom"
201 // should replace it. Setting a config property means you override it, not extend it.
202 // NOTE: It is important that we suppress warnings because extend() will also access
203 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
204 suppressWarnings();
205 copy = $.extend( {}, liveConfig.get(), custom );
206 restoreWarnings();
207
208 return copy;
209 }
210
211 function freshMessagesCopy( custom ) {
212 return $.extend( /*deep=*/true, {}, liveMessages.get(), custom );
213 }
214
215 /**
216 * @param {jQuery.Event} event
217 * @param {jqXHR} jqXHR
218 * @param {Object} ajaxOptions
219 */
220 function trackAjax( event, jqXHR, ajaxOptions ) {
221 ajaxRequests.push( { xhr: jqXHR, options: ajaxOptions } );
222 }
223
224 return function ( localEnv ) {
225 localEnv = $.extend( {
226 // QUnit
227 setup: $.noop,
228 teardown: $.noop,
229 // MediaWiki
230 config: {},
231 messages: {}
232 }, localEnv );
233
234 return {
235 setup: function () {
236
237 // Greetings, mock environment!
238 mw.config = new MwMap();
239 mw.config.set( freshConfigCopy( localEnv.config ) );
240 mw.messages = new MwMap();
241 mw.messages.set( freshMessagesCopy( localEnv.messages ) );
242 // Update reference to mw.messages
243 mw.jqueryMsg.setParserDefaults( {
244 messages: mw.messages
245 } );
246
247 this.suppressWarnings = suppressWarnings;
248 this.restoreWarnings = restoreWarnings;
249
250 // Start tracking ajax requests
251 $( document ).on( 'ajaxSend', trackAjax );
252
253 localEnv.setup.call( this );
254 },
255
256 teardown: function () {
257 var timers, pending, $activeLen;
258
259 localEnv.teardown.call( this );
260
261 // Stop tracking ajax requests
262 $( document ).off( 'ajaxSend', trackAjax );
263
264 // Farewell, mock environment!
265 mw.config = liveConfig;
266 mw.messages = liveMessages;
267 // Restore reference to mw.messages
268 mw.jqueryMsg.setParserDefaults( {
269 messages: liveMessages
270 } );
271
272 // As a convenience feature, automatically restore warnings if they're
273 // still suppressed by the end of the test.
274 restoreWarnings();
275
276 // Tests should use fake timers or wait for animations to complete
277 // Check for incomplete animations/requests/etc and throw if there are any.
278 if ( $.timers && $.timers.length !== 0 ) {
279 timers = $.timers.length;
280 $.each( $.timers, function ( i, timer ) {
281 var node = timer.elem;
282 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
283 mw.html.element( node.nodeName.toLowerCase(), $( node ).getAttrs() )
284 );
285 } );
286 // Force animations to stop to give the next test a clean start
287 $.fx.stop();
288
289 throw new Error( 'Unfinished animations: ' + timers );
290 }
291
292 // Test should use fake XHR, wait for requests, or call abort()
293 $activeLen = $.active;
294 if ( $activeLen !== undefined && $activeLen !== 0 ) {
295 pending = $.grep( ajaxRequests, function ( ajax ) {
296 return ajax.xhr.state() === 'pending';
297 } );
298 if ( pending.length !== $activeLen ) {
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( pending, function ( i, ajax ) {
303 mw.log.warn( 'Pending AJAX request #' + i, ajax.options );
304 ajax.xhr.abort();
305 } );
306 ajaxRequests = [];
307
308 throw new Error( 'Pending AJAX requests: ' + pending.length + ' (active: ' + $activeLen + ')' );
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 === Node.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 === Node.ELEMENT_NODE || el.nodeType === Node.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 ) );