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