Don't display composer installed extensions/skins on Special:Version
[mediawiki.git] / tests / qunit / data / testrunner.js
blob7294d62b42037a45ccf7fa875ed8bcd4e960e03f
1 /*global CompletenessTest, sinon */
2 /*jshint evil: true */
3 ( function ( $, mw, QUnit ) {
4 'use strict';
6 var mwTestIgnore, mwTester,
7 addons,
8 ELEMENT_NODE = 1,
9 TEXT_NODE = 3;
11 /**
12 * Add bogus to url to prevent IE crazy caching
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'
18 QUnit.fixurl = function ( value ) {
19 return value + (/\?/.test( value ) ? '&' : '?')
20 + String( new Date().getTime() )
21 + String( parseInt( Math.random() * 100000, 10 ) );
24 /**
25 * Configuration
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;
33 QUnit.config.requireExpects = true;
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 } );
42 /**
43 * CompletenessTest
45 * Adds toggle checkbox to header
47 QUnit.config.urlConfig.push( {
48 id: 'completenesstest',
49 label: 'Run CompletenessTest',
50 tooltip: 'Run the completeness test'
51 } );
53 /**
54 * SinonJS
56 * Glue code for nicer integration with QUnit setup/teardown
57 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
58 * Fixes:
59 * - Work properly with asynchronous QUnit by using module setup/teardown
60 * instead of synchronously wrapping QUnit.test.
62 sinon.assert.fail = function ( msg ) {
63 QUnit.assert.ok( false, msg );
65 sinon.assert.pass = function ( msg ) {
66 QUnit.assert.ok( true, msg );
68 sinon.config = {
69 injectIntoThis: true,
70 injectInto: null,
71 properties: ['spy', 'stub', 'mock', 'sandbox'],
72 // Don't fake timers by default
73 useFakeTimers: false,
74 useFakeServer: false
76 ( function () {
77 var orgModule = QUnit.module;
79 QUnit.module = function ( name, localEnv ) {
80 localEnv = localEnv || {};
81 orgModule( name, {
82 setup: function () {
83 var config = sinon.getConfig( sinon.config );
84 config.injectInto = this;
85 sinon.sandbox.create( config );
87 if ( localEnv.setup ) {
88 localEnv.setup.call( this );
91 teardown: function () {
92 this.sandbox.verifyAndRestore();
94 if ( localEnv.teardown ) {
95 localEnv.teardown.call( this );
98 } );
100 }() );
102 // Initiate when enabled
103 if ( QUnit.urlParams.completenesstest ) {
105 // Return true to ignore
106 mwTestIgnore = function ( val, tester ) {
108 // Don't record methods of the properties of constructors,
109 // to avoid getting into a loop (prototype.constructor.prototype..).
110 // Since we're therefor skipping any injection for
111 // "new mw.Foo()", manually set it to true here.
112 if ( val instanceof mw.Map ) {
113 tester.methodCallTracker.Map = true;
114 return true;
116 if ( val instanceof mw.Title ) {
117 tester.methodCallTracker.Title = true;
118 return true;
121 // Don't record methods of the properties of a jQuery object
122 if ( val instanceof $ ) {
123 return true;
126 // Don't iterate over the module registry (the 'script' references would
127 // be listed as untested methods otherwise)
128 if ( val === mw.loader.moduleRegistry ) {
129 return true;
132 return false;
135 mwTester = new CompletenessTest( mw, mwTestIgnore );
139 * Test environment recommended for all QUnit test modules
141 * Whether to log environment changes to the console
143 QUnit.config.urlConfig.push( 'mwlogenv' );
146 * Reset mw.config and others to a fresh copy of the live config for each test(),
147 * and restore it back to the live one afterwards.
148 * @param localEnv {Object} [optional]
149 * @example (see test suite at the bottom of this file)
150 * </code>
152 QUnit.newMwEnvironment = ( function () {
153 var warn, log, liveConfig, liveMessages;
155 liveConfig = mw.config.values;
156 liveMessages = mw.messages.values;
158 function suppressWarnings() {
159 warn = mw.log.warn;
160 mw.log.warn = $.noop;
163 function restoreWarnings() {
164 if ( warn !== undefined ) {
165 mw.log.warn = warn;
166 warn = undefined;
170 function freshConfigCopy( custom ) {
171 var copy;
172 // Tests should mock all factors that directly influence the tested code.
173 // For backwards compatibility though we set mw.config to a fresh copy of the live
174 // config. This way any modifications made to mw.config during the test will not
175 // affect other tests, nor the global scope outside the test runner.
176 // This is a shallow copy, since overriding an array or object value via "custom"
177 // should replace it. Setting a config property means you override it, not extend it.
178 // NOTE: It is important that we suppress warnings because extend() will also access
179 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
180 suppressWarnings();
181 copy = $.extend( {}, liveConfig, custom );
182 restoreWarnings();
184 return copy;
187 function freshMessagesCopy( custom ) {
188 return $.extend( /*deep=*/true, {}, liveMessages, custom );
191 log = QUnit.urlParams.mwlogenv ? mw.log : function () {};
193 return function ( localEnv ) {
194 localEnv = $.extend( {
195 // QUnit
196 setup: $.noop,
197 teardown: $.noop,
198 // MediaWiki
199 config: {},
200 messages: {}
201 }, localEnv );
203 return {
204 setup: function () {
205 log( 'MwEnvironment> SETUP for "' + QUnit.config.current.module
206 + ': ' + QUnit.config.current.testName + '"' );
208 // Greetings, mock environment!
209 mw.config.values = freshConfigCopy( localEnv.config );
210 mw.messages.values = freshMessagesCopy( localEnv.messages );
211 this.suppressWarnings = suppressWarnings;
212 this.restoreWarnings = restoreWarnings;
214 localEnv.setup.call( this );
217 teardown: function () {
218 var timers;
219 log( 'MwEnvironment> TEARDOWN for "' + QUnit.config.current.module
220 + ': ' + QUnit.config.current.testName + '"' );
222 localEnv.teardown.call( this );
224 // Farewell, mock environment!
225 mw.config.values = liveConfig;
226 mw.messages.values = liveMessages;
228 // As a convenience feature, automatically restore warnings if they're
229 // still suppressed by the end of the test.
230 restoreWarnings();
232 // Check for incomplete animations/requests/etc and throw
233 // error if there are any.
234 if ( $.timers && $.timers.length !== 0 ) {
235 timers = $.timers.length;
236 // Tests shoulld use fake timers or wait for animations to complete
237 $.each( $.timers, function ( i, timer ) {
238 var node = timer.elem;
239 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
240 mw.html.element( node.nodeName.toLowerCase(), $(node).getAttrs() )
242 } );
243 // Force animations to stop to give the next test a clean start
244 $.fx.stop();
246 throw new Error( 'Unfinished animations: ' + timers );
248 if ( $.active !== undefined && $.active !== 0 ) {
249 // Test may need to use fake XHR, wait for requests or
250 // call abort().
251 throw new Error( 'Unfinished AJAX requests: ' + $.active );
256 }() );
258 // $.when stops as soon as one fails, which makes sense in most
259 // practical scenarios, but not in a unit test where we really do
260 // need to wait until all of them are finished.
261 QUnit.whenPromisesComplete = function () {
262 var altPromises = [];
264 $.each( arguments, function ( i, arg ) {
265 var alt = $.Deferred();
266 altPromises.push( alt );
268 // Whether this one fails or not, forwards it to
269 // the 'done' (resolve) callback of the alternative promise.
270 arg.always( alt.resolve );
271 } );
273 return $.when.apply( $, altPromises );
277 * Recursively convert a node to a plain object representing its structure.
278 * Only considers attributes and contents (elements and text nodes).
279 * Attribute values are compared strictly and not normalised.
281 * @param {Node} node
282 * @return {Object|string} Plain JavaScript value representing the node.
284 function getDomStructure( node ) {
285 var $node, children, processedChildren, i, len, el;
286 $node = $( node );
287 if ( node.nodeType === ELEMENT_NODE ) {
288 children = $node.contents();
289 processedChildren = [];
290 for ( i = 0, len = children.length; i < len; i++ ) {
291 el = children[i];
292 if ( el.nodeType === ELEMENT_NODE || el.nodeType === TEXT_NODE ) {
293 processedChildren.push( getDomStructure( el ) );
297 return {
298 tagName: node.tagName,
299 attributes: $node.getAttrs(),
300 contents: processedChildren
302 } else {
303 // Should be text node
304 return $node.text();
309 * Gets structure of node for this HTML.
311 * @param {string} html HTML markup for one or more nodes.
313 function getHtmlStructure( html ) {
314 var el = $( '<div>' ).append( html )[0];
315 return getDomStructure( el );
319 * Add-on assertion helpers
321 // Define the add-ons
322 addons = {
324 // Expect boolean true
325 assertTrue: function ( actual, message ) {
326 QUnit.push( actual === true, actual, true, message );
329 // Expect boolean false
330 assertFalse: function ( actual, message ) {
331 QUnit.push( actual === false, actual, false, message );
334 // Expect numerical value less than X
335 lt: function ( actual, expected, message ) {
336 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
339 // Expect numerical value less than or equal to X
340 ltOrEq: function ( actual, expected, message ) {
341 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
344 // Expect numerical value greater than X
345 gt: function ( actual, expected, message ) {
346 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
349 // Expect numerical value greater than or equal to X
350 gtOrEq: function ( actual, expected, message ) {
351 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
355 * Asserts that two HTML strings are structurally equivalent.
357 * @param {string} actualHtml Actual HTML markup.
358 * @param {string} expectedHtml Expected HTML markup
359 * @param {string} message Assertion message.
361 htmlEqual: function ( actualHtml, expectedHtml, message ) {
362 var actual = getHtmlStructure( actualHtml ),
363 expected = getHtmlStructure( expectedHtml );
365 QUnit.push(
366 QUnit.equiv(
367 actual,
368 expected
370 actual,
371 expected,
372 message
377 * Asserts that two HTML strings are not structurally equivalent.
379 * @param {string} actualHtml Actual HTML markup.
380 * @param {string} expectedHtml Expected HTML markup.
381 * @param {string} message Assertion message.
383 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
384 var actual = getHtmlStructure( actualHtml ),
385 expected = getHtmlStructure( expectedHtml );
387 QUnit.push(
388 !QUnit.equiv(
389 actual,
390 expected
392 actual,
393 expected,
394 message
399 $.extend( QUnit.assert, addons );
402 * Small test suite to confirm proper functionality of the utilities and
403 * initializations defined above in this file.
405 QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
406 setup: function () {
407 this.mwHtmlLive = mw.html;
408 mw.html = {
409 escape: function () {
410 return 'mocked';
414 teardown: function () {
415 mw.html = this.mwHtmlLive;
417 config: {
418 testVar: 'foo'
420 messages: {
421 testMsg: 'Foo.'
423 } ) );
425 QUnit.test( 'Setup', 3, function ( assert ) {
426 assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
427 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
428 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
430 mw.config.set( 'testVar', 'bar' );
431 mw.messages.set( 'testMsg', 'Bar.' );
432 } );
434 QUnit.test( 'Teardown', 2, function ( assert ) {
435 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
436 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
437 } );
439 QUnit.test( 'Loader status', 2, function ( assert ) {
440 var i, len, state,
441 modules = mw.loader.getModuleNames(),
442 error = [],
443 missing = [];
445 for ( i = 0, len = modules.length; i < len; i++ ) {
446 state = mw.loader.getState( modules[i] );
447 if ( state === 'error' ) {
448 error.push( modules[i] );
449 } else if ( state === 'missing' ) {
450 missing.push( modules[i] );
454 assert.deepEqual( error, [], 'Modules in error state' );
455 assert.deepEqual( missing, [], 'Modules in missing state' );
456 } );
458 QUnit.test( 'htmlEqual', 8, function ( assert ) {
459 assert.htmlEqual(
460 '<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>',
461 '<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>',
462 'Attribute order, spacing and quotation marks (equal)'
465 assert.notHtmlEqual(
466 '<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>',
467 '<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>',
468 'Attribute order, spacing and quotation marks (not equal)'
471 assert.htmlEqual(
472 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
473 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
474 'Multiple root nodes (equal)'
477 assert.notHtmlEqual(
478 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
479 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
480 'Multiple root nodes (not equal, last label node is different)'
483 assert.htmlEqual(
484 'fo&quot;o<br/>b&gt;ar',
485 'fo"o<br/>b>ar',
486 'Extra escaping is equal'
488 assert.notHtmlEqual(
489 'foo&lt;br/&gt;bar',
490 'foo<br/>bar',
491 'Text escaping (not equal)'
494 assert.htmlEqual(
495 'foo<a href="http://example.com">example</a>bar',
496 'foo<a href="http://example.com">example</a>bar',
497 'Outer text nodes are compared (equal)'
500 assert.notHtmlEqual(
501 'foo<a href="http://example.com">example</a>bar',
502 'foo<a href="http://example.com">example</a>quux',
503 'Outer text nodes are compared (last text node different)'
506 } );
508 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
510 QUnit.test( 'Teardown', 3, function ( assert ) {
511 assert.equal( mw.html.escape( '<' ), '&lt;', 'teardown() callback was ran.' );
512 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
513 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
514 } );
516 }( jQuery, mediaWiki, QUnit ) );