Merge "Added more filter options to $wgRCFeeds"
[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,
7 addons,
8 envExecCount,
9 ELEMENT_NODE = 1,
10 TEXT_NODE = 3;
11
12 /**
13 * Add bogus to url to prevent IE crazy caching
14 *
15 * @param value {String} a relative path (eg. 'data/foo.js'
16 * or 'data/test.php?foo=bar').
17 * @return {String} Such as 'data/foo.js?131031765087663960'
18 */
19 QUnit.fixurl = function ( value ) {
20 return value + (/\?/.test( value ) ? '&' : '?')
21 + String( new Date().getTime() )
22 + String( parseInt( Math.random() * 100000, 10 ) );
23 };
24
25 /**
26 * Configuration
27 */
28
29 // When a test() indicates asynchronicity with stop(),
30 // allow 10 seconds to pass before killing the test(),
31 // and assuming failure.
32 QUnit.config.testTimeout = 10 * 1000;
33
34 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
35 QUnit.config.urlConfig.push( {
36 id: 'debug',
37 label: 'Enable ResourceLoaderDebug',
38 tooltip: 'Enable debug mode in ResourceLoader'
39 } );
40
41 QUnit.config.requireExpects = true;
42
43 /**
44 * Load TestSwarm agent
45 */
46 // Only if the current url indicates that there is a TestSwarm instance watching us
47 // (TestSwarm appends swarmURL to the test suites url it loads in iframes).
48 // Otherwise this is just a simple view of Special:JavaScriptTest/qunit directly,
49 // no point in loading inject.js in that case. Also, make sure that this instance
50 // of MediaWiki has actually been configured with the required url to that inject.js
51 // script. By default it is false.
52 if ( QUnit.urlParams.swarmURL && mw.config.get( 'QUnitTestSwarmInjectJSPath' ) ) {
53 jQuery.getScript( QUnit.fixurl( mw.config.get( 'QUnitTestSwarmInjectJSPath' ) ) );
54 }
55
56 /**
57 * CompletenessTest
58 *
59 * Adds toggle checkbox to header
60 */
61 QUnit.config.urlConfig.push( {
62 id: 'completenesstest',
63 label: 'Run CompletenessTest',
64 tooltip: 'Run the completeness test'
65 } );
66
67 /**
68 * SinonJS
69 *
70 * Glue code for nicer integration with QUnit setup/teardown
71 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
72 * Fixes:
73 * - Work properly with asynchronous QUnit by using module setup/teardown
74 * instead of synchronously wrapping QUnit.test.
75 */
76 sinon.assert.fail = function ( msg ) {
77 QUnit.assert.ok( false, msg );
78 };
79 sinon.assert.pass = function ( msg ) {
80 QUnit.assert.ok( true, msg );
81 };
82 sinon.config = {
83 injectIntoThis: true,
84 injectInto: null,
85 properties: ['spy', 'stub', 'mock', 'sandbox'],
86 // Don't fake timers by default
87 useFakeTimers: false,
88 useFakeServer: false
89 };
90 ( function () {
91 var orgModule = QUnit.module;
92
93 QUnit.module = function ( name, localEnv ) {
94 localEnv = localEnv || {};
95 orgModule( name, {
96 setup: function () {
97 var config = sinon.getConfig( sinon.config );
98 config.injectInto = this;
99 sinon.sandbox.create( config );
100
101 if ( localEnv.setup ) {
102 localEnv.setup.call( this );
103 }
104 },
105 teardown: function () {
106 this.sandbox.verifyAndRestore();
107
108 if ( localEnv.teardown ) {
109 localEnv.teardown.call( this );
110 }
111 }
112 } );
113 };
114 }() );
115
116 // Initiate when enabled
117 if ( QUnit.urlParams.completenesstest ) {
118
119 // Return true to ignore
120 mwTestIgnore = function ( val, tester ) {
121
122 // Don't record methods of the properties of constructors,
123 // to avoid getting into a loop (prototype.constructor.prototype..).
124 // Since we're therefor skipping any injection for
125 // "new mw.Foo()", manually set it to true here.
126 if ( val instanceof mw.Map ) {
127 tester.methodCallTracker.Map = true;
128 return true;
129 }
130 if ( val instanceof mw.Title ) {
131 tester.methodCallTracker.Title = true;
132 return true;
133 }
134
135 // Don't record methods of the properties of a jQuery object
136 if ( val instanceof $ ) {
137 return true;
138 }
139
140 return false;
141 };
142
143 mwTester = new CompletenessTest( mw, mwTestIgnore );
144 }
145
146 /**
147 * Test environment recommended for all QUnit test modules
148 *
149 * Whether to log environment changes to the console
150 */
151 QUnit.config.urlConfig.push( 'mwlogenv' );
152
153 /**
154 * Reset mw.config and others to a fresh copy of the live config for each test(),
155 * and restore it back to the live one afterwards.
156 * @param localEnv {Object} [optional]
157 * @example (see test suite at the bottom of this file)
158 * </code>
159 */
160 QUnit.newMwEnvironment = ( function () {
161 var warn, log, liveConfig, liveMessages;
162
163 liveConfig = mw.config.values;
164 liveMessages = mw.messages.values;
165
166 function suppressWarnings() {
167 warn = mw.log.warn;
168 mw.log.warn = $.noop;
169 }
170
171 function restoreWarnings() {
172 if ( warn !== undefined ) {
173 mw.log.warn = warn;
174 warn = undefined;
175 }
176 }
177
178 function freshConfigCopy( custom ) {
179 var copy;
180 // Tests should mock all factors that directly influence the tested code.
181 // For backwards compatibility though we set mw.config to a fresh copy of the live
182 // config. This way any modifications made to mw.config during the test will not
183 // affect other tests, nor the global scope outside the test runner.
184 // This is a shallow copy, since overriding an array or object value via "custom"
185 // should replace it. Setting a config property means you override it, not extend it.
186 // NOTE: It is important that we suppress warnings because extend() will also access
187 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
188 suppressWarnings();
189 copy = $.extend( {}, liveConfig, custom );
190 restoreWarnings();
191
192 return copy;
193 }
194
195 function freshMessagesCopy( custom ) {
196 return $.extend( /*deep=*/true, {}, liveMessages, custom );
197 }
198
199 log = QUnit.urlParams.mwlogenv ? mw.log : function () {};
200
201 return function ( localEnv ) {
202 localEnv = $.extend( {
203 // QUnit
204 setup: $.noop,
205 teardown: $.noop,
206 // MediaWiki
207 config: {},
208 messages: {}
209 }, localEnv );
210
211 return {
212 setup: function () {
213 log( 'MwEnvironment> SETUP for "' + QUnit.config.current.module
214 + ': ' + QUnit.config.current.testName + '"' );
215
216 // Greetings, mock environment!
217 mw.config.values = freshConfigCopy( localEnv.config );
218 mw.messages.values = freshMessagesCopy( localEnv.messages );
219 this.suppressWarnings = suppressWarnings;
220 this.restoreWarnings = restoreWarnings;
221
222 localEnv.setup.call( this );
223 },
224
225 teardown: function () {
226 log( 'MwEnvironment> TEARDOWN for "' + QUnit.config.current.module
227 + ': ' + QUnit.config.current.testName + '"' );
228
229 localEnv.teardown.call( this );
230
231 // Farewell, mock environment!
232 mw.config.values = liveConfig;
233 mw.messages.values = liveMessages;
234
235 // As a convenience feature, automatically restore warnings if they're
236 // still suppressed by the end of the test.
237 restoreWarnings();
238 }
239 };
240 };
241 }() );
242
243 // $.when stops as soon as one fails, which makes sense in most
244 // practical scenarios, but not in a unit test where we really do
245 // need to wait until all of them are finished.
246 QUnit.whenPromisesComplete = function () {
247 var altPromises = [];
248
249 $.each( arguments, function ( i, arg ) {
250 var alt = $.Deferred();
251 altPromises.push( alt );
252
253 // Whether this one fails or not, forwards it to
254 // the 'done' (resolve) callback of the alternative promise.
255 arg.always( alt.resolve );
256 } );
257
258 return $.when.apply( $, altPromises );
259 };
260
261 /**
262 * Recursively convert a node to a plain object representing its structure.
263 * Only considers attributes and contents (elements and text nodes).
264 * Attribute values are compared strictly and not normalised.
265 *
266 * @param {Node} node
267 * @return {Object|string} Plain JavaScript value representing the node.
268 */
269 function getDomStructure( node ) {
270 var $node, children, processedChildren, i, len, el;
271 $node = $( node );
272 if ( node.nodeType === ELEMENT_NODE ) {
273 children = $node.contents();
274 processedChildren = [];
275 for ( i = 0, len = children.length; i < len; i++ ) {
276 el = children[i];
277 if ( el.nodeType === ELEMENT_NODE || el.nodeType === TEXT_NODE ) {
278 processedChildren.push( getDomStructure( el ) );
279 }
280 }
281
282 return {
283 tagName: node.tagName,
284 attributes: $node.getAttrs(),
285 contents: processedChildren
286 };
287 } else {
288 // Should be text node
289 return $node.text();
290 }
291 }
292
293 /**
294 * Gets structure of node for this HTML.
295 *
296 * @param {string} html HTML markup for one or more nodes.
297 */
298 function getHtmlStructure( html ) {
299 var el = $( '<div>' ).append( html )[0];
300 return getDomStructure( el );
301 }
302
303 /**
304 * Add-on assertion helpers
305 */
306 // Define the add-ons
307 addons = {
308
309 // Expect boolean true
310 assertTrue: function ( actual, message ) {
311 QUnit.push( actual === true, actual, true, message );
312 },
313
314 // Expect boolean false
315 assertFalse: function ( actual, message ) {
316 QUnit.push( actual === false, actual, false, message );
317 },
318
319 // Expect numerical value less than X
320 lt: function ( actual, expected, message ) {
321 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
322 },
323
324 // Expect numerical value less than or equal to X
325 ltOrEq: function ( actual, expected, message ) {
326 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
327 },
328
329 // Expect numerical value greater than X
330 gt: function ( actual, expected, message ) {
331 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
332 },
333
334 // Expect numerical value greater than or equal to X
335 gtOrEq: function ( actual, expected, message ) {
336 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
337 },
338
339 /**
340 * Asserts that two HTML strings are structurally equivalent.
341 *
342 * @param {string} actualHtml Actual HTML markup.
343 * @param {string} expectedHtml Expected HTML markup
344 * @param {string} message Assertion message.
345 */
346 htmlEqual: function ( actualHtml, expectedHtml, message ) {
347 var actual = getHtmlStructure( actualHtml ),
348 expected = getHtmlStructure( expectedHtml );
349
350 QUnit.push(
351 QUnit.equiv(
352 actual,
353 expected
354 ),
355 actual,
356 expected,
357 message
358 );
359 },
360
361 /**
362 * Asserts that two HTML strings are not structurally equivalent.
363 *
364 * @param {string} actualHtml Actual HTML markup.
365 * @param {string} expectedHtml Expected HTML markup.
366 * @param {string} message Assertion message.
367 */
368 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
369 var actual = getHtmlStructure( actualHtml ),
370 expected = getHtmlStructure( expectedHtml );
371
372 QUnit.push(
373 !QUnit.equiv(
374 actual,
375 expected
376 ),
377 actual,
378 expected,
379 message
380 );
381 }
382 };
383
384 $.extend( QUnit.assert, addons );
385
386 /**
387 * Small test suite to confirm proper functionality of the utilities and
388 * initializations defined above in this file.
389 */
390 envExecCount = 0;
391 QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
392 setup: function () {
393 envExecCount += 1;
394 this.mwHtmlLive = mw.html;
395 mw.html = {
396 escape: function () {
397 return 'mocked-' + envExecCount;
398 }
399 };
400 },
401 teardown: function () {
402 mw.html = this.mwHtmlLive;
403 },
404 config: {
405 testVar: 'foo'
406 },
407 messages: {
408 testMsg: 'Foo.'
409 }
410 } ) );
411
412 QUnit.test( 'Setup', 3, function ( assert ) {
413 assert.equal( mw.html.escape( 'foo' ), 'mocked-1', 'extra setup() callback was ran.' );
414 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
415 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
416
417 mw.config.set( 'testVar', 'bar' );
418 mw.messages.set( 'testMsg', 'Bar.' );
419 } );
420
421 QUnit.test( 'Teardown', 3, function ( assert ) {
422 assert.equal( mw.html.escape( 'foo' ), 'mocked-2', 'extra setup() callback was re-ran.' );
423 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
424 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
425 } );
426
427 QUnit.test( 'Loader status', 2, function ( assert ) {
428 var i, len, state,
429 modules = mw.loader.getModuleNames(),
430 error = [],
431 missing = [];
432
433 for ( i = 0, len = modules.length; i < len; i++ ) {
434 state = mw.loader.getState( modules[i] );
435 if ( state === 'error' ) {
436 error.push( modules[i] );
437 } else if ( state === 'missing' ) {
438 missing.push( modules[i] );
439 }
440 }
441
442 assert.deepEqual( error, [], 'Modules in error state' );
443 assert.deepEqual( missing, [], 'Modules in missing state' );
444 } );
445
446 QUnit.test( 'htmlEqual', 8, function ( assert ) {
447 assert.htmlEqual(
448 '<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>',
449 '<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>',
450 'Attribute order, spacing and quotation marks (equal)'
451 );
452
453 assert.notHtmlEqual(
454 '<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>',
455 '<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>',
456 'Attribute order, spacing and quotation marks (not equal)'
457 );
458
459 assert.htmlEqual(
460 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
461 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
462 'Multiple root nodes (equal)'
463 );
464
465 assert.notHtmlEqual(
466 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
467 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
468 'Multiple root nodes (not equal, last label node is different)'
469 );
470
471 assert.htmlEqual(
472 'fo&quot;o<br/>b&gt;ar',
473 'fo"o<br/>b>ar',
474 'Extra escaping is equal'
475 );
476 assert.notHtmlEqual(
477 'foo&lt;br/&gt;bar',
478 'foo<br/>bar',
479 'Text escaping (not equal)'
480 );
481
482 assert.htmlEqual(
483 'foo<a href="http://example.com">example</a>bar',
484 'foo<a href="http://example.com">example</a>bar',
485 'Outer text nodes are compared (equal)'
486 );
487
488 assert.notHtmlEqual(
489 'foo<a href="http://example.com">example</a>bar',
490 'foo<a href="http://example.com">example</a>quux',
491 'Outer text nodes are compared (last text node different)'
492 );
493
494 } );
495
496 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
497
498 QUnit.test( 'Teardown', 3, function ( assert ) {
499 assert.equal( mw.html.escape( '<' ), '&lt;', 'extra teardown() callback was ran.' );
500 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
501 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
502 } );
503
504 }( jQuery, mediaWiki, QUnit ) );