Debian Codegraph @

tests/qunit/data/testrunner.js

raw symbols SCIP
1 ( function () {
2 'use strict';
3
4 // For each test that is asynchronous, allow this time to pass before
5 // killing the test and assuming timeout failure.
6 QUnit.config.testTimeout = 60 * 1000;
7
8 QUnit.dump.maxDepth = QUnit.config.maxDepth = 20;
9
10 // Reduce default animation duration from 400ms to 0ms for unit tests
11 // eslint-disable-next-line no-underscore-dangle
12 $.fx.speeds._default = 0;
13
14 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
15 QUnit.config.urlConfig.push( {
16 id: 'debug',
17 label: 'Enable ResourceLoaderDebug',
18 tooltip: 'Enable debug mode in ResourceLoader',
19 value: 'true'
20 } );
21
22 // Integrate SinonJS with QUnit
23 //
24 // - Add a Sinon sandbox to the test context that is automatically
25 // restored at the end of each test.
26 // - Forward sinon assertions to QUnit.
27 //
28 // Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
29 sinon.assert.fail = function ( msg ) {
30 QUnit.assert.true( false, msg );
31 };
32 sinon.assert.pass = function ( msg ) {
33 QUnit.assert.true( true, msg );
34 };
35 sinon.config = {
36 injectIntoThis: true,
37 injectInto: null,
38 properties: [ 'spy', 'stub', 'mock', 'sandbox' ],
39 // Don't fake timers by default
40 useFakeTimers: false,
41 useFakeServer: false
42 };
43 QUnit.hooks.beforeEach( function () {
44 // Sinon sandbox
45 const config = sinon.getConfig( sinon.config );
46 config.injectInto = this;
47 sinon.sandbox.create( config );
48 } );
49 QUnit.hooks.afterEach( function () {
50 this.sandbox.verifyAndRestore();
51 } );
52
53 const deepClone = typeof structuredClone === 'function' ? structuredClone : function ( obj ) {
54 return $.extend( /* deep */ true, {}, obj );
55 };
56
57 const liveConfig = mw.config.values;
58 const liveMessages = mw.messages.values;
59 const liveWarnFn = mw.log.warn;
60 const liveErrorFn = mw.log.error;
61 const noopFn = function () {};
62
63 function suppressWarnings() {
64 mw.log.warn = mw.log.error = noopFn;
65 }
66
67 function restoreWarnings() {
68 mw.log.warn = liveWarnFn;
69 mw.log.error = liveErrorFn;
70 }
71
72 /**
73 * Ensure mw.config and other `mw` singleton state is prestine for each test.
74 *
75 * Example:
76 *
77 * QUnit.module('mw.myModule', QUnit.newMwEnvironment() );
78 *
79 * QUnit.module('mw.myModule', QUnit.newMwEnvironment( {
80 * config: {
81 * wgServer: 'https://example.org'
82 * },
83 * messages: {
84 * 'monday-short': 'Monday'
85 * }
86 * } );
87 *
88 * @param {Object} [localEnv]
89 * @param {Object} [localEnv.config]
90 * @param {Object} [localEnv.messages]
91 */
92 QUnit.newMwEnvironment = function newMwEnvironment( localEnv ) {
93 localEnv = localEnv || {};
94
95 const orgBeforeEach = localEnv.beforeEach;
96 const orgAfterEach = localEnv.afterEach;
97
98 localEnv.beforeEach = function () {
99 mw.config.values = deepClone( liveConfig );
100 if ( localEnv.config ) {
101 mw.config.set( localEnv.config );
102 }
103
104 // Start with a clean message store.
105 // Optimization: Use fast empty object instead of deep clone to preserve
106 // server response (on mediawiki-wmf-quibble with 2000 tests, reduces
107 // newMwEnvironment_beforeEach from 3.7s to 0.7s). ResourceLoader runs
108 // tests with lang=qqx so tests shouldn't rely on these anyway.
109 mw.messages.values = {};
110 if ( localEnv.messages ) {
111 mw.messages.set( localEnv.messages );
112 }
113
114 this.suppressWarnings = suppressWarnings;
115 this.restoreWarnings = restoreWarnings;
116
117 if ( orgBeforeEach ) {
118 return orgBeforeEach.apply( this, arguments );
119 }
120 };
121 localEnv.afterEach = function () {
122 let ret;
123 if ( orgAfterEach ) {
124 ret = orgAfterEach.apply( this, arguments );
125 }
126
127 // For convenience and to avoid leakage, always restore after each test.
128 // Restoring earlier is allowed.
129 restoreWarnings();
130
131 mw.config.values = liveConfig;
132 mw.messages.values = liveMessages;
133
134 // Stop animations to ensure a clean start for the next test
135 $.timers = [];
136 $.fx.stop();
137
138 return ret;
139 };
140 return localEnv;
141 };
142
143 /**
144 * Wait for multiple promises to have finished.
145 *
146 * This differs from `$.when`, which stops as soon as one fails,
147 * which makes sense in a production context, but not in a test
148 * where we really do need to wait until all are finished before
149 * moving on.
150 *
151 * @return {jQuery.Promise}
152 */
153 QUnit.whenPromisesComplete = function () {
154 const altPromises = [];
155
156 // eslint-disable-next-line no-jquery/no-each-util
157 $.each( arguments, ( i, arg ) => {
158 const alt = $.Deferred();
159 altPromises.push( alt );
160
161 // Whether this one fails or not, forwards it to
162 // the 'done' (resolve) callback of the alternative promise.
163 arg.always( alt.resolve );
164 } );
165
166 return $.when( ...altPromises );
167 };
168
169 /**
170 * Recursively convert a node to a plain object representing its structure.
171 * Only considers attributes and contents (elements and text nodes).
172 * Attribute values are compared strictly and not normalised.
173 *
174 * @param {Node} node
175 * @return {Object|string} Plain JavaScript value representing the node.
176 */
177 function getDomStructure( node ) {
178 if ( node.nodeType === Node.ELEMENT_NODE ) {
179 const processedChildren = [];
180 $( node ).contents().each( ( i, el ) => {
181 if ( el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.TEXT_NODE ) {
182 processedChildren.push( getDomStructure( el ) );
183 }
184 } );
185
186 const attribs = {};
187 // eslint-disable-next-line no-jquery/no-each-util
188 $.each( node.attributes, ( i, attrib ) => {
189 attribs[ attrib.name ] = attrib.value;
190 } );
191
192 return {
193 tagName: node.tagName,
194 attributes: attribs,
195 contents: processedChildren
196 };
197 } else {
198 // Should be text node
199 return node.textContent;
200 }
201 }
202
203 /**
204 * Get structure of node for this HTML.
205 *
206 * @param {string} html HTML markup for one or more nodes.
207 * @return {Object}
208 */
209 function getHtmlStructure( html ) {
210 const el = $( '<div>' ).append( html )[ 0 ];
211 return getDomStructure( el );
212 }
213
214 const addons = {
215
216 /**
217 * Assert numerical value less than X
218 *
219 * @param {Mixed} actual
220 * @param {number} expected
221 * @param {string} [message]
222 */
223 lt: function ( actual, expected, message ) {
224 this.pushResult( {
225 result: actual < expected,
226 actual: actual,
227 expected: 'less than ' + expected,
228 message: message
229 } );
230 },
231
232 /**
233 * Assert numerical value less than or equal to X
234 *
235 * @param {Mixed} actual
236 * @param {number} expected
237 * @param {string} [message]
238 */
239 ltOrEq: function ( actual, expected, message ) {
240 this.pushResult( {
241 result: actual <= expected,
242 actual: actual,
243 expected: 'less than or equal to ' + expected,
244 message: message
245 } );
246 },
247
248 /**
249 * Assert numerical value greater than X
250 *
251 * @param {Mixed} actual
252 * @param {number} expected
253 * @param {string} [message]
254 */
255 gt: function ( actual, expected, message ) {
256 this.pushResult( {
257 result: actual > expected,
258 actual: actual,
259 expected: 'greater than ' + expected,
260 message: message
261 } );
262 },
263
264 /**
265 * Assert numerical value greater than or equal to X
266 *
267 * @param {Mixed} actual
268 * @param {number} expected
269 * @param {string} [message]
270 */
271 gtOrEq: function ( actual, expected, message ) {
272 this.pushResult( {
273 result: actual >= true,
274 actual: actual,
275 expected: 'greater than or equal to ' + expected,
276 message: message
277 } );
278 },
279
280 /**
281 * Asserts that two DOM nodes are structurally equivalent.
282 *
283 * @param {HTMLElement} actual
284 * @param {Object} expectedStruct
285 * @param {string} message Assertion message.
286 */
287 domEqual: function ( actual, expectedStruct, message ) {
288 const actualStruct = getDomStructure( actual );
289 this.pushResult( {
290 result: QUnit.equiv( actualStruct, expectedStruct ),
291 actual: actualStruct,
292 expected: expectedStruct,
293 message: message
294 } );
295 },
296
297 /**
298 * Asserts that two HTML strings are structurally equivalent.
299 *
300 * @param {string} actualHtml Actual HTML markup.
301 * @param {string} expectedHtml Expected HTML markup
302 * @param {string} message Assertion message.
303 */
304 htmlEqual: function ( actualHtml, expectedHtml, message ) {
305 const actual = getHtmlStructure( actualHtml ),
306 expected = getHtmlStructure( expectedHtml );
307 this.pushResult( {
308 result: QUnit.equiv( actual, expected ),
309 actual: actual,
310 expected: expected,
311 message: message
312 } );
313 },
314
315 /**
316 * Asserts that two HTML strings are not 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 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
323 const actual = getHtmlStructure( actualHtml ),
324 expected = getHtmlStructure( expectedHtml );
325
326 this.pushResult( {
327 result: !QUnit.equiv( actual, expected ),
328 actual: actual,
329 expected: expected,
330 message: message,
331 negative: true
332 } );
333 }
334 };
335
336 Object.assign( QUnit.assert, addons );
337
338 QUnit.begin( () => {
339 // Run a few quick environment checks to make sure the above is all working correctly.
340 // We run this as a plugin callback with QUnit.onUncaughtException() instead of as
341 // a normal QUnit.module() or QUnit.test() because:
342 //
343 // 1. This way it always runs first, instead of out of order when using `seed`,
344 // or when reloading which runs previously failed tests first.
345 // 2. Reduce noise in the output.
346 // 3. Makes it actually run instead of skipped when selecting a single module,
347 // or re-running a single test.
348 const issues = [];
349 function ensure( ok, issue ) {
350 if ( !ok ) {
351 issues.push( issue );
352 }
353 }
354 const env = QUnit.newMwEnvironment( {
355 beforeEach: function () {
356 this.mwHtmlLive = mw.html;
357 mw.html = {
358 escape: function () {
359 return 'mocked';
360 }
361 };
362 },
363 afterEach: function () {
364 mw.html = this.mwHtmlLive;
365 },
366 config: {
367 testVar: 'foo'
368 },
369 messages: {
370 testMsg: 'Foo.'
371 }
372 } );
373
374 env.beforeEach();
375 ensure( mw.html.escape( 'foo' ) === 'mocked', 'newMwEnvironment did not call beforeEach()' );
376 ensure( mw.config.get( 'testVar' ) === 'foo', 'newMwEnvironment did not apply config' );
377 ensure( mw.messages.get( 'testMsg' ) === 'Foo.', 'newMwEnvironment did not apply messages' );
378
379 mw.config.set( 'testVar', 'bar' );
380 mw.messages.set( 'testMsg', 'Bar.' );
381 env.afterEach();
382 env.beforeEach();
383 ensure( mw.config.get( 'testVar' ) === 'foo', 'newMwEnvironment failed to restore config' );
384 ensure( mw.messages.get( 'testMsg' ) === 'Foo.', 'newMwEnvironment failed to restore messages' );
385
386 env.afterEach();
387 ensure( mw.html.escape( '<' ) === '&lt;', 'newMwEnvironment did not call afterEach()' );
388 ensure( mw.config.get( 'testVar' ) === null, 'newMwEnvironment leaks config' );
389 ensure( mw.messages.get( 'testMsg' ) === null, 'newMwEnvironment leaks messages' );
390
391 mw.loader.getModuleNames().forEach( ( name ) => {
392 const state = mw.loader.getState( name );
393 if ( state === 'error' ) {
394 issues.push( `Module "${ name }" in error state` );
395 } else if ( state === 'missing' ) {
396 issues.push( `Missing "${ name }" module dependency` );
397 }
398 } );
399
400 if ( issues.length ) {
401 QUnit.onUncaughtException( 'testrunner.js found the following issues:\n * ' + issues.join( '\n * ' ) );
402 }
403 } );
404
405 QUnit.module( 'testrunner', () => {
406 QUnit.test( 'assert.htmlEqual', ( assert ) => {
407 assert.htmlEqual(
408 '<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>',
409 '<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>',
410 'Attribute order, spacing and quotation marks (equal)'
411 );
412
413 assert.notHtmlEqual(
414 '<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>',
415 '<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>',
416 'Attribute order, spacing and quotation marks (not equal)'
417 );
418
419 assert.htmlEqual(
420 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
421 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
422 'Multiple root nodes (equal)'
423 );
424
425 assert.notHtmlEqual(
426 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
427 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
428 'Multiple root nodes (not equal, last label node is different)'
429 );
430
431 assert.htmlEqual(
432 'fo&quot;o<br/>b&gt;ar',
433 'fo"o<br/>b>ar',
434 'Extra escaping is equal'
435 );
436 assert.notHtmlEqual(
437 'foo&lt;br/&gt;bar',
438 'foo<br/>bar',
439 'Text escaping (not equal)'
440 );
441
442 assert.htmlEqual(
443 'foo<a href="http://example.com">example</a>bar',
444 'foo<a href="http://example.com">example</a>bar',
445 'Outer text nodes are compared (equal)'
446 );
447
448 assert.notHtmlEqual(
449 'foo<a href="http://example.com">example</a>bar',
450 'foo<a href="http://example.com">example</a>quux',
451 'Outer text nodes are compared (last text node different)'
452 );
453 } );
454 } );
455 }() );