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