Merge "Revert "Limit searches at 500 per page""
[lhc/web/wiklou.git] / tests / qunit / data / testrunner.js
1 /*global CompletenessTest, sinon */
2 /*jshint evil: true */
3 ( function ( $, mw, QUnit, undefined ) {
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', 'clock', '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 log, liveConfig, liveMessages;
162
163 liveConfig = mw.config.values;
164 liveMessages = mw.messages.values;
165
166 function freshConfigCopy( custom ) {
167 // Tests should mock all factors that directly influence the tested code.
168 // For backwards compatibility though we set mw.config to a copy of the live config
169 // and extend it with the (optionally) given custom settings for this test
170 // (instead of starting blank with only the given custmo settings).
171 // This is a shallow copy, so we don't end up with settings taking an array value
172 // extended with the custom settings - setting a config property means you override it,
173 // not extend it.
174 return $.extend( {}, liveConfig, custom );
175 }
176
177 function freshMessagesCopy( custom ) {
178 return $.extend( /*deep=*/true, {}, liveMessages, custom );
179 }
180
181 log = QUnit.urlParams.mwlogenv ? mw.log : function () {};
182
183 return function ( localEnv ) {
184 localEnv = $.extend( {
185 // QUnit
186 setup: $.noop,
187 teardown: $.noop,
188 // MediaWiki
189 config: {},
190 messages: {}
191 }, localEnv );
192
193 return {
194 setup: function () {
195 log( 'MwEnvironment> SETUP for "' + QUnit.config.current.module
196 + ': ' + QUnit.config.current.testName + '"' );
197
198 // Greetings, mock environment!
199 mw.config.values = freshConfigCopy( localEnv.config );
200 mw.messages.values = freshMessagesCopy( localEnv.messages );
201
202 localEnv.setup.call( this );
203 },
204
205 teardown: function () {
206 log( 'MwEnvironment> TEARDOWN for "' + QUnit.config.current.module
207 + ': ' + QUnit.config.current.testName + '"' );
208
209 localEnv.teardown.call( this );
210
211 // Farewell, mock environment!
212 mw.config.values = liveConfig;
213 mw.messages.values = liveMessages;
214 }
215 };
216 };
217 }() );
218
219 // $.when stops as soon as one fails, which makes sense in most
220 // practical scenarios, but not in a unit test where we really do
221 // need to wait until all of them are finished.
222 QUnit.whenPromisesComplete = function () {
223 var altPromises = [];
224
225 $.each( arguments, function ( i, arg ) {
226 var alt = $.Deferred();
227 altPromises.push( alt );
228
229 // Whether this one fails or not, forwards it to
230 // the 'done' (resolve) callback of the alternative promise.
231 arg.always( alt.resolve );
232 } );
233
234 return $.when.apply( $, altPromises );
235 };
236
237 /**
238 * Recursively convert a node to a plain object representing its structure.
239 * Only considers attributes and contents (elements and text nodes).
240 * Attribute values are compared strictly and not normalised.
241 *
242 * @param {Node} node
243 * @return {Object|string} Plain JavaScript value representing the node.
244 */
245 function getDomStructure( node ) {
246 var $node, children, processedChildren, i, len, el;
247 $node = $( node );
248 if ( node.nodeType === ELEMENT_NODE ) {
249 children = $node.contents();
250 processedChildren = [];
251 for ( i = 0, len = children.length; i < len; i++ ) {
252 el = children[i];
253 if ( el.nodeType === ELEMENT_NODE || el.nodeType === TEXT_NODE ) {
254 processedChildren.push( getDomStructure( el ) );
255 }
256 }
257
258 return {
259 tagName: node.tagName,
260 attributes: $node.getAttrs(),
261 contents: processedChildren
262 };
263 } else {
264 // Should be text node
265 return $node.text();
266 }
267 }
268
269 /**
270 * Gets structure of node for this HTML.
271 *
272 * @param {string} html HTML markup for one or more nodes.
273 */
274 function getHtmlStructure( html ) {
275 var el = $( '<div>' ).append( html )[0];
276 return getDomStructure( el );
277 }
278
279 /**
280 * Add-on assertion helpers
281 */
282 // Define the add-ons
283 addons = {
284
285 // Expect boolean true
286 assertTrue: function ( actual, message ) {
287 QUnit.push( actual === true, actual, true, message );
288 },
289
290 // Expect boolean false
291 assertFalse: function ( actual, message ) {
292 QUnit.push( actual === false, actual, false, message );
293 },
294
295 // Expect numerical value less than X
296 lt: function ( actual, expected, message ) {
297 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
298 },
299
300 // Expect numerical value less than or equal to X
301 ltOrEq: function ( actual, expected, message ) {
302 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
303 },
304
305 // Expect numerical value greater than X
306 gt: function ( actual, expected, message ) {
307 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
308 },
309
310 // Expect numerical value greater than or equal to X
311 gtOrEq: function ( actual, expected, message ) {
312 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
313 },
314
315 /**
316 * Asserts that two HTML strings are structurally equivalent.
317 *
318 * @param {string} actualHtml Actual HTML markup.
319 * @param {string} expectedHtml Expected HTML markup
320 * @param {string} message Assertion message.
321 */
322 htmlEqual: function ( actualHtml, expectedHtml, message ) {
323 var actual = getHtmlStructure( actualHtml ),
324 expected = getHtmlStructure( expectedHtml );
325
326 QUnit.push(
327 QUnit.equiv(
328 actual,
329 expected
330 ),
331 actual,
332 expected,
333 message
334 );
335 },
336
337 /**
338 * Asserts that two HTML strings are not structurally equivalent.
339 *
340 * @param {string} actualHtml Actual HTML markup.
341 * @param {string} expectedHtml Expected HTML markup.
342 * @param {string} message Assertion message.
343 */
344 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
345 var actual = getHtmlStructure( actualHtml ),
346 expected = getHtmlStructure( expectedHtml );
347
348 QUnit.push(
349 !QUnit.equiv(
350 actual,
351 expected
352 ),
353 actual,
354 expected,
355 message
356 );
357 }
358 };
359
360 $.extend( QUnit.assert, addons );
361
362 /**
363 * Small test suite to confirm proper functionality of the utilities and
364 * initializations defined above in this file.
365 */
366 envExecCount = 0;
367 QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
368 setup: function () {
369 envExecCount += 1;
370 this.mwHtmlLive = mw.html;
371 mw.html = {
372 escape: function () {
373 return 'mocked-' + envExecCount;
374 }
375 };
376 },
377 teardown: function () {
378 mw.html = this.mwHtmlLive;
379 },
380 config: {
381 testVar: 'foo'
382 },
383 messages: {
384 testMsg: 'Foo.'
385 }
386 } ) );
387
388 QUnit.test( 'Setup', 3, function ( assert ) {
389 assert.equal( mw.html.escape( 'foo' ), 'mocked-1', 'extra setup() callback was ran.' );
390 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
391 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
392
393 mw.config.set( 'testVar', 'bar' );
394 mw.messages.set( 'testMsg', 'Bar.' );
395 } );
396
397 QUnit.test( 'Teardown', 3, function ( assert ) {
398 assert.equal( mw.html.escape( 'foo' ), 'mocked-2', 'extra setup() callback was re-ran.' );
399 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
400 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
401 } );
402
403 QUnit.test( 'Loader status', 2, function ( assert ) {
404 var i, len, state,
405 modules = mw.loader.getModuleNames(),
406 error = [],
407 missing = [];
408
409 for ( i = 0, len = modules.length; i < len; i++ ) {
410 state = mw.loader.getState( modules[i] );
411 if ( state === 'error' ) {
412 error.push( modules[i] );
413 } else if ( state === 'missing' ) {
414 missing.push( modules[i] );
415 }
416 }
417
418 assert.deepEqual( error, [], 'Modules in error state' );
419 assert.deepEqual( missing, [], 'Modules in missing state' );
420 } );
421
422 QUnit.test( 'htmlEqual', 8, function ( assert ) {
423 assert.htmlEqual(
424 '<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>',
425 '<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>',
426 'Attribute order, spacing and quotation marks (equal)'
427 );
428
429 assert.notHtmlEqual(
430 '<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>',
431 '<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>',
432 'Attribute order, spacing and quotation marks (not equal)'
433 );
434
435 assert.htmlEqual(
436 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
437 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
438 'Multiple root nodes (equal)'
439 );
440
441 assert.notHtmlEqual(
442 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
443 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
444 'Multiple root nodes (not equal, last label node is different)'
445 );
446
447 assert.htmlEqual(
448 'fo&quot;o<br/>b&gt;ar',
449 'fo"o<br/>b>ar',
450 'Extra escaping is equal'
451 );
452 assert.notHtmlEqual(
453 'foo&lt;br/&gt;bar',
454 'foo<br/>bar',
455 'Text escaping (not equal)'
456 );
457
458 assert.htmlEqual(
459 'foo<a href="http://example.com">example</a>bar',
460 'foo<a href="http://example.com">example</a>bar',
461 'Outer text nodes are compared (equal)'
462 );
463
464 assert.notHtmlEqual(
465 'foo<a href="http://example.com">example</a>bar',
466 'foo<a href="http://example.com">example</a>quux',
467 'Outer text nodes are compared (last text node different)'
468 );
469
470 } );
471
472 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
473
474 QUnit.test( 'Teardown', 3, function ( assert ) {
475 assert.equal( mw.html.escape( '<' ), '&lt;', 'extra teardown() callback was ran.' );
476 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
477 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
478 } );
479
480 }( jQuery, mediaWiki, QUnit ) );