Add autocomplete for WhatLinksHere subpages
[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 } );
41
42 /**
43 * CompletenessTest
44 *
45 * Adds toggle checkbox to header
46 */
47 QUnit.config.urlConfig.push( {
48 id: 'completenesstest',
49 label: 'Run CompletenessTest',
50 tooltip: 'Run the completeness test'
51 } );
52
53 /**
54 * SinonJS
55 *
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.
61 */
62 sinon.assert.fail = function ( msg ) {
63 QUnit.assert.ok( false, msg );
64 };
65 sinon.assert.pass = function ( msg ) {
66 QUnit.assert.ok( true, msg );
67 };
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
75 };
76 ( function () {
77 var orgModule = QUnit.module;
78
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 );
86
87 if ( localEnv.setup ) {
88 localEnv.setup.call( this );
89 }
90 },
91 teardown: function () {
92 this.sandbox.verifyAndRestore();
93
94 if ( localEnv.teardown ) {
95 localEnv.teardown.call( this );
96 }
97 }
98 } );
99 };
100 }() );
101
102 // Initiate when enabled
103 if ( QUnit.urlParams.completenesstest ) {
104
105 // Return true to ignore
106 mwTestIgnore = function ( val, tester ) {
107
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;
115 }
116 if ( val instanceof mw.Title ) {
117 tester.methodCallTracker.Title = true;
118 return true;
119 }
120
121 // Don't record methods of the properties of a jQuery object
122 if ( val instanceof $ ) {
123 return true;
124 }
125
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;
130 }
131
132 return false;
133 };
134
135 mwTester = new CompletenessTest( mw, mwTestIgnore );
136 }
137
138 /**
139 * Test environment recommended for all QUnit test modules
140 *
141 * Whether to log environment changes to the console
142 */
143 QUnit.config.urlConfig.push( 'mwlogenv' );
144
145 /**
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>
151 */
152 QUnit.newMwEnvironment = ( function () {
153 var warn, log, liveConfig, liveMessages;
154
155 liveConfig = mw.config.values;
156 liveMessages = mw.messages.values;
157
158 function suppressWarnings() {
159 warn = mw.log.warn;
160 mw.log.warn = $.noop;
161 }
162
163 function restoreWarnings() {
164 if ( warn !== undefined ) {
165 mw.log.warn = warn;
166 warn = undefined;
167 }
168 }
169
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();
183
184 return copy;
185 }
186
187 function freshMessagesCopy( custom ) {
188 return $.extend( /*deep=*/true, {}, liveMessages, custom );
189 }
190
191 log = QUnit.urlParams.mwlogenv ? mw.log : function () {};
192
193 return function ( localEnv ) {
194 localEnv = $.extend( {
195 // QUnit
196 setup: $.noop,
197 teardown: $.noop,
198 // MediaWiki
199 config: {},
200 messages: {}
201 }, localEnv );
202
203 return {
204 setup: function () {
205 log( 'MwEnvironment> SETUP for "' + QUnit.config.current.module
206 + ': ' + QUnit.config.current.testName + '"' );
207
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;
213
214 localEnv.setup.call( this );
215 },
216
217 teardown: function () {
218 var timers;
219 log( 'MwEnvironment> TEARDOWN for "' + QUnit.config.current.module
220 + ': ' + QUnit.config.current.testName + '"' );
221
222 localEnv.teardown.call( this );
223
224 // Farewell, mock environment!
225 mw.config.values = liveConfig;
226 mw.messages.values = liveMessages;
227
228 // As a convenience feature, automatically restore warnings if they're
229 // still suppressed by the end of the test.
230 restoreWarnings();
231
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() )
241 );
242 } );
243 // Force animations to stop to give the next test a clean start
244 $.fx.stop();
245
246 throw new Error( 'Unfinished animations: ' + timers );
247 }
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 );
252 }
253 }
254 };
255 };
256 }() );
257
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 = [];
263
264 $.each( arguments, function ( i, arg ) {
265 var alt = $.Deferred();
266 altPromises.push( alt );
267
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 } );
272
273 return $.when.apply( $, altPromises );
274 };
275
276 /**
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.
280 *
281 * @param {Node} node
282 * @return {Object|string} Plain JavaScript value representing the node.
283 */
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 ) );
294 }
295 }
296
297 return {
298 tagName: node.tagName,
299 attributes: $node.getAttrs(),
300 contents: processedChildren
301 };
302 } else {
303 // Should be text node
304 return $node.text();
305 }
306 }
307
308 /**
309 * Gets structure of node for this HTML.
310 *
311 * @param {string} html HTML markup for one or more nodes.
312 */
313 function getHtmlStructure( html ) {
314 var el = $( '<div>' ).append( html )[0];
315 return getDomStructure( el );
316 }
317
318 /**
319 * Add-on assertion helpers
320 */
321 // Define the add-ons
322 addons = {
323
324 // Expect boolean true
325 assertTrue: function ( actual, message ) {
326 QUnit.push( actual === true, actual, true, message );
327 },
328
329 // Expect boolean false
330 assertFalse: function ( actual, message ) {
331 QUnit.push( actual === false, actual, false, message );
332 },
333
334 // Expect numerical value less than X
335 lt: function ( actual, expected, message ) {
336 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
337 },
338
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 );
342 },
343
344 // Expect numerical value greater than X
345 gt: function ( actual, expected, message ) {
346 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
347 },
348
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 );
352 },
353
354 /**
355 * Asserts that two HTML strings are structurally equivalent.
356 *
357 * @param {string} actualHtml Actual HTML markup.
358 * @param {string} expectedHtml Expected HTML markup
359 * @param {string} message Assertion message.
360 */
361 htmlEqual: function ( actualHtml, expectedHtml, message ) {
362 var actual = getHtmlStructure( actualHtml ),
363 expected = getHtmlStructure( expectedHtml );
364
365 QUnit.push(
366 QUnit.equiv(
367 actual,
368 expected
369 ),
370 actual,
371 expected,
372 message
373 );
374 },
375
376 /**
377 * Asserts that two HTML strings are not structurally equivalent.
378 *
379 * @param {string} actualHtml Actual HTML markup.
380 * @param {string} expectedHtml Expected HTML markup.
381 * @param {string} message Assertion message.
382 */
383 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
384 var actual = getHtmlStructure( actualHtml ),
385 expected = getHtmlStructure( expectedHtml );
386
387 QUnit.push(
388 !QUnit.equiv(
389 actual,
390 expected
391 ),
392 actual,
393 expected,
394 message
395 );
396 }
397 };
398
399 $.extend( QUnit.assert, addons );
400
401 /**
402 * Small test suite to confirm proper functionality of the utilities and
403 * initializations defined above in this file.
404 */
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';
411 }
412 };
413 },
414 teardown: function () {
415 mw.html = this.mwHtmlLive;
416 },
417 config: {
418 testVar: 'foo'
419 },
420 messages: {
421 testMsg: 'Foo.'
422 }
423 } ) );
424
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' );
429
430 mw.config.set( 'testVar', 'bar' );
431 mw.messages.set( 'testMsg', 'Bar.' );
432 } );
433
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 } );
438
439 QUnit.test( 'Loader status', 2, function ( assert ) {
440 var i, len, state,
441 modules = mw.loader.getModuleNames(),
442 error = [],
443 missing = [];
444
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] );
451 }
452 }
453
454 assert.deepEqual( error, [], 'Modules in error state' );
455 assert.deepEqual( missing, [], 'Modules in missing state' );
456 } );
457
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)'
463 );
464
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)'
469 );
470
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)'
475 );
476
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)'
481 );
482
483 assert.htmlEqual(
484 'fo&quot;o<br/>b&gt;ar',
485 'fo"o<br/>b>ar',
486 'Extra escaping is equal'
487 );
488 assert.notHtmlEqual(
489 'foo&lt;br/&gt;bar',
490 'foo<br/>bar',
491 'Text escaping (not equal)'
492 );
493
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)'
498 );
499
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)'
504 );
505
506 } );
507
508 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
509
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 } );
515
516 }( jQuery, mediaWiki, QUnit ) );