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