Merge "Revert "Log the reason why revision->getContent() returns null""
[lhc/web/wiklou.git] / tests / qunit / data / testrunner.js
1 /* global sinon */
2 ( function ( $, mw, QUnit ) {
3 'use strict';
4
5 var addons, nested;
6
7 /**
8 * Make a safe copy of localEnv:
9 * - Creates a new object that inherits, instead of modifying the original.
10 * This prevents recursion in the event that a test suite stores inherits
11 * hooks object statically and passes it to multiple QUnit.module() calls.
12 * - Supporting QUnit 1.x 'setup' and 'teardown' hooks
13 * (deprecated in QUnit 1.16, removed in QUnit 2).
14 */
15 function makeSafeEnv( localEnv ) {
16 var wrap = localEnv ? Object.create( localEnv ) : {};
17 if ( wrap.setup ) {
18 wrap.beforeEach = wrap.beforeEach || wrap.setup;
19 }
20 if ( wrap.teardown ) {
21 wrap.afterEach = wrap.afterEach || wrap.teardown;
22 }
23 return wrap;
24 }
25
26 /**
27 * Add bogus to url to prevent IE crazy caching
28 *
29 * @param {string} value a relative path (eg. 'data/foo.js'
30 * or 'data/test.php?foo=bar').
31 * @return {string} Such as 'data/foo.js?131031765087663960'
32 */
33 QUnit.fixurl = function ( value ) {
34 return value + ( /\?/.test( value ) ? '&' : '?' )
35 + String( new Date().getTime() )
36 + String( parseInt( Math.random() * 100000, 10 ) );
37 };
38
39 /**
40 * Configuration
41 */
42
43 // For each test() that is asynchronous, allow this time to pass before
44 // killing the test and assuming timeout failure.
45 QUnit.config.testTimeout = 60 * 1000;
46
47 // Reduce default animation duration from 400ms to 0ms for unit tests
48 // eslint-disable-next-line no-underscore-dangle
49 $.fx.speeds._default = 0;
50
51 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
52 QUnit.config.urlConfig.push( {
53 id: 'debug',
54 label: 'Enable ResourceLoaderDebug',
55 tooltip: 'Enable debug mode in ResourceLoader',
56 value: 'true'
57 } );
58
59 /**
60 * SinonJS
61 *
62 * Glue code for nicer integration with QUnit setup/teardown
63 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
64 */
65 sinon.assert.fail = function ( msg ) {
66 QUnit.assert.ok( false, msg );
67 };
68 sinon.assert.pass = function ( msg ) {
69 QUnit.assert.ok( true, msg );
70 };
71 sinon.config = {
72 injectIntoThis: true,
73 injectInto: null,
74 properties: [ 'spy', 'stub', 'mock', 'sandbox' ],
75 // Don't fake timers by default
76 useFakeTimers: false,
77 useFakeServer: false
78 };
79 // Extend QUnit.module with:
80 // - Add support for QUnit 1.x 'setup' and 'teardown' hooks
81 // - Add a Sinon sandbox to the test context.
82 // - Add a test fixture to the test context.
83 ( function () {
84 var orgModule = QUnit.module;
85 QUnit.module = function ( name, localEnv, executeNow ) {
86 var orgExecute, orgBeforeEach, orgAfterEach;
87 if ( nested ) {
88 // In a nested module, don't re-add our hooks, QUnit does that already.
89 return orgModule.apply( this, arguments );
90 }
91 if ( arguments.length === 2 && typeof localEnv === 'function' ) {
92 executeNow = localEnv;
93 localEnv = undefined;
94 }
95 if ( executeNow ) {
96 // Wrap executeNow() so that we can detect nested modules
97 orgExecute = executeNow;
98 executeNow = function () {
99 var ret;
100 nested = true;
101 ret = orgExecute.apply( this, arguments );
102 nested = false;
103 return ret;
104 };
105 }
106
107 localEnv = makeSafeEnv( localEnv );
108 orgBeforeEach = localEnv.beforeEach;
109 orgAfterEach = localEnv.afterEach;
110
111 localEnv.beforeEach = function () {
112 // Sinon sandbox
113 var config = sinon.getConfig( sinon.config );
114 config.injectInto = this;
115 sinon.sandbox.create( config );
116
117 // Fixture element
118 this.fixture = document.createElement( 'div' );
119 this.fixture.id = 'qunit-fixture';
120 document.body.appendChild( this.fixture );
121
122 if ( orgBeforeEach ) {
123 return orgBeforeEach.apply( this, arguments );
124 }
125 };
126 localEnv.afterEach = function () {
127 var ret;
128 if ( orgAfterEach ) {
129 ret = orgAfterEach.apply( this, arguments );
130 }
131 this.sandbox.verifyAndRestore();
132 this.fixture.parentNode.removeChild( this.fixture );
133 return ret;
134 };
135
136 return orgModule( name, localEnv, executeNow );
137 };
138 }() );
139
140 /**
141 * Reset mw.config and others to a fresh copy of the live config for each test(),
142 * and restore it back to the live one afterwards.
143 *
144 * @param {Object} [localEnv]
145 * @example (see test suite at the bottom of this file)
146 * </code>
147 */
148 QUnit.newMwEnvironment = ( function () {
149 var warn, error, liveConfig, liveMessages,
150 MwMap = mw.config.constructor, // internal use only
151 ajaxRequests = [];
152
153 liveConfig = mw.config;
154 liveMessages = mw.messages;
155
156 function suppressWarnings() {
157 if ( warn === undefined ) {
158 warn = mw.log.warn;
159 error = mw.log.error;
160 mw.log.warn = mw.log.error = $.noop;
161 }
162 }
163
164 function restoreWarnings() {
165 // Guard against calls not balanced with suppressWarnings()
166 if ( warn !== undefined ) {
167 mw.log.warn = warn;
168 mw.log.error = error;
169 warn = error = undefined;
170 }
171 }
172
173 function freshConfigCopy( custom ) {
174 var copy;
175 // Tests should mock all factors that directly influence the tested code.
176 // For backwards compatibility though we set mw.config to a fresh copy of the live
177 // config. This way any modifications made to mw.config during the test will not
178 // affect other tests, nor the global scope outside the test runner.
179 // This is a shallow copy, since overriding an array or object value via "custom"
180 // should replace it. Setting a config property means you override it, not extend it.
181 // NOTE: It is important that we suppress warnings because extend() will also access
182 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
183 suppressWarnings();
184 copy = $.extend( {}, liveConfig.get(), custom );
185 restoreWarnings();
186
187 return copy;
188 }
189
190 function freshMessagesCopy( custom ) {
191 return $.extend( /* deep */true, {}, liveMessages.get(), custom );
192 }
193
194 /**
195 * @param {jQuery.Event} event
196 * @param {jqXHR} jqXHR
197 * @param {Object} ajaxOptions
198 */
199 function trackAjax( event, jqXHR, ajaxOptions ) {
200 ajaxRequests.push( { xhr: jqXHR, options: ajaxOptions } );
201 }
202
203 return function ( orgEnv ) {
204 var localEnv, orgBeforeEach, orgAfterEach;
205
206 localEnv = makeSafeEnv( orgEnv );
207 // MediaWiki env testing
208 localEnv.config = localEnv.config || {};
209 localEnv.messages = localEnv.messages || {};
210
211 orgBeforeEach = localEnv.beforeEach;
212 orgAfterEach = localEnv.afterEach;
213
214 localEnv.beforeEach = function () {
215 // Greetings, mock environment!
216 mw.config = new MwMap();
217 mw.config.set( freshConfigCopy( localEnv.config ) );
218 mw.messages = new MwMap();
219 mw.messages.set( freshMessagesCopy( localEnv.messages ) );
220 // Update reference to mw.messages
221 mw.jqueryMsg.setParserDefaults( {
222 messages: mw.messages
223 } );
224
225 this.suppressWarnings = suppressWarnings;
226 this.restoreWarnings = restoreWarnings;
227
228 // Start tracking ajax requests
229 $( document ).on( 'ajaxSend', trackAjax );
230
231 if ( orgBeforeEach ) {
232 return orgBeforeEach.apply( this, arguments );
233 }
234 };
235 localEnv.afterEach = function () {
236 var timers, pending, $activeLen, ret;
237
238 if ( orgAfterEach ) {
239 ret = orgAfterEach.apply( this, arguments );
240 }
241
242 // Stop tracking ajax requests
243 $( document ).off( 'ajaxSend', trackAjax );
244
245 // As a convenience feature, automatically restore warnings if they're
246 // still suppressed by the end of the test.
247 restoreWarnings();
248
249 // Farewell, mock environment!
250 mw.config = liveConfig;
251 mw.messages = liveMessages;
252 // Restore reference to mw.messages
253 mw.jqueryMsg.setParserDefaults( {
254 messages: liveMessages
255 } );
256
257 // Tests should use fake timers or wait for animations to complete
258 // Check for incomplete animations/requests/etc and throw if there are any.
259 if ( $.timers && $.timers.length !== 0 ) {
260 timers = $.timers.length;
261 $.each( $.timers, function ( i, timer ) {
262 var node = timer.elem;
263 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
264 mw.html.element( node.nodeName.toLowerCase(), $( node ).getAttrs() )
265 );
266 } );
267 // Force animations to stop to give the next test a clean start
268 $.timers = [];
269 $.fx.stop();
270
271 throw new Error( 'Unfinished animations: ' + timers );
272 }
273
274 // Test should use fake XHR, wait for requests, or call abort()
275 $activeLen = $.active;
276 if ( $activeLen !== undefined && $activeLen !== 0 ) {
277 pending = ajaxRequests.filter( function ( ajax ) {
278 return ajax.xhr.state() === 'pending';
279 } );
280 if ( pending.length !== $activeLen ) {
281 mw.log.warn( 'Pending requests does not match jQuery.active count' );
282 }
283 // Force requests to stop to give the next test a clean start
284 ajaxRequests.forEach( function ( ajax, i ) {
285 mw.log.warn(
286 'AJAX request #' + i + ' (state: ' + ajax.xhr.state() + ')',
287 ajax.options
288 );
289 ajax.xhr.abort();
290 } );
291 ajaxRequests = [];
292
293 throw new Error( 'Pending AJAX requests: ' + pending.length + ' (active: ' + $activeLen + ')' );
294 }
295
296 return ret;
297 };
298 return localEnv;
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 this.pushResult( {
371 result: actual === true,
372 actual: actual,
373 expected: true,
374 message: message
375 } );
376 },
377
378 // Expect boolean false
379 assertFalse: function ( actual, message ) {
380 this.pushResult( {
381 result: actual === false,
382 actual: actual,
383 expected: false,
384 message: message
385 } );
386 },
387
388 // Expect numerical value less than X
389 lt: function ( actual, expected, message ) {
390 this.pushResult( {
391 result: actual < expected,
392 actual: actual,
393 expected: 'less than ' + expected,
394 message: message
395 } );
396 },
397
398 // Expect numerical value less than or equal to X
399 ltOrEq: function ( actual, expected, message ) {
400 this.pushResult( {
401 result: actual <= expected,
402 actual: actual,
403 expected: 'less than or equal to ' + expected,
404 message: message
405 } );
406 },
407
408 // Expect numerical value greater than X
409 gt: function ( actual, expected, message ) {
410 this.pushResult( {
411 result: actual > expected,
412 actual: actual,
413 expected: 'greater than ' + expected,
414 message: message
415 } );
416 },
417
418 // Expect numerical value greater than or equal to X
419 gtOrEq: function ( actual, expected, message ) {
420 this.pushResult( {
421 result: actual >= true,
422 actual: actual,
423 expected: 'greater than or equal to ' + expected,
424 message: message
425 } );
426 },
427
428 /**
429 * Asserts that two HTML strings are structurally equivalent.
430 *
431 * @param {string} actualHtml Actual HTML markup.
432 * @param {string} expectedHtml Expected HTML markup
433 * @param {string} message Assertion message.
434 */
435 htmlEqual: function ( actualHtml, expectedHtml, message ) {
436 var actual = getHtmlStructure( actualHtml ),
437 expected = getHtmlStructure( expectedHtml );
438 this.pushResult( {
439 result: QUnit.equiv( actual, expected ),
440 actual: actual,
441 expected: expected,
442 message: message
443 } );
444 },
445
446 /**
447 * Asserts that two HTML strings are not structurally equivalent.
448 *
449 * @param {string} actualHtml Actual HTML markup.
450 * @param {string} expectedHtml Expected HTML markup.
451 * @param {string} message Assertion message.
452 */
453 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
454 var actual = getHtmlStructure( actualHtml ),
455 expected = getHtmlStructure( expectedHtml );
456
457 this.pushResult( {
458 result: !QUnit.equiv( actual, expected ),
459 actual: actual,
460 expected: expected,
461 message: message,
462 negative: true
463 } );
464 }
465 };
466
467 $.extend( QUnit.assert, addons );
468
469 /**
470 * Small test suite to confirm proper functionality of the utilities and
471 * initializations defined above in this file.
472 */
473 QUnit.module( 'testrunner', QUnit.newMwEnvironment( {
474 setup: function () {
475 this.mwHtmlLive = mw.html;
476 mw.html = {
477 escape: function () {
478 return 'mocked';
479 }
480 };
481 },
482 teardown: function () {
483 mw.html = this.mwHtmlLive;
484 },
485 config: {
486 testVar: 'foo'
487 },
488 messages: {
489 testMsg: 'Foo.'
490 }
491 } ) );
492
493 QUnit.test( 'Setup', function ( assert ) {
494 assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
495 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
496 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
497
498 mw.config.set( 'testVar', 'bar' );
499 mw.messages.set( 'testMsg', 'Bar.' );
500 } );
501
502 QUnit.test( 'Teardown', function ( assert ) {
503 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
504 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
505 } );
506
507 QUnit.test( 'Loader status', function ( assert ) {
508 var i, len, state,
509 modules = mw.loader.getModuleNames(),
510 error = [],
511 missing = [];
512
513 for ( i = 0, len = modules.length; i < len; i++ ) {
514 state = mw.loader.getState( modules[ i ] );
515 if ( state === 'error' ) {
516 error.push( modules[ i ] );
517 } else if ( state === 'missing' ) {
518 missing.push( modules[ i ] );
519 }
520 }
521
522 assert.deepEqual( error, [], 'Modules in error state' );
523 assert.deepEqual( missing, [], 'Modules in missing state' );
524 } );
525
526 QUnit.test( 'assert.htmlEqual', function ( assert ) {
527 assert.htmlEqual(
528 '<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>',
529 '<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>',
530 'Attribute order, spacing and quotation marks (equal)'
531 );
532
533 assert.notHtmlEqual(
534 '<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>',
535 '<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>',
536 'Attribute order, spacing and quotation marks (not equal)'
537 );
538
539 assert.htmlEqual(
540 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
541 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
542 'Multiple root nodes (equal)'
543 );
544
545 assert.notHtmlEqual(
546 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
547 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
548 'Multiple root nodes (not equal, last label node is different)'
549 );
550
551 assert.htmlEqual(
552 'fo&quot;o<br/>b&gt;ar',
553 'fo"o<br/>b>ar',
554 'Extra escaping is equal'
555 );
556 assert.notHtmlEqual(
557 'foo&lt;br/&gt;bar',
558 'foo<br/>bar',
559 'Text escaping (not equal)'
560 );
561
562 assert.htmlEqual(
563 'foo<a href="http://example.com">example</a>bar',
564 'foo<a href="http://example.com">example</a>bar',
565 'Outer text nodes are compared (equal)'
566 );
567
568 assert.notHtmlEqual(
569 'foo<a href="http://example.com">example</a>bar',
570 'foo<a href="http://example.com">example</a>quux',
571 'Outer text nodes are compared (last text node different)'
572 );
573 } );
574
575 QUnit.module( 'testrunner-after', QUnit.newMwEnvironment() );
576
577 QUnit.test( 'Teardown', function ( assert ) {
578 assert.equal( mw.html.escape( '<' ), '&lt;', 'teardown() callback was ran.' );
579 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
580 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
581 } );
582
583 QUnit.module( 'testrunner-each', {
584 beforeEach: function () {
585 this.mwHtmlLive = mw.html;
586 },
587 afterEach: function () {
588 mw.html = this.mwHtmlLive;
589 }
590 } );
591 QUnit.test( 'beforeEach', function ( assert ) {
592 assert.ok( this.mwHtmlLive, 'setup() ran' );
593 mw.html = null;
594 } );
595 QUnit.test( 'afterEach', function ( assert ) {
596 assert.equal( mw.html.escape( '<' ), '&lt;', 'afterEach() ran' );
597 } );
598
599 QUnit.module( 'testrunner-each-compat', {
600 setup: function () {
601 this.mwHtmlLive = mw.html;
602 },
603 teardown: function () {
604 mw.html = this.mwHtmlLive;
605 }
606 } );
607 QUnit.test( 'setup', function ( assert ) {
608 assert.ok( this.mwHtmlLive, 'setup() ran' );
609 mw.html = null;
610 } );
611 QUnit.test( 'teardown', function ( assert ) {
612 assert.equal( mw.html.escape( '<' ), '&lt;', 'teardown() ran' );
613 } );
614
615 // Regression test for 'this.sandbox undefined' error, fixed by
616 // ensuring Sinon setup/teardown is not re-run on inner module.
617 QUnit.module( 'testrunner-nested', function () {
618 QUnit.module( 'testrunner-nested-inner', function () {
619 QUnit.test( 'Dummy', function ( assert ) {
620 assert.ok( true, 'Nested modules supported' );
621 } );
622 } );
623 } );
624
625 QUnit.module( 'testrunner-hooks-outer', function () {
626 var beforeHookWasExecuted = false,
627 afterHookWasExecuted = false;
628 QUnit.module( 'testrunner-hooks', {
629 before: function () {
630 beforeHookWasExecuted = true;
631
632 // This way we can be sure that module `testrunner-hook-after` will always
633 // be executed after module `testrunner-hooks`
634 QUnit.module( 'testrunner-hooks-after' );
635 QUnit.test(
636 '`after` hook for module `testrunner-hooks` was executed',
637 function ( assert ) {
638 assert.ok( afterHookWasExecuted );
639 }
640 );
641 },
642 after: function () {
643 afterHookWasExecuted = true;
644 }
645 } );
646
647 QUnit.test( '`before` hook was executed', function ( assert ) {
648 assert.ok( beforeHookWasExecuted );
649 } );
650 } );
651
652 }( jQuery, mediaWiki, QUnit ) );