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