Merge "Auto-forward to search suggestion when zero results"
[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 value {String} 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 * @param localEnv {Object} [optional]
168 * @example (see test suite at the bottom of this file)
169 * </code>
170 */
171 QUnit.newMwEnvironment = ( function () {
172 var warn, error, liveConfig, liveMessages,
173 ajaxRequests = [];
174
175 liveConfig = mw.config.values;
176 liveMessages = mw.messages.values;
177
178 function suppressWarnings() {
179 warn = mw.log.warn;
180 error = mw.log.error;
181 mw.log.warn = mw.log.error = $.noop;
182 }
183
184 function restoreWarnings() {
185 // Guard against calls not balanced with suppressWarnings()
186 if ( warn !== undefined ) {
187 mw.log.warn = warn;
188 mw.log.error = error;
189 warn = error = undefined;
190 }
191 }
192
193 function freshConfigCopy( custom ) {
194 var copy;
195 // Tests should mock all factors that directly influence the tested code.
196 // For backwards compatibility though we set mw.config to a fresh copy of the live
197 // config. This way any modifications made to mw.config during the test will not
198 // affect other tests, nor the global scope outside the test runner.
199 // This is a shallow copy, since overriding an array or object value via "custom"
200 // should replace it. Setting a config property means you override it, not extend it.
201 // NOTE: It is important that we suppress warnings because extend() will also access
202 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
203 suppressWarnings();
204 copy = $.extend( {}, liveConfig, custom );
205 restoreWarnings();
206
207 return copy;
208 }
209
210 function freshMessagesCopy( custom ) {
211 return $.extend( /*deep=*/true, {}, liveMessages, custom );
212 }
213
214 /**
215 * @param {jQuery.Event} event
216 * @param {jqXHR} jqXHR
217 * @param {Object} ajaxOptions
218 */
219 function trackAjax( event, jqXHR, ajaxOptions ) {
220 ajaxRequests.push( { xhr: jqXHR, options: ajaxOptions } );
221 }
222
223 return function ( localEnv ) {
224 localEnv = $.extend( {
225 // QUnit
226 setup: $.noop,
227 teardown: $.noop,
228 // MediaWiki
229 config: {},
230 messages: {}
231 }, localEnv );
232
233 return {
234 setup: function () {
235
236 // Greetings, mock environment!
237 mw.config.values = freshConfigCopy( localEnv.config );
238 mw.messages.values = freshMessagesCopy( localEnv.messages );
239 this.suppressWarnings = suppressWarnings;
240 this.restoreWarnings = restoreWarnings;
241
242 // Start tracking ajax requests
243 $( document ).on( 'ajaxSend', trackAjax );
244
245 localEnv.setup.call( this );
246 },
247
248 teardown: function () {
249 var timers, active;
250
251 localEnv.teardown.call( this );
252
253 // Stop tracking ajax requests
254 $( document ).off( 'ajaxSend', trackAjax );
255
256 // Farewell, mock environment!
257 mw.config.values = liveConfig;
258 mw.messages.values = liveMessages;
259
260 // As a convenience feature, automatically restore warnings if they're
261 // still suppressed by the end of the test.
262 restoreWarnings();
263
264 // Tests should use fake timers or wait for animations to complete
265 // Check for incomplete animations/requests/etc and throw if there are any.
266 if ( $.timers && $.timers.length !== 0 ) {
267 timers = $.timers.length;
268 $.each( $.timers, function ( i, timer ) {
269 var node = timer.elem;
270 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
271 mw.html.element( node.nodeName.toLowerCase(), $(node).getAttrs() )
272 );
273 } );
274 // Force animations to stop to give the next test a clean start
275 $.fx.stop();
276
277 throw new Error( 'Unfinished animations: ' + timers );
278 }
279
280 // Test should use fake XHR, wait for requests, or call abort()
281 if ( $.active !== undefined && $.active !== 0 ) {
282 active = $.grep( ajaxRequests, function ( ajax ) {
283 return ajax.xhr.state() === 'pending';
284 } );
285 if ( active.length !== $.active ) {
286 mw.log.warn( 'Pending requests does not match jQuery.active count' );
287 }
288 // Force requests to stop to give the next test a clean start
289 $.each( active, function ( i, ajax ) {
290 mw.log.warn( 'Unfinished AJAX request #' + i, ajax.options );
291 ajax.xhr.abort();
292 } );
293 ajaxRequests = [];
294
295 throw new Error( 'Unfinished AJAX requests: ' + active.length );
296 }
297 }
298 };
299 };
300 }() );
301
302 // $.when stops as soon as one fails, which makes sense in most
303 // practical scenarios, but not in a unit test where we really do
304 // need to wait until all of them are finished.
305 QUnit.whenPromisesComplete = function () {
306 var altPromises = [];
307
308 $.each( arguments, function ( i, arg ) {
309 var alt = $.Deferred();
310 altPromises.push( alt );
311
312 // Whether this one fails or not, forwards it to
313 // the 'done' (resolve) callback of the alternative promise.
314 arg.always( alt.resolve );
315 } );
316
317 return $.when.apply( $, altPromises );
318 };
319
320 /**
321 * Recursively convert a node to a plain object representing its structure.
322 * Only considers attributes and contents (elements and text nodes).
323 * Attribute values are compared strictly and not normalised.
324 *
325 * @param {Node} node
326 * @return {Object|string} Plain JavaScript value representing the node.
327 */
328 function getDomStructure( node ) {
329 var $node, children, processedChildren, i, len, el;
330 $node = $( node );
331 if ( node.nodeType === Node.ELEMENT_NODE ) {
332 children = $node.contents();
333 processedChildren = [];
334 for ( i = 0, len = children.length; i < len; i++ ) {
335 el = children[i];
336 if ( el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.TEXT_NODE ) {
337 processedChildren.push( getDomStructure( el ) );
338 }
339 }
340
341 return {
342 tagName: node.tagName,
343 attributes: $node.getAttrs(),
344 contents: processedChildren
345 };
346 } else {
347 // Should be text node
348 return $node.text();
349 }
350 }
351
352 /**
353 * Gets structure of node for this HTML.
354 *
355 * @param {string} html HTML markup for one or more nodes.
356 */
357 function getHtmlStructure( html ) {
358 var el = $( '<div>' ).append( html )[0];
359 return getDomStructure( el );
360 }
361
362 /**
363 * Add-on assertion helpers
364 */
365 // Define the add-ons
366 addons = {
367
368 // Expect boolean true
369 assertTrue: function ( actual, message ) {
370 QUnit.push( actual === true, actual, true, message );
371 },
372
373 // Expect boolean false
374 assertFalse: function ( actual, message ) {
375 QUnit.push( actual === false, actual, false, message );
376 },
377
378 // Expect numerical value less than X
379 lt: function ( actual, expected, message ) {
380 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
381 },
382
383 // Expect numerical value less than or equal to X
384 ltOrEq: function ( actual, expected, message ) {
385 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
386 },
387
388 // Expect numerical value greater than X
389 gt: function ( actual, expected, message ) {
390 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
391 },
392
393 // Expect numerical value greater than or equal to X
394 gtOrEq: function ( actual, expected, message ) {
395 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
396 },
397
398 /**
399 * Asserts that two HTML strings are structurally equivalent.
400 *
401 * @param {string} actualHtml Actual HTML markup.
402 * @param {string} expectedHtml Expected HTML markup
403 * @param {string} message Assertion message.
404 */
405 htmlEqual: function ( actualHtml, expectedHtml, message ) {
406 var actual = getHtmlStructure( actualHtml ),
407 expected = getHtmlStructure( expectedHtml );
408
409 QUnit.push(
410 QUnit.equiv(
411 actual,
412 expected
413 ),
414 actual,
415 expected,
416 message
417 );
418 },
419
420 /**
421 * Asserts that two HTML strings are not structurally equivalent.
422 *
423 * @param {string} actualHtml Actual HTML markup.
424 * @param {string} expectedHtml Expected HTML markup.
425 * @param {string} message Assertion message.
426 */
427 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
428 var actual = getHtmlStructure( actualHtml ),
429 expected = getHtmlStructure( expectedHtml );
430
431 QUnit.push(
432 !QUnit.equiv(
433 actual,
434 expected
435 ),
436 actual,
437 expected,
438 message
439 );
440 }
441 };
442
443 $.extend( QUnit.assert, addons );
444
445 /**
446 * Small test suite to confirm proper functionality of the utilities and
447 * initializations defined above in this file.
448 */
449 QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
450 setup: function () {
451 this.mwHtmlLive = mw.html;
452 mw.html = {
453 escape: function () {
454 return 'mocked';
455 }
456 };
457 },
458 teardown: function () {
459 mw.html = this.mwHtmlLive;
460 },
461 config: {
462 testVar: 'foo'
463 },
464 messages: {
465 testMsg: 'Foo.'
466 }
467 } ) );
468
469 QUnit.test( 'Setup', 3, function ( assert ) {
470 assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
471 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
472 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
473
474 mw.config.set( 'testVar', 'bar' );
475 mw.messages.set( 'testMsg', 'Bar.' );
476 } );
477
478 QUnit.test( 'Teardown', 2, function ( assert ) {
479 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
480 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
481 } );
482
483 QUnit.test( 'Loader status', 2, function ( assert ) {
484 var i, len, state,
485 modules = mw.loader.getModuleNames(),
486 error = [],
487 missing = [];
488
489 for ( i = 0, len = modules.length; i < len; i++ ) {
490 state = mw.loader.getState( modules[i] );
491 if ( state === 'error' ) {
492 error.push( modules[i] );
493 } else if ( state === 'missing' ) {
494 missing.push( modules[i] );
495 }
496 }
497
498 assert.deepEqual( error, [], 'Modules in error state' );
499 assert.deepEqual( missing, [], 'Modules in missing state' );
500 } );
501
502 QUnit.test( 'htmlEqual', 8, function ( assert ) {
503 assert.htmlEqual(
504 '<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>',
505 '<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>',
506 'Attribute order, spacing and quotation marks (equal)'
507 );
508
509 assert.notHtmlEqual(
510 '<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>',
511 '<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>',
512 'Attribute order, spacing and quotation marks (not equal)'
513 );
514
515 assert.htmlEqual(
516 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
517 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
518 'Multiple root nodes (equal)'
519 );
520
521 assert.notHtmlEqual(
522 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
523 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
524 'Multiple root nodes (not equal, last label node is different)'
525 );
526
527 assert.htmlEqual(
528 'fo&quot;o<br/>b&gt;ar',
529 'fo"o<br/>b>ar',
530 'Extra escaping is equal'
531 );
532 assert.notHtmlEqual(
533 'foo&lt;br/&gt;bar',
534 'foo<br/>bar',
535 'Text escaping (not equal)'
536 );
537
538 assert.htmlEqual(
539 'foo<a href="http://example.com">example</a>bar',
540 'foo<a href="http://example.com">example</a>bar',
541 'Outer text nodes are compared (equal)'
542 );
543
544 assert.notHtmlEqual(
545 'foo<a href="http://example.com">example</a>bar',
546 'foo<a href="http://example.com">example</a>quux',
547 'Outer text nodes are compared (last text node different)'
548 );
549
550 } );
551
552 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
553
554 QUnit.test( 'Teardown', 3, function ( assert ) {
555 assert.equal( mw.html.escape( '<' ), '&lt;', 'teardown() callback was ran.' );
556 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
557 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
558 } );
559
560 }( jQuery, mediaWiki, QUnit ) );