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