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