Merge "Fix default value of the SpecialWatchlistFilters hook"
[lhc/web/wiklou.git] / tests / qunit / data / testrunner.js
1 /*global CompletenessTest */
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 /**
42 * Load TestSwarm agent
43 */
44 // Only if the current url indicates that there is a TestSwarm instance watching us
45 // (TestSwarm appends swarmURL to the test suites url it loads in iframes).
46 // Otherwise this is just a simple view of Special:JavaScriptTest/qunit directly,
47 // no point in loading inject.js in that case. Also, make sure that this instance
48 // of MediaWiki has actually been configured with the required url to that inject.js
49 // script. By default it is false.
50 if ( QUnit.urlParams.swarmURL && mw.config.get( 'QUnitTestSwarmInjectJSPath' ) ) {
51 document.write( '<scr' + 'ipt src="' + QUnit.fixurl( mw.config.get( 'QUnitTestSwarmInjectJSPath' ) ) + '"></scr' + 'ipt>' );
52 }
53
54 /**
55 * CompletenessTest
56 */
57 // Adds toggle checkbox to header
58 QUnit.config.urlConfig.push( {
59 id: 'completenesstest',
60 label: 'Run CompletenessTest',
61 tooltip: 'Run the completeness test'
62 } );
63
64 // Initiate when enabled
65 if ( QUnit.urlParams.completenesstest ) {
66
67 // Return true to ignore
68 mwTestIgnore = function ( val, tester ) {
69
70 // Don't record methods of the properties of constructors,
71 // to avoid getting into a loop (prototype.constructor.prototype..).
72 // Since we're therefor skipping any injection for
73 // "new mw.Foo()", manually set it to true here.
74 if ( val instanceof mw.Map ) {
75 tester.methodCallTracker.Map = true;
76 return true;
77 }
78 if ( val instanceof mw.Title ) {
79 tester.methodCallTracker.Title = true;
80 return true;
81 }
82
83 // Don't record methods of the properties of a jQuery object
84 if ( val instanceof $ ) {
85 return true;
86 }
87
88 return false;
89 };
90
91 mwTester = new CompletenessTest( mw, mwTestIgnore );
92 }
93
94 /**
95 * Test environment recommended for all QUnit test modules
96 */
97 // Whether to log environment changes to the console
98 QUnit.config.urlConfig.push( 'mwlogenv' );
99
100 /**
101 * Reset mw.config and others to a fresh copy of the live config for each test(),
102 * and restore it back to the live one afterwards.
103 * @param localEnv {Object} [optional]
104 * @example (see test suite at the bottom of this file)
105 * </code>
106 */
107 QUnit.newMwEnvironment = ( function () {
108 var log, liveConfig, liveMessages;
109
110 liveConfig = mw.config.values;
111 liveMessages = mw.messages.values;
112
113 function freshConfigCopy( custom ) {
114 // Tests should mock all factors that directly influence the tested code.
115 // For backwards compatibility though we set mw.config to a copy of the live config
116 // and extend it with the (optionally) given custom settings for this test
117 // (instead of starting blank with only the given custmo settings).
118 // This is a shallow copy, so we don't end up with settings taking an array value
119 // extended with the custom settings - setting a config property means you override it,
120 // not extend it.
121 return $.extend( {}, liveConfig, custom );
122 }
123
124 function freshMessagesCopy( custom ) {
125 return $.extend( /*deep=*/true, {}, liveMessages, custom );
126 }
127
128 log = QUnit.urlParams.mwlogenv ? mw.log : function () {};
129
130 return function ( localEnv ) {
131 localEnv = $.extend( {
132 // QUnit
133 setup: $.noop,
134 teardown: $.noop,
135 // MediaWiki
136 config: {},
137 messages: {}
138 }, localEnv );
139
140 return {
141 setup: function () {
142 log( 'MwEnvironment> SETUP for "' + QUnit.config.current.module
143 + ': ' + QUnit.config.current.testName + '"' );
144
145 // Greetings, mock environment!
146 mw.config.values = freshConfigCopy( localEnv.config );
147 mw.messages.values = freshMessagesCopy( localEnv.messages );
148
149 localEnv.setup();
150 },
151
152 teardown: function () {
153 log( 'MwEnvironment> TEARDOWN for "' + QUnit.config.current.module
154 + ': ' + QUnit.config.current.testName + '"' );
155
156 localEnv.teardown();
157
158 // Farewell, mock environment!
159 mw.config.values = liveConfig;
160 mw.messages.values = liveMessages;
161 }
162 };
163 };
164 }() );
165
166 // $.when stops as soon as one fails, which makes sense in most
167 // practical scenarios, but not in a unit test where we really do
168 // need to wait until all of them are finished.
169 QUnit.whenPromisesComplete = function () {
170 var altPromises = [];
171
172 $.each( arguments, function ( i, arg ) {
173 var alt = $.Deferred();
174 altPromises.push( alt );
175
176 // Whether this one fails or not, forwards it to
177 // the 'done' (resolve) callback of the alternative promise.
178 arg.always( alt.resolve );
179 } );
180
181 return $.when.apply( $, altPromises );
182 };
183
184 /**
185 * Recursively convert a node to a plain object representing its structure.
186 * Only considers attributes and contents (elements and text nodes).
187 * Attribute values are compared strictly and not normalised.
188 *
189 * @param {Node} node
190 * @return {Object|string} Plain JavaScript value representing the node.
191 */
192 function getDomStructure( node ) {
193 var $node, children, processedChildren, i, len, el;
194 $node = $( node );
195 if ( node.nodeType === ELEMENT_NODE ) {
196 children = $node.contents();
197 processedChildren = [];
198 for ( i = 0, len = children.length; i < len; i++ ) {
199 el = children[i];
200 if ( el.nodeType === ELEMENT_NODE || el.nodeType === TEXT_NODE ) {
201 processedChildren.push( getDomStructure( el ) );
202 }
203 }
204
205 return {
206 tagName: node.tagName,
207 attributes: $node.getAttrs(),
208 contents: processedChildren
209 };
210 } else {
211 // Should be text node
212 return $node.text();
213 }
214 }
215
216 /**
217 * Gets structure of node for this HTML.
218 *
219 * @param {string} html HTML markup for one or more nodes.
220 */
221 function getHtmlStructure( html ) {
222 var el = $( '<div>' ).append( html )[0];
223 return getDomStructure( el );
224 }
225
226 /**
227 * Add-on assertion helpers
228 */
229 // Define the add-ons
230 addons = {
231
232 // Expect boolean true
233 assertTrue: function ( actual, message ) {
234 QUnit.push( actual === true, actual, true, message );
235 },
236
237 // Expect boolean false
238 assertFalse: function ( actual, message ) {
239 QUnit.push( actual === false, actual, false, message );
240 },
241
242 // Expect numerical value less than X
243 lt: function ( actual, expected, message ) {
244 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
245 },
246
247 // Expect numerical value less than or equal to X
248 ltOrEq: function ( actual, expected, message ) {
249 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
250 },
251
252 // Expect numerical value greater than X
253 gt: function ( actual, expected, message ) {
254 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
255 },
256
257 // Expect numerical value greater than or equal to X
258 gtOrEq: function ( actual, expected, message ) {
259 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
260 },
261
262 /**
263 * Asserts that two HTML strings are structurally equivalent.
264 *
265 * @param {string} actualHtml Actual HTML markup.
266 * @param {string} expectedHtml Expected HTML markup
267 * @param {string} message Assertion message.
268 */
269 htmlEqual: function ( actualHtml, expectedHtml, message ) {
270 var actual = getHtmlStructure( actualHtml ),
271 expected = getHtmlStructure( expectedHtml );
272
273 QUnit.push(
274 QUnit.equiv(
275 actual,
276 expected
277 ),
278 actual,
279 expected,
280 message
281 );
282 },
283
284 /**
285 * Asserts that two HTML strings are not structurally equivalent.
286 *
287 * @param {string} actualHtml Actual HTML markup.
288 * @param {string} expectedHtml Expected HTML markup.
289 * @param {string} message Assertion message.
290 */
291 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
292 var actual = getHtmlStructure( actualHtml ),
293 expected = getHtmlStructure( expectedHtml );
294
295 QUnit.push(
296 !QUnit.equiv(
297 actual,
298 expected
299 ),
300 actual,
301 expected,
302 message
303 );
304 }
305 };
306
307 $.extend( QUnit.assert, addons );
308
309 /**
310 * Small test suite to confirm proper functionality of the utilities and
311 * initializations defined above in this file.
312 */
313 envExecCount = 0;
314 QUnit.module( 'mediawiki.tests.qunit.testrunner', QUnit.newMwEnvironment( {
315 setup: function () {
316 envExecCount += 1;
317 this.mwHtmlLive = mw.html;
318 mw.html = {
319 escape: function () {
320 return 'mocked-' + envExecCount;
321 }
322 };
323 },
324 teardown: function () {
325 mw.html = this.mwHtmlLive;
326 },
327 config: {
328 testVar: 'foo'
329 },
330 messages: {
331 testMsg: 'Foo.'
332 }
333 } ) );
334
335 QUnit.test( 'Setup', 3, function ( assert ) {
336 assert.equal( mw.html.escape( 'foo' ), 'mocked-1', 'extra setup() callback was ran.' );
337 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
338 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
339
340 mw.config.set( 'testVar', 'bar' );
341 mw.messages.set( 'testMsg', 'Bar.' );
342 } );
343
344 QUnit.test( 'Teardown', 3, function ( assert ) {
345 assert.equal( mw.html.escape( 'foo' ), 'mocked-2', 'extra setup() callback was re-ran.' );
346 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
347 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
348 } );
349
350 QUnit.test( 'htmlEqual', 8, function ( assert ) {
351 assert.htmlEqual(
352 '<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>',
353 '<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>',
354 'Attribute order, spacing and quotation marks (equal)'
355 );
356
357 assert.notHtmlEqual(
358 '<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>',
359 '<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>',
360 'Attribute order, spacing and quotation marks (not equal)'
361 );
362
363 assert.htmlEqual(
364 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
365 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
366 'Multiple root nodes (equal)'
367 );
368
369 assert.notHtmlEqual(
370 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
371 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
372 'Multiple root nodes (not equal, last label node is different)'
373 );
374
375 assert.htmlEqual(
376 'fo&quot;o<br/>b&gt;ar',
377 'fo"o<br/>b>ar',
378 'Extra escaping is equal'
379 );
380 assert.notHtmlEqual(
381 'foo&lt;br/&gt;bar',
382 'foo<br/>bar',
383 'Text escaping (not equal)'
384 );
385
386 assert.htmlEqual(
387 'foo<a href="http://example.com">example</a>bar',
388 'foo<a href="http://example.com">example</a>bar',
389 'Outer text nodes are compared (equal)'
390 );
391
392 assert.notHtmlEqual(
393 'foo<a href="http://example.com">example</a>bar',
394 'foo<a href="http://example.com">example</a>quux',
395 'Outer text nodes are compared (last text node different)'
396 );
397
398 } );
399
400 QUnit.module( 'mediawiki.tests.qunit.testrunner-after', QUnit.newMwEnvironment() );
401
402 QUnit.test( 'Teardown', 3, function ( assert ) {
403 assert.equal( mw.html.escape( '<' ), '&lt;', 'extra teardown() callback was ran.' );
404 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
405 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
406 } );
407
408 }( jQuery, mediaWiki, QUnit ) );