Merge "SpecialMovepage: Convert form to use OOUI controls"
[lhc/web/wiklou.git] / tests / qunit / data / testrunner.js
1 /*global CompletenessTest, sinon */
2 /*jshint evil: true */
3 ( function ( $, mw, QUnit ) {
4 'use strict';
5
6 var mwTestIgnore, mwTester, addons;
7
8 /**
9 * Add bogus to url to prevent IE crazy caching
10 *
11 * @param {String} value a relative path (eg. 'data/foo.js'
12 * or 'data/test.php?foo=bar').
13 * @return {String} Such as 'data/foo.js?131031765087663960'
14 */
15 QUnit.fixurl = function ( value ) {
16 return value + ( /\?/.test( value ) ? '&' : '?' )
17 + String( new Date().getTime() )
18 + String( parseInt( Math.random() * 100000, 10 ) );
19 };
20
21 /**
22 * Configuration
23 */
24
25 // When a test() indicates asynchronicity with stop(),
26 // allow 30 seconds to pass before killing the test(),
27 // and assuming failure.
28 QUnit.config.testTimeout = 30 * 1000;
29
30 QUnit.config.requireExpects = true;
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 mwTester = new CompletenessTest( mw, mwTestIgnore );
162 }
163
164 /**
165 * Reset mw.config and others to a fresh copy of the live config for each test(),
166 * and restore it back to the live one afterwards.
167 *
168 * @param {Object} [localEnv]
169 * @example (see test suite at the bottom of this file)
170 * </code>
171 */
172 QUnit.newMwEnvironment = ( function () {
173 var warn, error, liveConfig, liveMessages,
174 ajaxRequests = [];
175
176 liveConfig = mw.config.values;
177 liveMessages = mw.messages.values;
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, custom );
206 restoreWarnings();
207
208 return copy;
209 }
210
211 function freshMessagesCopy( custom ) {
212 return $.extend( /*deep=*/true, {}, liveMessages, 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.values = freshConfigCopy( localEnv.config );
239 mw.messages.values = freshMessagesCopy( localEnv.messages );
240 this.suppressWarnings = suppressWarnings;
241 this.restoreWarnings = restoreWarnings;
242
243 // Start tracking ajax requests
244 $( document ).on( 'ajaxSend', trackAjax );
245
246 localEnv.setup.call( this );
247 },
248
249 teardown: function () {
250 var timers, pending, $activeLen;
251
252 localEnv.teardown.call( this );
253
254 // Stop tracking ajax requests
255 $( document ).off( 'ajaxSend', trackAjax );
256
257 // Farewell, mock environment!
258 mw.config.values = liveConfig;
259 mw.messages.values = liveMessages;
260
261 // As a convenience feature, automatically restore warnings if they're
262 // still suppressed by the end of the test.
263 restoreWarnings();
264
265 // Tests should use fake timers or wait for animations to complete
266 // Check for incomplete animations/requests/etc and throw if there are any.
267 if ( $.timers && $.timers.length !== 0 ) {
268 timers = $.timers.length;
269 $.each( $.timers, function ( i, timer ) {
270 var node = timer.elem;
271 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
272 mw.html.element( node.nodeName.toLowerCase(), $( node ).getAttrs() )
273 );
274 } );
275 // Force animations to stop to give the next test a clean start
276 $.fx.stop();
277
278 throw new Error( 'Unfinished animations: ' + timers );
279 }
280
281 // Test should use fake XHR, wait for requests, or call abort()
282 $activeLen = $.active;
283 if ( $activeLen !== undefined && $activeLen !== 0 ) {
284 pending = $.grep( ajaxRequests, function ( ajax ) {
285 return ajax.xhr.state() === 'pending';
286 } );
287 if ( pending.length !== $activeLen ) {
288 mw.log.warn( 'Pending requests does not match jQuery.active count' );
289 }
290 // Force requests to stop to give the next test a clean start
291 $.each( pending, function ( i, ajax ) {
292 mw.log.warn( 'Pending AJAX request #' + i, ajax.options );
293 ajax.xhr.abort();
294 } );
295 ajaxRequests = [];
296
297 throw new Error( 'Pending AJAX requests: ' + pending.length + ' (active: ' + $activeLen + ')' );
298 }
299 }
300 };
301 };
302 }() );
303
304 // $.when stops as soon as one fails, which makes sense in most
305 // practical scenarios, but not in a unit test where we really do
306 // need to wait until all of them are finished.
307 QUnit.whenPromisesComplete = function () {
308 var altPromises = [];
309
310 $.each( arguments, function ( i, arg ) {
311 var alt = $.Deferred();
312 altPromises.push( alt );
313
314 // Whether this one fails or not, forwards it to
315 // the 'done' (resolve) callback of the alternative promise.
316 arg.always( alt.resolve );
317 } );
318
319 return $.when.apply( $, altPromises );
320 };
321
322 /**
323 * Recursively convert a node to a plain object representing its structure.
324 * Only considers attributes and contents (elements and text nodes).
325 * Attribute values are compared strictly and not normalised.
326 *
327 * @param {Node} node
328 * @return {Object|string} Plain JavaScript value representing the node.
329 */
330 function getDomStructure( node ) {
331 var $node, children, processedChildren, i, len, el;
332 $node = $( node );
333 if ( node.nodeType === Node.ELEMENT_NODE ) {
334 children = $node.contents();
335 processedChildren = [];
336 for ( i = 0, len = children.length; i < len; i++ ) {
337 el = children[ i ];
338 if ( el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.TEXT_NODE ) {
339 processedChildren.push( getDomStructure( el ) );
340 }
341 }
342
343 return {
344 tagName: node.tagName,
345 attributes: $node.getAttrs(),
346 contents: processedChildren
347 };
348 } else {
349 // Should be text node
350 return $node.text();
351 }
352 }
353
354 /**
355 * Gets structure of node for this HTML.
356 *
357 * @param {string} html HTML markup for one or more nodes.
358 */
359 function getHtmlStructure( html ) {
360 var el = $( '<div>' ).append( html )[ 0 ];
361 return getDomStructure( el );
362 }
363
364 /**
365 * Add-on assertion helpers
366 */
367 // Define the add-ons
368 addons = {
369
370 // Expect boolean true
371 assertTrue: function ( actual, message ) {
372 QUnit.push( actual === true, actual, true, message );
373 },
374
375 // Expect boolean false
376 assertFalse: function ( actual, message ) {
377 QUnit.push( actual === false, actual, false, message );
378 },
379
380 // Expect numerical value less than X
381 lt: function ( actual, expected, message ) {
382 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
383 },
384
385 // Expect numerical value less than or equal to X
386 ltOrEq: function ( actual, expected, message ) {
387 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
388 },
389
390 // Expect numerical value greater than X
391 gt: function ( actual, expected, message ) {
392 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
393 },
394
395 // Expect numerical value greater than or equal to X
396 gtOrEq: function ( actual, expected, message ) {
397 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
398 },
399
400 /**
401 * Asserts that two HTML strings are structurally equivalent.
402 *
403 * @param {string} actualHtml Actual HTML markup.
404 * @param {string} expectedHtml Expected HTML markup
405 * @param {string} message Assertion message.
406 */
407 htmlEqual: function ( actualHtml, expectedHtml, message ) {
408 var actual = getHtmlStructure( actualHtml ),
409 expected = getHtmlStructure( expectedHtml );
410
411 QUnit.push(
412 QUnit.equiv(
413 actual,
414 expected
415 ),
416 actual,
417 expected,
418 message
419 );
420 },
421
422 /**
423 * Asserts that two HTML strings are not structurally equivalent.
424 *
425 * @param {string} actualHtml Actual HTML markup.
426 * @param {string} expectedHtml Expected HTML markup.
427 * @param {string} message Assertion message.
428 */
429 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
430 var actual = getHtmlStructure( actualHtml ),
431 expected = getHtmlStructure( expectedHtml );
432
433 QUnit.push(
434 !QUnit.equiv(
435 actual,
436 expected
437 ),
438 actual,
439 expected,
440 message
441 );
442 }
443 };
444
445 $.extend( QUnit.assert, addons );
446
447 /**
448 * Small test suite to confirm proper functionality of the utilities and
449 * initializations defined above in this file.
450 */
451 QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
452 setup: function () {
453 this.mwHtmlLive = mw.html;
454 mw.html = {
455 escape: function () {
456 return 'mocked';
457 }
458 };
459 },
460 teardown: function () {
461 mw.html = this.mwHtmlLive;
462 },
463 config: {
464 testVar: 'foo'
465 },
466 messages: {
467 testMsg: 'Foo.'
468 }
469 } ) );
470
471 QUnit.test( 'Setup', 3, function ( assert ) {
472 assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
473 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
474 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
475
476 mw.config.set( 'testVar', 'bar' );
477 mw.messages.set( 'testMsg', 'Bar.' );
478 } );
479
480 QUnit.test( 'Teardown', 2, function ( assert ) {
481 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
482 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
483 } );
484
485 QUnit.test( 'Loader status', 2, function ( assert ) {
486 var i, len, state,
487 modules = mw.loader.getModuleNames(),
488 error = [],
489 missing = [];
490
491 for ( i = 0, len = modules.length; i < len; i++ ) {
492 state = mw.loader.getState( modules[ i ] );
493 if ( state === 'error' ) {
494 error.push( modules[ i ] );
495 } else if ( state === 'missing' ) {
496 missing.push( modules[ i ] );
497 }
498 }
499
500 assert.deepEqual( error, [], 'Modules in error state' );
501 assert.deepEqual( missing, [], 'Modules in missing state' );
502 } );
503
504 QUnit.test( 'htmlEqual', 8, function ( assert ) {
505 assert.htmlEqual(
506 '<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>',
507 '<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>',
508 'Attribute order, spacing and quotation marks (equal)'
509 );
510
511 assert.notHtmlEqual(
512 '<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>',
513 '<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>',
514 'Attribute order, spacing and quotation marks (not equal)'
515 );
516
517 assert.htmlEqual(
518 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
519 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
520 'Multiple root nodes (equal)'
521 );
522
523 assert.notHtmlEqual(
524 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
525 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
526 'Multiple root nodes (not equal, last label node is different)'
527 );
528
529 assert.htmlEqual(
530 'fo&quot;o<br/>b&gt;ar',
531 'fo"o<br/>b>ar',
532 'Extra escaping is equal'
533 );
534 assert.notHtmlEqual(
535 'foo&lt;br/&gt;bar',
536 'foo<br/>bar',
537 'Text escaping (not equal)'
538 );
539
540 assert.htmlEqual(
541 'foo<a href="http://example.com">example</a>bar',
542 'foo<a href="http://example.com">example</a>bar',
543 'Outer text nodes are compared (equal)'
544 );
545
546 assert.notHtmlEqual(
547 'foo<a href="http://example.com">example</a>bar',
548 'foo<a href="http://example.com">example</a>quux',
549 'Outer text nodes are compared (last text node different)'
550 );
551
552 } );
553
554 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
555
556 QUnit.test( 'Teardown', 3, function ( assert ) {
557 assert.equal( mw.html.escape( '<' ), '&lt;', 'teardown() callback was ran.' );
558 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
559 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
560 } );
561
562 }( jQuery, mediaWiki, QUnit ) );